@reqvire-org/ads 0.3.51 → 0.3.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/dist/assets.mjs +15 -1
  3. package/dist/browser-audit/axe-run.mjs +17 -0
  4. package/dist/browser-audit/first-render.mjs +22 -0
  5. package/dist/browser-audit/image-shape.mjs +36 -0
  6. package/dist/browser-audit/layout-overflow.mjs +11 -5
  7. package/dist/browser-audit/non-text-contrast.mjs +12 -7
  8. package/dist/browser-audit/render-states.mjs +208 -0
  9. package/dist/browser-audit/worker.mjs +60 -22
  10. package/dist/browser-audit.mjs +72 -12
  11. package/dist/bun-compiler.mjs +9 -1
  12. package/dist/check.mjs +4 -1
  13. package/dist/cli.mjs +9 -4
  14. package/dist/config.mjs +3 -1
  15. package/dist/finding-rules.mjs +14 -1
  16. package/dist/font-rules.mjs +103 -0
  17. package/dist/fonts-generated.mjs +30 -12
  18. package/dist/layout-widths.mjs +17 -8
  19. package/dist/mcp/preview-watch.mjs +2 -2
  20. package/dist/mcp/preview-widget.bundle.js +50 -47
  21. package/dist/mcp/project-widget.bundle.js +45 -42
  22. package/dist/mcp/server.mjs +4 -4
  23. package/dist/mcp/widget.bundle.js +49 -46
  24. package/dist/preview-resources.mjs +4 -1
  25. package/dist/scenarios-compiler.mjs +2 -2
  26. package/dist/showcase/client.bundle.js +27 -27
  27. package/dist/skills/ads-break-ui/references/design-data.md +8 -1
  28. package/dist/skills/ads-designer/SKILL.md +5 -3
  29. package/dist/skills/ads-designer/references/branding.md +2 -2
  30. package/dist/skills/ads-designer/references/design-data.md +8 -1
  31. package/dist/skills/ads-designer/references/performance.md +54 -4
  32. package/dist/skills/ads-import/references/design-data.md +8 -1
  33. package/dist/skills/ads-motion/references/design-data.md +8 -1
  34. package/dist/skills/ads-port/references/design-data.md +8 -1
  35. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +1 -1
  36. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +2 -2
  37. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
  38. package/docs/ARCHITECTURE.md +26 -2
  39. package/docs/CHANGELOG.md +92 -12
  40. package/docs/GUIDE.md +65 -9
  41. package/package.json +7 -7
@@ -43,7 +43,8 @@ export const containerWidth = 240;
43
43
  export const containerKinds = Object.freeze(["components", "patterns"]);
44
44
  /** Attempts for one render, against a dropped preview connection or a slow preview. */
45
45
  export const auditAttempts = 3;
46
- 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, contentQuietMs: 500, contentLimitMs: 5000 };
47
48
 
48
49
  /** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
49
50
  export function wcagCriteria(tags) {
@@ -95,6 +96,7 @@ export function incompleteFindings(runs, scenarios) {
95
96
  const nonTextKinds = {
96
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." },
97
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." },
98
100
  };
99
101
 
100
102
  /** Collapse per-brand, per-theme non-text contrast issues into ADS errors: one per scenario, kind
@@ -125,6 +127,23 @@ export function nonTextContrastFindings(runs, scenarios) {
125
127
  });
126
128
  }
127
129
 
130
+ const skipReasons = {
131
+ "overlay-did-not-open": "a control with aria-haspopup opened nothing with a dialog, menu or listbox role",
132
+ "overlay-trigger-gone": "a trigger left the page before its turn",
133
+ "overlay-left-open": "an overlay did not close on Escape, so later triggers could not be reached",
134
+ "overlay-timeout": "a trigger could not be clicked in time",
135
+ "overlay-detached": "a trigger left the page or was covered while it was being clicked",
136
+ "overlay-failed": "opening an overlay failed",
137
+ "overlay-cap": "the limit of 3 triggers per render was reached and no other scenario has them",
138
+ "control-gone": "a control left the page before its turn",
139
+ "control-timeout": "a control could not be hovered in time",
140
+ "control-detached": "a control left the page while it was being measured",
141
+ "control-failed": "measuring a control failed",
142
+ "control-cap": "the limit of 6 controls per render was reached and no other scenario has them",
143
+ "content-still-changing": "the page kept changing past 5 s, so what it measured may be mid-change",
144
+ "focus-not-reachable": "a control a keyboard cannot reach (aria-hidden, inert, or tabindex -1 outside a roving widget): hover measured, focus not",
145
+ };
146
+
128
147
  const overflowKinds = {
129
148
  document: { what: "the page scrolls horizontally", fix: "Find the element wider than its container; use fluid widths, min-width: 0 on flex and grid children, and let long text wrap." },
130
149
  viewport: { what: "content reaches past the viewport", fix: "Make the element fluid (%, fr, a --grid-span-N token in a container query), wrap it, or put it in an overflow-x: auto scroller." },
@@ -157,6 +176,45 @@ export function layoutOverflowFindings(runs, scenarios) {
157
176
  });
158
177
  }
159
178
 
179
+ /** One error per scenario and image rendered at a shape other than the one it declares. */
180
+ export function imageShapeFindings(runs, scenarios) {
181
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
182
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
183
+ for (const run of runs) for (const issue of run.imageShape ?? []) {
184
+ const key = JSON.stringify([run.scenario, issue.selector]);
185
+ const group = groups.get(key) ?? { scenario: run.scenario, issue, themes: [], brands: [] };
186
+ groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
187
+ }
188
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, issue, themes, brands }) => ({
189
+ rule: "img-shape", severity: findingSeverity("img-shape"), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", scenario, themes, ...(brands.length ? { brands } : {}), nodes: [issue], rendered: issue.rendered, declared: issue.declared, guidanceUri: "ads://guides/performance",
190
+ message: `Image shape in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${issue.selector} renders at ${issue.rendered} at the ${issue.width} px viewport but declares ${issue.declared}, so it is cropped or stretched. A height attribute beats aspect-ratio: add height: auto. For a deliberate crop in a box of its own, set object-fit and no aspect-ratio.`,
191
+ }));
192
+ }
193
+
194
+ /** What a run measured, and what it skipped and why: per reason, with a few examples. An info finding
195
+ * for each reason, and a review item for a render assigned targets that measured none of them. */
196
+ export function auditCoverage(runs, capped, scenarios) {
197
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), reasons = new Map();
198
+ const claimedNow = new Set(runs.flatMap(run => run.coverage?.claimed ?? []));
199
+ const note = (reason, example) => { const entry = reasons.get(reason) ?? { count: 0, examples: [] }; reasons.set(reason, entry); entry.count++; if (entry.examples.length < limits.nodes) entry.examples.push(example); };
200
+ for (const run of runs) for (const { reason, name } of run.coverage?.skipped ?? []) note(reason, { scenario: run.scenario, theme: run.theme, ...(run.brand ? { brand: run.brand } : {}), name });
201
+ for (const { claim, reason, ...example } of capped) if (!claimedNow.has(claim)) note(reason, example);
202
+ const coverage = { renders: runs.length, overlaysOpened: 0, controlsMeasured: 0, skipped: Object.fromEntries([...reasons].sort(([a], [b]) => a.localeCompare(b))) };
203
+ const empty = [];
204
+ for (const run of runs) if (run.coverage) {
205
+ coverage.overlaysOpened += run.coverage.overlays; coverage.controlsMeasured += run.coverage.controls;
206
+ // A trigger that opened nothing is not a failure to measure: that is a skip, and the rest of the render stands.
207
+ const failed = run.coverage.skipped.filter(item => /^(?:overlay|control)-(?:gone|timeout|detached|failed)$/.test(item.reason)).length;
208
+ if (failed && !run.coverage.overlays && !run.coverage.controls) empty.push(run);
209
+ }
210
+ const findings = [...reasons].map(([reason, { count, examples }]) => ({
211
+ rule: "browser-audit-skipped", severity: findingSeverity("browser-audit-skipped"), file: files.get(examples[0].scenario) ?? examples[0].scenario, line: 1, column: 1, source: "ads", reason, count, examples, guidanceUri: "ads://guides/accessibility",
212
+ message: `The audit skipped ${count} target${count === 1 ? "" : "s"}: ${skipReasons[reason] ?? reason}. ${examples.slice(0, 3).map(item => `"${item.name}" in ${item.scenario} [${item.theme}]`).join(", ")}${count > 3 ? ` and ${count - 3} more` : ""}.`,
213
+ }));
214
+ for (const run of empty) findings.push({ rule: "browser-audit-nothing-measured", severity: findingSeverity("browser-audit-nothing-measured"), file: files.get(run.scenario) ?? run.scenario, line: 1, column: 1, source: "ads", scenario: run.scenario, themes: [run.theme], message: `Nothing the audit tried to open or hover in ${run.scenario} [${run.theme}] could be measured: ${[...new Set(run.coverage.skipped.map(item => item.reason))].join(", ")}.` });
215
+ return { coverage, findings };
216
+ }
217
+
160
218
  /** One error per scenario above the threshold, with its worst score, themes, brands and elements. */
161
219
  export function layoutShiftFindings(runs, scenarios) {
162
220
  const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
@@ -198,7 +256,7 @@ export function auditScenarioSelection(options, changedFiles) {
198
256
  export function auditCheck(audit, extra = {}) {
199
257
  const routed = routeFindings([], audit.findings);
200
258
  return { routed, check: { name: "browser-accessibility-audit", passed: !routed.diagnostics.length, engine: audit.engine, scenarios: audit.scenarios, themes: audit.themes, ...(audit.brands ? { brands: audit.brands } : {}),
201
- renders: audit.runs, ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
259
+ renders: audit.runs, ...(audit.coverage ? { coverage: audit.coverage } : {}), ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
202
260
  }
203
261
 
204
262
  function projectPlaywright(root) {
@@ -243,10 +301,10 @@ async function warmScenariosApart(host, ids, signal) {
243
301
 
244
302
  /** One browser process over the given renders. Its report grows as they finish, so a worker that
245
303
  * dies keeps what it finished. A browser that is not installed stops the audit. */
246
- async function runAuditWorker({ root, temporary, playwright, settings, apps, signal }) {
304
+ async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed }) {
247
305
  const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
248
306
  rmSync(report, { force: true });
249
- writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
307
+ writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, overlayLimit: limits.overlays, stateLimit: limits.controls, contentQuietMs: limits.contentQuietMs, contentLimitMs: limits.contentLimitMs, claimed, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
250
308
  const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
251
309
  let cause;
252
310
  try {
@@ -257,10 +315,10 @@ async function runAuditWorker({ root, temporary, playwright, settings, apps, sig
257
315
  if (signal.aborted || error.code === "ADS_AUDIT_UNAVAILABLE") throw error;
258
316
  cause = clipCause(error.message);
259
317
  }
260
- if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], cause: cause ?? "Accessibility audit produced no bounded report." };
318
+ if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], capped: [], cause: cause ?? "Accessibility audit produced no bounded report." };
261
319
  const value = JSON.parse(readFileSync(report, "utf8"));
262
- if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
263
- return { runs: value.runs, cause };
320
+ if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], capped: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
321
+ return { runs: value.runs, capped: value.capped ?? [], cause };
264
322
  }
265
323
 
266
324
  /** A scenario that could not be audited is an error naming it and its last cause, never a pass. */
@@ -313,12 +371,12 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
313
371
  let host = previewHost;
314
372
  try {
315
373
  onProgress?.({ stage: "browser-audit", message: `Accessibility audit: building ${scenarios.length} scenario previews.`, elapsedMs: Date.now() - startedAt });
316
- const startHost = async () => { const { startAdsMcp } = await import("./mcp/server.mjs"); return startAdsMcp(root, { stdio: false, showcase: true }); };
374
+ const startHost = async () => { const { startAdsMcp } = await import("./mcp/server.mjs"); return startAdsMcp(root, { stdio: false, showcase: true, despitePolicy: true }); };
317
375
  if (!host?.url) host = await startHost();
318
376
  const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
319
377
  const floating = floatingScenarios(options, scenarios);
320
378
  const wanted = themes.flatMap(theme => (brands.length ? brands : [undefined]).flatMap(brand => scenarios.map(scenario => ({ scenario: scenario.id, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, ...(theme === themes[0] && containerKinds.includes(scenario.kind) && !floating.has(scenario.id) ? { container: containerWidth } : {}) }))));
321
- const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }]));
379
+ const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }])), capped = new Map();
322
380
  onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${wanted.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
323
381
  for (let attempt = 1; attempt <= auditAttempts; attempt++) {
324
382
  const pending = [...renders.values()].filter(render => !render.result);
@@ -336,7 +394,8 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
336
394
  if (app.brand) url.searchParams.set("brand", app.brand);
337
395
  return { ...app, url: url.href };
338
396
  });
339
- const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal }) : { runs: [] };
397
+ const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed: [...renders.values()].flatMap(render => render.result?.coverage?.claimed ?? []) }) : { runs: [], capped: [] };
398
+ for (const item of reached.capped ?? []) capped.set(item.claim, item);
340
399
  for (const run of reached.runs) {
341
400
  const render = renders.get(renderKey(run));
342
401
  if (!render) continue;
@@ -352,9 +411,10 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
352
411
  }
353
412
  const all = [...renders.values()], runs = all.map(render => render.result ?? render.partial).filter(Boolean);
354
413
  const retries = all.filter(render => render.result && render.attempts > 1).map(({ app, attempts, causes }) => ({ scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), attempts, causes }));
355
- const findings = [...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
414
+ const { coverage, findings: coverageItems } = auditCoverage(all.map(render => render.result).filter(Boolean), [...capped.values()], scenarios);
415
+ const findings = [...coverageItems, ...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...imageShapeFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
356
416
  const shifts = runs.filter(run => run.layoutShift).sort((a, b) => b.layoutShift.value - a.layoutShift.value);
357
- 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, findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
417
+ return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: findings.filter(finding => finding.rule === INCOMPLETE_RULE).length, overlaysOpened: coverage.overlaysOpened, controlsMeasured: coverage.controlsMeasured, coverage, findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
358
418
  } finally {
359
419
  try { if (host !== previewHost) await host?.close(); } finally { rmSync(temporary, { recursive: true, force: true }); }
360
420
  }
@@ -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
  }
package/dist/check.mjs CHANGED
@@ -40,6 +40,7 @@ import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
40
40
  import { inspectUsage } from "./usage.mjs";
41
41
  import { controlPaddingAdvisories } from "./control-padding.mjs";
42
42
  import { createComponentContrast } from "./component-contrast.mjs";
43
+ import { createFontRules } from "./font-rules.mjs";
43
44
  import { createLayoutWidths, globMatcher } from "./layout-widths.mjs";
44
45
  import { imageAttributeFindings } from "./image-attributes.mjs";
45
46
  import { findingSeverity, routeFindings } from "./finding-rules.mjs";
@@ -113,6 +114,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
113
114
  for (const glob of config.layout.widthTokens) if (!tokenInventory.tokens.some(token => globMatcher([glob])(token.name))) diagnostics.push({ rule: "layout-config", file: "ds.config.json", line: 1, column: 1, message: `layout.widthTokens entry ${glob} matches no declared token. Remove it or declare the token.` });
114
115
  for (const glob of config.layout.fixedWidthUnits) if (!units.units.some(unit => globMatcher([glob])(unit.id) || unit.files.some(file => globMatcher([glob])(file)))) diagnostics.push({ rule: "layout-config", file: "ds.config.json", line: 1, column: 1, message: `layout.fixedWidthUnits entry ${glob} matches no unit or owned file. Remove it or correct the path.` });
115
116
  const ownerFixedWidths = [];
117
+ const fontRules = createFontRules(options, tokenInventory.tokens);
116
118
  function checkRegistrations(file,css,offset={line:1}){
117
119
  css.walkAtRules(/^property$/i,rule=>{
118
120
  const line=offset.line+(rule.source?.start.line??1)-1;
@@ -148,6 +150,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
148
150
  catch (error) { report(file, "css-syntax", error.reason ?? error.message, offset.line + (error.line ?? 1) - 1); return; }
149
151
  layers.collectComponentStyles(file, css);
150
152
  layerStyles.push({ file, css, offset });
153
+ if (foundation || !isDevelopmentFile(file, options)) fontRules.collect(css, file, offset);
151
154
  checkRegistrations(file,css,offset);
152
155
  if (!foundation && !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file))) componentContrast.collect(path.relative(root, file).replaceAll("\\", "/"), css, offset);
153
156
  if (!foundation && (isInside(path.join(dsRoot, "composition"), file) || !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file)))) {
@@ -383,7 +386,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
383
386
  }
384
387
  inspectDesignAliases(layerStyles,options,report);
385
388
  for (const { file, css, offset } of layerStyles) layers.inspectStyles(file, css, offset);
386
- advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths));
389
+ advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths), ...fontRules.findings());
387
390
  // Errors block by class; bounded clients see review items before informational limits.
388
391
  const routed=routeFindings(diagnostics,advisories);
389
392
  const uniqueDiagnostics=[...new Map(routed.diagnostics.map(diagnostic=>[JSON.stringify([diagnostic.file,diagnostic.rule,diagnostic.line,diagnostic.column,diagnostic.message]),diagnostic])).values()];
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
  }
@@ -197,7 +202,7 @@ async function main(args) {
197
202
  }
198
203
  else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
199
204
  else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
200
- 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}`); }
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.coverage) { const skipped = Object.entries(result.coverage.skipped); console.log(`Covered: ${result.coverage.renders} renders, ${result.coverage.overlaysOpened} overlays opened, ${result.coverage.controlsMeasured} controls hovered and focused; ${skipped.length ? `skipped ${skipped.map(([reason, entry]) => `${reason} ${entry.count}`).join(", ")}` : "nothing skipped"}.`); } 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}`); }
201
206
  else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
202
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})`:""}`);}
203
208
  else if (command === "tokens") {
package/dist/config.mjs CHANGED
@@ -28,7 +28,7 @@ export const defaultConfig = {
28
28
  followSystemTheme: false,
29
29
  inlineStyleFiles: [],
30
30
  boundaries: { styleWrites: [], componentVariables: [] },
31
- assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null, imageBudgetKb: null },
31
+ assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null, imageBudgetKb: null, fontBudgetKb: null, preloadFonts: null },
32
32
  oxlint: { plugins: [], rules: {}, overrides: [] },
33
33
  acceptance: { checks: [], behaviorChecks: false, browserAudit: true },
34
34
  validation: { checks: [], behaviorChecks: true, browserAudit: true, inputs: [] },
@@ -131,6 +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 (config.assets.preloadFonts !== null && (!Array.isArray(config.assets.preloadFonts) || config.assets.preloadFonts.some(item => !item || typeof item !== "object" || Array.isArray(item) || Object.keys(item).some(key => !["family", "weight"].includes(key)) || typeof item.family !== "string" || !item.family || !Number.isInteger(item.weight) || item.weight < 1 || item.weight > 1000))) throw new Error('assets.preloadFonts must be null or an array of { "family": "Name", "weight": 400 }.');
135
+ if (config.assets.fontBudgetKb !== null && (!Number.isInteger(config.assets.fontBudgetKb) || config.assets.fontBudgetKb < 1 || config.assets.fontBudgetKb > 1048576)) throw new Error("assets.fontBudgetKb must be null (the default limit) or a positive whole number of KB.");
134
136
  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
137
  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
138
  if (!Array.isArray(config.usage.notifications) || config.usage.notifications.length > 100) throw new Error("usage.notifications must be an array of notification API registrations.");
@@ -27,9 +27,16 @@ export const findingRules = Object.freeze({
27
27
  // Whether a declared width must stay fixed, a fluid wrapper does anything, or a part ever sits in
28
28
  // a narrow pane takes judgement.
29
29
  "layout-declared-width": "review", "layout-width-noop": "review", "layout-overflow-narrow": "review",
30
+ // Rendered at a shape other than the one declared: cropped or stretched.
31
+ "img-shape": "error",
32
+ // What the audit could not measure, by reason; a render whose targets could none be measured is for review.
33
+ "browser-audit-skipped": "info", "browser-audit-nothing-measured": "review",
30
34
  // Images reserve their space and choose how they load; a spread or foreign class cannot be read.
31
35
  "img-attributes": "error", "img-attributes-unresolved": "info",
32
- "asset-image-budget": "error",
36
+ "asset-image-budget": "error", "asset-font-budget": "error",
37
+ // A weight no declared face covers is faked or replaced. An unused file, a font-display and a format
38
+ // are choices someone can have a reason for.
39
+ "font-weight-missing": "error", "font-preload-config": "error", "font-file-unused": "review", "font-display": "review", "font-format": "review",
33
40
  "layout-shift": "error",
34
41
  "glyph-aliases": "error", "glyph-color": "error", "glyph-viewbox": "error",
35
42
  // Local source cannot prove pointer-capture cleanup or dynamic scenario execution.
@@ -48,6 +55,12 @@ export const findingRules = Object.freeze({
48
55
  "token-overlap-review": "review",
49
56
  });
50
57
 
58
+ /** Static errors that stop a preview from rendering: a file that does not parse, a project that is
59
+ * not laid out, a scenario that cannot be registered. Everything else is policy: it fails ads check,
60
+ * validation and the audit's exit code, but the audit still renders and reports it. A broken import
61
+ * stops only the builds that reach it, which then fail as unaudited scenarios. */
62
+ export const renderStoppingRules = Object.freeze(new Set(["css-syntax", "project-structure", "scenario-contract", "source-syntax", "styles-entry"]));
63
+
51
64
  const severities = new Set(["error", "review", "info"]);
52
65
 
53
66
  /** A classified finding's severity; throws for an id missing from the registry. */
@@ -0,0 +1,103 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import postcss from "postcss";
4
+ import valueParser from "postcss-value-parser";
5
+ import { contextValues } from "./themes.mjs";
6
+ import { findingSeverity } from "./finding-rules.mjs";
7
+ import { fontFaces, preloadFace } from "./fonts-generated.mjs";
8
+
9
+ /** Fonts a project declares in tokens/fonts.css, against the weights its CSS uses. Without a declared
10
+ * face it finds nothing: a system font stack has no files and no faces to fake.
11
+ * A face with a weight range, or with no font-weight (auto, as a variable font), covers what it spans.
12
+ * A weight read in a rule with no font-family belongs to the body's family, since it inherits. */
13
+ const unquote = value => value.trim().replace(/^["']|["']$/g, "");
14
+ const keyword = { normal: 400, bold: 700 };
15
+ const weightOf = value => { const number = Number(value); return Number.isFinite(number) && number >= 1 && number <= 1000 ? number : keyword[value?.toLowerCase()]; };
16
+
17
+ function declaredFaces(file) {
18
+ const faces = [];
19
+ postcss.parse(readFileSync(file, "utf8")).walkAtRules(/^font-face$/i, rule => {
20
+ const read = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
21
+ const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(read("src") ?? "")?.[1], weight = read("font-weight")?.trim().toLowerCase();
22
+ const parts = weight && weight !== "auto" ? weight.split(/\s+/).map(weightOf) : null;
23
+ faces.push({ family: unquote(read("font-family") ?? ""), url, low: parts?.[0], high: parts?.[1] ?? parts?.[0], auto: !parts, display: read("font-display")?.trim().toLowerCase(), italic: /italic|oblique/i.test(read("font-style") ?? ""), ranged: !!read("unicode-range"), line: rule.source.start.line });
24
+ });
25
+ return faces;
26
+ }
27
+
28
+ export function createFontRules({ root, dsRoot, config }, tokens) {
29
+ const file = path.join(dsRoot, config.tokenDir, "fonts.css");
30
+ let faces = [];
31
+ try { if (existsSync(file)) faces = declaredFaces(file); } catch { /* The core CSS syntax diagnostic owns a malformed sheet. */ }
32
+ const relative = target => path.relative(root, target).replaceAll("\\", "/");
33
+ // A named preload that fonts.css cannot satisfy is an error, so a typo cannot silently lose it.
34
+ const preloadFindings = () => (config.assets.preloadFonts ?? []).flatMap(entry => {
35
+ let sheet = [];
36
+ try { if (existsSync(file)) sheet = fontFaces(readFileSync(file, "utf8")); } catch { /* The core CSS syntax diagnostic owns a malformed sheet. */ }
37
+ if (preloadFace(sheet, entry)) return [];
38
+ const known = sheet.some(face => face.family === entry.family);
39
+ return [{ rule: "font-preload-config", severity: findingSeverity("font-preload-config"), file: "ds.config.json", line: 1, column: 1, guidanceUri: "ads://guides/performance",
40
+ message: `assets.preloadFonts names ${entry.family} at weight ${entry.weight}, and tokens/fonts.css ${known ? `has no upright face of ${entry.family} covering Latin at that weight` : `declares no font-family ${entry.family}`}. Correct the entry or add the face.` }];
41
+ });
42
+ if (!faces.length) return { collect() {}, findings: preloadFindings };
43
+ const values = contextValues(tokens, { theme: config.themes[0].name, themes: config.themes });
44
+ const families = new Set(faces.map(face => face.family));
45
+ /** A value with its var() read through, as far as tokens define it. */
46
+ const read = (value, seen = new Set()) => valueParser(value).nodes.map(node => {
47
+ if (node.type !== "function" || node.value !== "var") return valueParser.stringify(node);
48
+ const [name, ...fallback] = valueParser.stringify(node.nodes).split(",");
49
+ const token = name.trim();
50
+ if (seen.has(token)) return "";
51
+ const found = values.get(token)?.value ?? fallback.join(",");
52
+ return read(found, new Set([...seen, token]));
53
+ }).join("");
54
+ const familiesIn = value => read(value).split(",").map(unquote).filter(item => families.has(item));
55
+ // A family set with no weight in its rule takes whatever weight it inherits, so any of its weights may be in use.
56
+ const used = new Map(), named = new Set(), inherited = new Set();
57
+ let bodyFamily, pending = [];
58
+ const note = (family, weight, source) => { const uses = used.get(family) ?? new Map(); used.set(family, uses); if (!uses.has(weight)) uses.set(weight, source); };
59
+ return {
60
+ /** Reads one style sheet or Linaria template. */
61
+ collect(css, target, offset = { line: 1 }) {
62
+ const source = decl => ({ file: relative(target), line: offset.line + (decl.source?.start.line ?? 1) - 1 });
63
+ // A Linaria template's own declarations sit at the root of what it parses to.
64
+ const owners = new Set();
65
+ css.walkDecls(/^font(?:-family|-weight)?$/i, decl => { if (decl.parent.type !== "atrule" || !/^font-face$/i.test(decl.parent.name)) owners.add(decl.parent); });
66
+ for (const rule of owners) {
67
+ const own = name => rule.nodes.filter(node => node.type === "decl" && node.prop.toLowerCase() === name).at(-1);
68
+ const shorthand = own("font"), parts = shorthand ? read(shorthand.value).split(/\s+/) : [];
69
+ const familyDecl = own("font-family");
70
+ const stack = familyDecl ? familiesIn(familyDecl.value) : shorthand ? familiesIn(read(shorthand.value).replace(/^.*?\d[^ ]*(?:\/[^ ]+)?\s+/, "")) : [], family = stack[0];
71
+ for (const item of stack) named.add(item);
72
+ if (family && /^(?:(?::where\()?(?:html|body|:root)\)?)$/.test(rule.selector?.trim() ?? "")) bodyFamily ??= family;
73
+ const weightDecl = own("font-weight"), weight = weightDecl ? weightOf(read(weightDecl.value).trim()) : parts.map(weightOf).find(Boolean);
74
+ if (!weight) { for (const item of stack) inherited.add(item); continue; }
75
+ const where = source(weightDecl ?? shorthand);
76
+ if (family) note(family, weight, where);
77
+ else if (!familyDecl && !shorthand) pending.push({ weight, where });
78
+ }
79
+ },
80
+ findings() {
81
+ const findings = preloadFindings(), covering = (family, weight) => faces.some(face => face.family === family && !face.italic && (face.auto || face.low <= weight && weight <= face.high));
82
+ if (bodyFamily) { named.add(bodyFamily); inherited.delete(bodyFamily); for (const { weight, where } of pending) note(bodyFamily, weight, where); }
83
+ pending = [];
84
+ for (const [family, uses] of used) for (const [weight, where] of uses) if (!covering(family, weight)) {
85
+ findings.push({ rule: "font-weight-missing", severity: findingSeverity("font-weight-missing"), file: where.file, line: where.line, column: 1, guidanceUri: "ads://guides/performance",
86
+ message: `${where.file}:${where.line} uses ${family} at weight ${weight}, and tokens/fonts.css has no face that covers it, so the browser fakes it or picks another weight. Add the file, use a variable font with a font-weight range, or use a declared weight.` });
87
+ }
88
+ const seen = new Set();
89
+ // A face of local() files only downloads nothing: a fallback sized to match, say.
90
+ for (const face of faces.filter(item => item.url)) {
91
+ const at = { file: relative(file), line: face.line, column: 1, guidanceUri: "ads://guides/performance" };
92
+ const name = face.url ? path.basename(face.url) : face.family;
93
+ const single = !face.auto && face.low === face.high && !face.italic;
94
+ const unused = !named.has(face.family) || single && !face.ranged && !inherited.has(face.family) && ![400, 700].includes(face.low) && !used.get(face.family)?.has(face.low);
95
+ if (unused && !seen.has(name)) { seen.add(name); findings.push({ rule: "font-file-unused", severity: findingSeverity("font-file-unused"), ...at, message: `${name}${named.has(face.family) ? ` (${face.family} at weight ${face.low})` : ` (${face.family})`} is declared and no CSS uses it. Remove the face and the file, so nothing downloads it.` }); }
96
+ if (!face.display) findings.push({ rule: "font-display", severity: findingSeverity("font-display"), ...at, message: `${name} has no font-display, so text can stay invisible while it loads. Set font-display: swap.` });
97
+ else if (face.display === "optional") findings.push({ rule: "font-display", severity: findingSeverity("font-display"), ...at, message: `${name} has font-display: optional. The browser decides per file, so one page can draw some weights in the font and others in the fallback. Use font-display: swap.` });
98
+ if (face.url && !/^data:/i.test(face.url) && !/\.woff2(?:[?#].*)?$/i.test(face.url)) findings.push({ rule: "font-format", severity: findingSeverity("font-format"), ...at, message: `${name} is not WOFF2, the smallest format every current browser reads. Convert it.` });
99
+ }
100
+ return findings;
101
+ },
102
+ };
103
+ }
@@ -3,23 +3,25 @@ import path from "node:path";
3
3
  import postcss from "postcss";
4
4
  import { resolveValue } from "./themes.mjs";
5
5
 
6
- /** fonts.preload.generated.ts names the font files the first text uses, read from the sheets: the
7
- * first family in base.css's body font-family and heading font-family that fonts.css declares, at
8
- * the body and heading font-weight. Preloading more than that delays what matters. It imports each
6
+ /** fonts.preload.generated.ts names the font files the first text uses: assets.preloadFonts when the
7
+ * project lists them, otherwise read from the sheets: the first family in base.css's body font-family
8
+ * and heading font-family that fonts.css declares, at the body and heading font-weight. Preloading more than that delays what matters. It imports each
9
9
  * file through the bundler, the way the stylesheet's url() does, so both ask for one URL: a page
10
- * that preloads another URL downloads the font twice. Without such a font nothing is generated. */
10
+ * that preloads another URL downloads the font twice. A plain import is what Vite, Bun and the
11
+ * preview compiler all read as a file's URL. Without such a font nothing is generated. */
11
12
  export const generatedFontsFile = "fonts.preload.generated.ts";
12
13
  const unquote = value => value.trim().replace(/^["']|["']$/g, "");
13
14
  const formats = { woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf" };
14
15
 
15
- function fontFaces(text) {
16
+ export function fontFaces(text) {
16
17
  const faces = [];
17
18
  postcss.parse(text).walkAtRules(/^font-face$/i, rule => {
18
19
  const value = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
19
20
  const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(value("src") ?? "")?.[1];
20
21
  if (!url || /^data:/i.test(url)) return;
21
- const [low, high = low] = (value("font-weight") ?? "400").replace(/\bnormal\b/, "400").replace(/\bbold\b/, "700").trim().split(/\s+/).map(Number);
22
- faces.push({ family: unquote(value("font-family") ?? ""), url, low, high, slant: (value("font-style") ?? "normal").trim().toLowerCase(), range: value("unicode-range") });
22
+ const auto = !value("font-weight") || /^auto$/i.test(value("font-weight").trim());
23
+ const [low, high = low] = (auto ? "400" : value("font-weight")).replace(/\bnormal\b/, "400").replace(/\bbold\b/, "700").trim().split(/\s+/).map(Number);
24
+ faces.push({ family: unquote(value("font-family") ?? ""), url, auto, low, high, slant: (value("font-style") ?? "normal").trim().toLowerCase(), range: value("unicode-range") });
23
25
  });
24
26
  return faces;
25
27
  }
@@ -27,6 +29,9 @@ function fontFaces(text) {
27
29
  /** Whether a unicode-range covers Latin capital A, the subset first text needs. */
28
30
  const coversLatin = range => !range || range.split(",").some(part => { const [first, last = first] = part.trim().replace(/^U\+/i, "").split("-").map(item => parseInt(item.replaceAll("?", "0"), 16)); return first <= 0x41 && 0x41 <= (part.includes("?") ? first + 0xff : last); });
29
31
 
32
+ /** The face a named family and weight loads for first text: upright, covering Latin and that weight. */
33
+ export const preloadFace = (faces, { family, weight }) => faces.find(face => face.family === family && face.slant === "normal" && coversLatin(face.range) && (face.auto || face.low <= weight && weight <= face.high));
34
+
30
35
  /** The font and weight of the body and of headings, as base.css sets them. */
31
36
  function firstTextFonts(text, values) {
32
37
  const read = pattern => {
@@ -47,11 +52,14 @@ function firstTextFonts(text, values) {
47
52
  /** The generated module for a project's tokens, or null when no first-text font is a project file. */
48
53
  export function fontPreloadText({ dsRoot, config }, values) {
49
54
  const directory = path.join(dsRoot, config.tokenDir), fontsFile = path.join(directory, "fonts.css"), baseFile = path.join(directory, "base.css");
50
- if (!existsSync(fontsFile) || !existsSync(baseFile)) return null;
55
+ const named = config.assets.preloadFonts;
56
+ if (!existsSync(fontsFile) || !named && !existsSync(baseFile)) return null;
51
57
  let faces, uses;
52
- try { faces = fontFaces(readFileSync(fontsFile, "utf8")); uses = firstTextFonts(readFileSync(baseFile, "utf8"), values); }
58
+ try { faces = fontFaces(readFileSync(fontsFile, "utf8")); uses = named ? [] : firstTextFonts(readFileSync(baseFile, "utf8"), values); }
53
59
  catch { return null; /* The core CSS syntax diagnostic owns malformed sheets. */ }
54
60
  const urls = new Set();
61
+ // Named in the config: exactly these, and font-preload-config reports one fonts.css does not have.
62
+ for (const entry of named ?? []) { const face = preloadFace(faces, entry); if (face) urls.add(face.url); }
55
63
  for (const { family, weight } of uses) {
56
64
  const name = (family ?? "").split(",").map(unquote).find(item => faces.some(face => face.family === item));
57
65
  if (!name) continue;
@@ -63,15 +71,25 @@ export function fontPreloadText({ dsRoot, config }, values) {
63
71
  const list = [...urls], local = url => !/^(?:[a-z]+:)?\/\//i.test(url) && !url.startsWith("/");
64
72
  const type = url => formats[/\.(\w+)(?:[?#].*)?$/.exec(url)?.[1]?.toLowerCase()] ?? "font/woff2";
65
73
  return [
66
- "/* Generated by ADS from fonts.css and base.css: the fonts the first text uses. `ads assets` and the",
74
+ "/* Generated by ADS from fonts.css and base.css or assets.preloadFonts: the fonts the first text uses. `ads assets` and the",
67
75
  " showcase and MCP server rewrite it; do not edit it. Call preloadFonts() in the app entry before",
68
- " the first render. */",
69
- ...list.flatMap((url, index) => local(url) ? [`import font${index} from ${JSON.stringify(`${url.startsWith(".") ? url : `./${url}`}?url`)};`] : []),
76
+ " the first render, or put fontPreloadTags() or fontPreloadHeader() in the page from a build step. */",
77
+ ...list.flatMap((url, index) => local(url) ? [`import font${index} from ${JSON.stringify(url.startsWith(".") ? url : `./${url}`)};`] : []),
70
78
  "",
71
79
  "export const fontPreloads: readonly { readonly href: string; readonly type: string }[] = [",
72
80
  ...list.map((url, index) => ` { href: ${local(url) ? `font${index}` : JSON.stringify(url)}, type: ${JSON.stringify(type(url))} },`),
73
81
  "];",
74
82
  "",
83
+ "/** The same list for a build step or prerender: <link> tags for the page's HTML. */",
84
+ "export function fontPreloadTags(): string {",
85
+ ' return fontPreloads.map(({ href, type }) => `<link rel="preload" href="${href}" as="font" type="${type}" crossorigin="anonymous">`).join("\\n");',
86
+ "}",
87
+ "",
88
+ "/** The same list as a Link header value. */",
89
+ "export function fontPreloadHeader(): string {",
90
+ ' return fontPreloads.map(({ href, type }) => `<${href}>; rel=preload; as=font; type="${type}"; crossorigin=anonymous`).join(", ");',
91
+ "}",
92
+ "",
75
93
  "/** Adds one preload link per font. The crossorigin attribute matches how browsers fetch fonts. */",
76
94
  "export function preloadFonts(): void {",
77
95
  " for (const { href, type } of fontPreloads) {",
@@ -19,9 +19,10 @@ import { findingSeverity } from "./finding-rules.mjs";
19
19
  export const smallPartLimitPx = 96;
20
20
  const widthProperties = new Set(["width", "min-width", "inline-size", "min-inline-size", "flex-basis", "flex", "grid-template-columns"]);
21
21
  const fluidUnits = /^(?:%|fr|[sld]?v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max))$/i;
22
- /** Lengths in px; a font-relative one at the 16 px root font, as an estimate. It is still fixed. */
23
- const absoluteUnits = { px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6 };
24
- const fontUnits = { rem: 16, em: 16, ic: 16, ch: 8, ex: 8, cap: 11, lh: 24, rlh: 24 };
22
+ /** Lengths in px. A font-relative one is estimated at the rule's font-size, or 16 px. It is still fixed. */
23
+ const absoluteUnits = { px: 1, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6, rem: 16, rlh: 24 };
24
+ /** Per px of the element's font size, as estimates. */
25
+ const fontUnits = { em: 1, ic: 1, ch: 0.5, ex: 0.5, cap: 0.7, lh: 1.5 };
25
26
  const keywords = /^(?:auto|none|min-content|max-content|fit-content|stretch|inherit|initial|unset|revert|revert-layer|content|subgrid)$/i;
26
27
  const fluid = { low: 0, high: Infinity }, neutral = { neutral: true }, unknown = { unknown: true };
27
28
  const isLength = part => part.low !== undefined;
@@ -75,7 +76,7 @@ export function createLayoutWidths(tokens, { themes, layout }) {
75
76
  if (!unit) return number === 0 ? fixedAt(0) : { number };
76
77
  if (number === 0) return fixedAt(0);
77
78
  if (fluidUnits.test(unit)) return fluid;
78
- const size = absoluteUnits[unit] ?? fontUnits[unit];
79
+ const size = absoluteUnits[unit] ?? (fontUnits[unit] ? fontUnits[unit] * (scope.fontPx ?? 16) : undefined);
79
80
  return size ? fixedAt(number * size) : unknown;
80
81
  }
81
82
  if (node.type !== "function") return unknown;
@@ -87,8 +88,12 @@ export function createLayoutWidths(tokens, { themes, layout }) {
87
88
  if (name === "max") return largest(splitArguments(node.nodes).map(part => sequence(part, scope)));
88
89
  if (name !== "clamp") return unknown;
89
90
  const [floor, preferred, ceiling] = splitArguments(node.nodes).map(part => sequence(part, scope));
90
- if (floor?.neutral) return ceiling?.neutral || !ceiling ? preferred ?? unknown : smallest([preferred, ceiling]);
91
- return largest([floor, !ceiling || ceiling.neutral ? preferred : smallest([preferred, ceiling])]);
91
+ const value = floor?.neutral ? (ceiling?.neutral || !ceiling ? preferred ?? unknown : smallest([preferred, ceiling]))
92
+ // A preferred value that cannot be read still leaves the floor: it cannot shrink below that.
93
+ : isLength(floor) && !isLength(preferred ?? unknown) ? { low: floor.low, high: Infinity }
94
+ : largest([floor, !ceiling || ceiling.neutral ? preferred : smallest([preferred, ceiling])]);
95
+ // A resizable part: every value is a declared width, each listed for review.
96
+ return floor?.declared && preferred?.declared && ceiling?.declared ? { ...(isLength(value) ? value : neutral), declared: "clamp" } : value;
92
97
  }
93
98
  /** min(): a part that reaches zero lets the whole shrink, whatever the others are. */
94
99
  function smallest(parts) {
@@ -188,7 +193,11 @@ export function createLayoutWidths(tokens, { themes, layout }) {
188
193
  css.walkDecls(decl => {
189
194
  const property = decl.prop.toLowerCase();
190
195
  if (!widthProperties.has(property) || decl.value.includes("__ds_expression__")) return;
191
- const declared = new Set(), scope = { seen: new Set(), locals, declared }, found = judge(property, decl.value, scope);
196
+ // ch and em follow a font size set in the same rule, read through its token; an em font size is taken against 16 px.
197
+ const fontSize = decl.parent.nodes.findLast(sibling => sibling.type === "decl" && sibling.prop.toLowerCase() === "font-size");
198
+ const font = fontSize && sequence(valueParser(fontSize.value).nodes, { seen: new Set(), locals });
199
+ const fontPx = font?.low !== undefined && font.low === font.high && font.low > 0 ? font.low : undefined;
200
+ const declared = new Set(), scope = { seen: new Set(), locals, declared, fontPx }, found = judge(property, decl.value, scope);
192
201
  for (const token of declared) declaredUses.set(token, (declaredUses.get(token) ?? 0) + 1);
193
202
  if (!found) return;
194
203
  // width: 280px with max-width: 100% in the same rule is min(100%, 280px).
@@ -196,7 +205,7 @@ export function createLayoutWidths(tokens, { themes, layout }) {
196
205
  const line = offset.line + decl.source.start.line - 1, column = decl.source.start.column + (decl.source.start.line === 1 ? offset.column - 1 : 0);
197
206
  if (found.review !== undefined) {
198
207
  findings.push({ rule: "layout-width-noop", severity: findingSeverity("layout-width-noop"), file, line, column, property, value: decl.value, guidanceUri: "ads://guides/tokens",
199
- message: `${file}:${line} sets ${property}: ${decl.value}. It never exceeds ${found.review}px, within the ${smallPartLimitPx}px a small part may use plainly, so the fluid part does nothing. Write the plain size.` });
208
+ message: `${file}:${line} sets ${property}: ${decl.value}. It never exceeds ${found.review}px, within the ${smallPartLimitPx}px a small part may use plainly, so it does not protect against overflow, and a plain size is clearer. In a flex or grid parent the percentage can still affect wrapping, so compare the scenario after changing it.` });
200
209
  return;
201
210
  }
202
211
  findings.push({ rule: "layout-fixed-width", severity: findingSeverity("layout-fixed-width"), file, line, column, property, value: decl.value, guidanceUri: "ads://guides/tokens",
@@ -16,7 +16,7 @@ function stamp(file) {
16
16
  }
17
17
 
18
18
  /** One project-owned compiler process, shared by all protocol instances. */
19
- export function createPreviewWatch(root, config, { log = process.stderr, buildTimeout = 30000, prewarm = false } = {}) {
19
+ export function createPreviewWatch(root, config, { log = process.stderr, buildTimeout = 30000, prewarm = false, despitePolicy = false } = {}) {
20
20
  config = { ...config, apps: [...config.apps] };
21
21
  const command = config.previewWatch;
22
22
  let session = randomUUID();
@@ -77,7 +77,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
77
77
  // No shell: configured arguments remain literal. Child stdin cannot consume
78
78
  // the MCP channel, and both output streams go exclusively to diagnostics.
79
79
  const executable = developmentExecutable(command.command);
80
- const env = { ...process.env, ADS_MCP_BUILD_SESSION: session, ADS_MCP_BUILD_STATUS: reportFile, ADS_MCP_REQUEST_FILE: requestFile, ADS_MCP_PREWARM_VIEWS: prewarm ? "1" : "0", PATH: [path.join(root, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) };
80
+ const env = { ...process.env, ADS_MCP_BUILD_SESSION: session, ADS_MCP_BUILD_STATUS: reportFile, ADS_MCP_REQUEST_FILE: requestFile, ADS_MCP_PREWARM_VIEWS: prewarm ? "1" : "0", ADS_PREVIEW_DESPITE_POLICY: despitePolicy ? "1" : "0", PATH: [path.join(root, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) };
81
81
  try {
82
82
  child = spawn(executable, command.args, { cwd: root, env, shell: false, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
83
83
  } catch (failure) {