@reqvire-org/ads 0.3.52 → 0.4.0

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 (151) hide show
  1. package/README.md +10 -9
  2. package/dist/assets.mjs +16 -2
  3. package/dist/behaviors.mjs +6 -5
  4. package/dist/boundaries.mjs +5 -5
  5. package/dist/browser-audit/first-render.mjs +22 -0
  6. package/dist/browser-audit/image-shape.mjs +36 -0
  7. package/dist/browser-audit/render-states.mjs +61 -35
  8. package/dist/browser-audit/worker.mjs +47 -12
  9. package/dist/browser-audit.mjs +75 -12
  10. package/dist/bun-compiler.mjs +14 -7
  11. package/dist/check-service.mjs +83 -0
  12. package/dist/check.mjs +20 -18
  13. package/dist/cli.mjs +5 -3
  14. package/dist/config.mjs +20 -41
  15. package/dist/contracts.d.mts +9 -0
  16. package/dist/finding-rules.mjs +8 -1
  17. package/dist/font-rules.mjs +103 -0
  18. package/dist/fonts-generated.mjs +32 -12
  19. package/dist/generated-entries.mjs +131 -0
  20. package/dist/icons.mjs +1 -1
  21. package/dist/init.mjs +11 -32
  22. package/dist/layers.mjs +7 -3
  23. package/dist/lint-config.mjs +4 -2
  24. package/dist/mcp/catalog.mjs +2 -1
  25. package/dist/mcp/context.mjs +3 -3
  26. package/dist/mcp/drafts.mjs +136 -121
  27. package/dist/mcp/mutations.mjs +65 -19
  28. package/dist/mcp/preview-watch.mjs +31 -5
  29. package/dist/mcp/preview-widget.bundle.js +50 -47
  30. package/dist/mcp/project-widget.bundle.js +45 -42
  31. package/dist/mcp/prompts.mjs +1 -1
  32. package/dist/mcp/server.mjs +81 -40
  33. package/dist/mcp/showcase-host.mjs +20 -7
  34. package/dist/mcp/widget.bundle.js +49 -46
  35. package/dist/oxlint.mjs +3 -2
  36. package/dist/program-cache.mjs +36 -0
  37. package/dist/public-api.mjs +2 -1
  38. package/dist/scenarios-compiler.mjs +82 -14
  39. package/dist/scenarios-vite.mjs +1 -1
  40. package/dist/scenarios.mjs +4 -3
  41. package/dist/showcase/client.bundle.js +27 -27
  42. package/dist/showcase/index.html +2 -2
  43. package/dist/skills/ads-break-ui/SKILL.md +25 -28
  44. package/dist/skills/ads-break-ui/references/behaviors.md +7 -6
  45. package/dist/skills/ads-break-ui/references/captures.md +7 -32
  46. package/dist/skills/ads-break-ui/references/contracts.md +58 -25
  47. package/dist/skills/ads-break-ui/references/drafts.md +59 -43
  48. package/dist/skills/ads-break-ui/references/evidence.md +1 -1
  49. package/dist/skills/ads-break-ui/references/guarded-editing.md +58 -47
  50. package/dist/skills/ads-break-ui/references/review.md +9 -8
  51. package/dist/skills/ads-break-ui/references/scenarios.md +1 -1
  52. package/dist/skills/ads-break-ui/references/validation.md +8 -4
  53. package/dist/skills/ads-break-ui/references/workflows.md +15 -8
  54. package/dist/skills/ads-designer/SKILL.md +30 -31
  55. package/dist/skills/ads-designer/references/accessibility.md +9 -5
  56. package/dist/skills/ads-designer/references/behaviors.md +7 -6
  57. package/dist/skills/ads-designer/references/branding.md +2 -2
  58. package/dist/skills/ads-designer/references/captures.md +7 -32
  59. package/dist/skills/ads-designer/references/cli.md +5 -1
  60. package/dist/skills/ads-designer/references/contracts.md +58 -25
  61. package/dist/skills/ads-designer/references/drafts.md +59 -43
  62. package/dist/skills/ads-designer/references/evidence.md +1 -1
  63. package/dist/skills/ads-designer/references/guarded-editing.md +58 -47
  64. package/dist/skills/ads-designer/references/performance.md +57 -6
  65. package/dist/skills/ads-designer/references/review.md +9 -8
  66. package/dist/skills/ads-designer/references/scenarios.md +1 -1
  67. package/dist/skills/ads-designer/references/validation.md +8 -4
  68. package/dist/skills/ads-designer/references/workflows.md +15 -8
  69. package/dist/skills/ads-import/SKILL.md +25 -28
  70. package/dist/skills/ads-import/references/behaviors.md +7 -6
  71. package/dist/skills/ads-import/references/captures.md +7 -32
  72. package/dist/skills/ads-import/references/cli.md +5 -1
  73. package/dist/skills/ads-import/references/contracts.md +58 -25
  74. package/dist/skills/ads-import/references/drafts.md +59 -43
  75. package/dist/skills/ads-import/references/evidence.md +1 -1
  76. package/dist/skills/ads-import/references/guarded-editing.md +58 -47
  77. package/dist/skills/ads-import/references/review.md +9 -8
  78. package/dist/skills/ads-import/references/scenarios.md +1 -1
  79. package/dist/skills/ads-import/references/validation.md +8 -4
  80. package/dist/skills/ads-import/references/workflows.md +15 -8
  81. package/dist/skills/ads-motion/SKILL.md +25 -28
  82. package/dist/skills/ads-motion/references/behaviors.md +7 -6
  83. package/dist/skills/ads-motion/references/captures.md +7 -32
  84. package/dist/skills/ads-motion/references/contracts.md +58 -25
  85. package/dist/skills/ads-motion/references/drafts.md +59 -43
  86. package/dist/skills/ads-motion/references/evidence.md +1 -1
  87. package/dist/skills/ads-motion/references/guarded-editing.md +58 -47
  88. package/dist/skills/ads-motion/references/review.md +9 -8
  89. package/dist/skills/ads-motion/references/scenarios.md +1 -1
  90. package/dist/skills/ads-motion/references/validation.md +8 -4
  91. package/dist/skills/ads-motion/references/workflows.md +15 -8
  92. package/dist/skills/ads-port/SKILL.md +25 -28
  93. package/dist/skills/ads-port/references/behaviors.md +7 -6
  94. package/dist/skills/ads-port/references/captures.md +7 -32
  95. package/dist/skills/ads-port/references/cli.md +5 -1
  96. package/dist/skills/ads-port/references/contracts.md +58 -25
  97. package/dist/skills/ads-port/references/drafts.md +59 -43
  98. package/dist/skills/ads-port/references/evidence.md +1 -1
  99. package/dist/skills/ads-port/references/guarded-editing.md +58 -47
  100. package/dist/skills/ads-port/references/native-implementation.md +6 -6
  101. package/dist/skills/ads-port/references/review.md +9 -8
  102. package/dist/skills/ads-port/references/scenarios.md +1 -1
  103. package/dist/skills/ads-port/references/validation.md +8 -4
  104. package/dist/skills/ads-port/references/workflows.md +15 -8
  105. package/dist/starters/preact/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
  106. package/dist/starters/preact/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
  107. package/dist/starters/preact/ds.config.json +0 -14
  108. package/dist/starters/react/README.md +9 -5
  109. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +1 -1
  110. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +2 -2
  111. package/dist/starters/react/design-system/components/Actions/Button/Button.ads.exports.ts +1 -0
  112. package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.exports.ts +1 -0
  113. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.exports.ts +1 -0
  114. package/dist/starters/react/design-system/components/Content/Image/Image.ads.exports.ts +1 -0
  115. package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.exports.ts +1 -0
  116. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
  117. package/dist/starters/react/design-system/components/Forms/TextField/TextField.ads.exports.ts +1 -0
  118. package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
  119. package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.exports.ts +1 -0
  120. package/dist/starters/react/design-system/controllers/Palette/Palette.ads.exports.ts +1 -0
  121. package/dist/starters/react/design-system/index.ts +3 -7
  122. package/dist/starters/react/design-system/patterns/Search/SearchBar/SearchBar.ads.exports.ts +1 -0
  123. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.ads.exports.ts +1 -0
  124. package/dist/starters/react/design-system/review/demo-frame/DemoFrame.ads.exports.ts +1 -0
  125. package/dist/starters/react/design-system/review/grid-cell/GridCell.ads.exports.ts +1 -0
  126. package/dist/starters/react/design-system/review/index.ts +4 -3
  127. package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.ads.exports.ts +1 -0
  128. package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
  129. package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.exports.ts +1 -0
  130. package/dist/starters/react/design-system/styles.css +1 -0
  131. package/dist/starters/react/ds.config.json +0 -14
  132. package/dist/style-boundaries.mjs +7 -6
  133. package/dist/test-boundaries.mjs +2 -2
  134. package/dist/themes-watch.mjs +9 -3
  135. package/dist/token-fixtures.mjs +1 -1
  136. package/dist/unit-contracts.mjs +38 -4
  137. package/dist/units.mjs +16 -91
  138. package/dist/validation-checks.mjs +7 -1
  139. package/docs/ADS.md +10 -10
  140. package/docs/ARCHITECTURE.md +104 -44
  141. package/docs/BEHAVIORS.md +8 -7
  142. package/docs/CACHING.md +15 -6
  143. package/docs/CHANGELOG.md +107 -12
  144. package/docs/COMPARISON.md +1 -1
  145. package/docs/CONTRACTS.md +10 -25
  146. package/docs/GUIDE.md +98 -57
  147. package/docs/MCP.md +116 -151
  148. package/package.json +7 -7
  149. package/dist/contract-migration.mjs +0 -110
  150. package/dist/mcp/draft-exports.mjs +0 -40
  151. package/dist/mcp/edit-preparation.mjs +0 -115
@@ -44,7 +44,7 @@ export const containerKinds = Object.freeze(["components", "patterns"]);
44
44
  /** Attempts for one render, against a dropped preview connection or a slow preview. */
45
45
  export const auditAttempts = 3;
46
46
  /** overlays and controls bound what each render opens and hovers: distinct ones, in document order. */
47
- const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, pages: 4, overlays: 3, controls: 6 };
47
+ const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, overlays: 3, controls: 6, contentQuietMs: 500, contentLimitMs: 5000 };
48
48
 
49
49
  /** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
50
50
  export function wcagCriteria(tags) {
@@ -127,6 +127,23 @@ export function nonTextContrastFindings(runs, scenarios) {
127
127
  });
128
128
  }
129
129
 
130
+ const skipReasons = {
131
+ "overlay-did-not-open": "a control with aria-haspopup opened nothing with a dialog, menu or listbox role",
132
+ "overlay-trigger-gone": "a trigger left the page before its turn",
133
+ "overlay-left-open": "an overlay did not close on Escape, so later triggers could not be reached",
134
+ "overlay-timeout": "a trigger could not be clicked in time",
135
+ "overlay-detached": "a trigger left the page or was covered while it was being clicked",
136
+ "overlay-failed": "opening an overlay failed",
137
+ "overlay-cap": "the limit of 3 triggers per render was reached and no other scenario has them",
138
+ "control-gone": "a control left the page before its turn",
139
+ "control-timeout": "a control could not be hovered in time",
140
+ "control-detached": "a control left the page while it was being measured",
141
+ "control-failed": "measuring a control failed",
142
+ "control-cap": "the limit of 6 controls per render was reached and no other scenario has them",
143
+ "content-still-changing": "the page kept changing past 5 s, so what it measured may be mid-change",
144
+ "focus-not-reachable": "a control a keyboard cannot reach (aria-hidden, inert, or tabindex -1 outside a roving widget): hover measured, focus not",
145
+ };
146
+
130
147
  const overflowKinds = {
131
148
  document: { what: "the page scrolls horizontally", fix: "Find the element wider than its container; use fluid widths, min-width: 0 on flex and grid children, and let long text wrap." },
132
149
  viewport: { what: "content reaches past the viewport", fix: "Make the element fluid (%, fr, a --grid-span-N token in a container query), wrap it, or put it in an overflow-x: auto scroller." },
@@ -159,6 +176,45 @@ export function layoutOverflowFindings(runs, scenarios) {
159
176
  });
160
177
  }
161
178
 
179
+ /** One error per scenario and image rendered at a shape other than the one it declares. */
180
+ export function imageShapeFindings(runs, scenarios) {
181
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
182
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
183
+ for (const run of runs) for (const issue of run.imageShape ?? []) {
184
+ const key = JSON.stringify([run.scenario, issue.selector]);
185
+ const group = groups.get(key) ?? { scenario: run.scenario, issue, themes: [], brands: [] };
186
+ groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
187
+ }
188
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, issue, themes, brands }) => ({
189
+ rule: "img-shape", severity: findingSeverity("img-shape"), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", scenario, themes, ...(brands.length ? { brands } : {}), nodes: [issue], rendered: issue.rendered, declared: issue.declared, guidanceUri: "ads://guides/performance",
190
+ message: `Image shape in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${issue.selector} renders at ${issue.rendered} at the ${issue.width} px viewport but declares ${issue.declared}, so it is cropped or stretched. A height attribute beats aspect-ratio: add height: auto. For a deliberate crop in a box of its own, set object-fit and no aspect-ratio.`,
191
+ }));
192
+ }
193
+
194
+ /** What a run measured, and what it skipped and why: per reason, with a few examples. An info finding
195
+ * for each reason, and a review item for a render assigned targets that measured none of them. */
196
+ export function auditCoverage(runs, capped, scenarios) {
197
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), reasons = new Map();
198
+ const claimedNow = new Set(runs.flatMap(run => run.coverage?.claimed ?? []));
199
+ const note = (reason, example) => { const entry = reasons.get(reason) ?? { count: 0, examples: [] }; reasons.set(reason, entry); entry.count++; if (entry.examples.length < limits.nodes) entry.examples.push(example); };
200
+ for (const run of runs) for (const { reason, name } of run.coverage?.skipped ?? []) note(reason, { scenario: run.scenario, theme: run.theme, ...(run.brand ? { brand: run.brand } : {}), name });
201
+ for (const { claim, reason, ...example } of capped) if (!claimedNow.has(claim)) note(reason, example);
202
+ const coverage = { renders: runs.length, overlaysOpened: 0, controlsMeasured: 0, skipped: Object.fromEntries([...reasons].sort(([a], [b]) => a.localeCompare(b))) };
203
+ const empty = [];
204
+ for (const run of runs) if (run.coverage) {
205
+ coverage.overlaysOpened += run.coverage.overlays; coverage.controlsMeasured += run.coverage.controls;
206
+ // A trigger that opened nothing is not a failure to measure: that is a skip, and the rest of the render stands.
207
+ const failed = run.coverage.skipped.filter(item => /^(?:overlay|control)-(?:gone|timeout|detached|failed)$/.test(item.reason)).length;
208
+ if (failed && !run.coverage.overlays && !run.coverage.controls) empty.push(run);
209
+ }
210
+ const findings = [...reasons].map(([reason, { count, examples }]) => ({
211
+ rule: "browser-audit-skipped", severity: findingSeverity("browser-audit-skipped"), file: files.get(examples[0].scenario) ?? examples[0].scenario, line: 1, column: 1, source: "ads", reason, count, examples, guidanceUri: "ads://guides/accessibility",
212
+ message: `The audit skipped ${count} target${count === 1 ? "" : "s"}: ${skipReasons[reason] ?? reason}. ${examples.slice(0, 3).map(item => `"${item.name}" in ${item.scenario} [${item.theme}]`).join(", ")}${count > 3 ? ` and ${count - 3} more` : ""}.`,
213
+ }));
214
+ for (const run of empty) findings.push({ rule: "browser-audit-nothing-measured", severity: findingSeverity("browser-audit-nothing-measured"), file: files.get(run.scenario) ?? run.scenario, line: 1, column: 1, source: "ads", scenario: run.scenario, themes: [run.theme], message: `Nothing the audit tried to open or hover in ${run.scenario} [${run.theme}] could be measured: ${[...new Set(run.coverage.skipped.map(item => item.reason))].join(", ")}.` });
215
+ return { coverage, findings };
216
+ }
217
+
162
218
  /** One error per scenario above the threshold, with its worst score, themes, brands and elements. */
163
219
  export function layoutShiftFindings(runs, scenarios) {
164
220
  const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
@@ -182,10 +238,15 @@ export function layoutShiftFindings(runs, scenarios) {
182
238
  * scenario; so does a failure to trace imports. Public/review entry re-exports are bookkeeping
183
239
  * for their own units and do not widen the selection.
184
240
  */
185
- export function auditScenarioSelection(options, changedFiles) {
241
+ /** "owners": the changed owners' own scenarios. "affected": every scenario the change reaches. */
242
+ export function auditScenarioSelection(options, changedFiles, { mode = "affected", owners = [] } = {}) {
186
243
  const scenarios = inspectScenarios(options).scenarios.filter(scenario => auditedKinds.includes(scenario.kind));
187
244
  const all = reason => ({ mode: "all", reason, scenarios: scenarios.map(scenario => scenario.id) });
188
245
  const inventory = inspectUnits(options), entries = [inventory.publicEntry, inventory.reviewEntry];
246
+ if (mode === "owners") {
247
+ const changed = new Set([...owners, ...changedFiles.map(file => inventory.owner(inventory.relative(file))).filter(Boolean)]);
248
+ return { mode: "owners", reason: "Owners' own scenarios; the validation stage audits everything they affect.", scenarios: scenarios.filter(scenario => changed.has(inventory.owner(inventory.relative(scenario.file)))).map(scenario => scenario.id) };
249
+ }
189
250
  const traced = changedFiles.filter(file => !entries.includes(inventory.relative(file)));
190
251
  const shared = traced.find(file => {
191
252
  const owner = inventory.owner(inventory.relative(file));
@@ -200,7 +261,7 @@ export function auditScenarioSelection(options, changedFiles) {
200
261
  export function auditCheck(audit, extra = {}) {
201
262
  const routed = routeFindings([], audit.findings);
202
263
  return { routed, check: { name: "browser-accessibility-audit", passed: !routed.diagnostics.length, engine: audit.engine, scenarios: audit.scenarios, themes: audit.themes, ...(audit.brands ? { brands: audit.brands } : {}),
203
- renders: audit.runs, ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
264
+ renders: audit.runs, ...(audit.coverage ? { coverage: audit.coverage } : {}), ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
204
265
  }
205
266
 
206
267
  function projectPlaywright(root) {
@@ -245,10 +306,10 @@ async function warmScenariosApart(host, ids, signal) {
245
306
 
246
307
  /** One browser process over the given renders. Its report grows as they finish, so a worker that
247
308
  * dies keeps what it finished. A browser that is not installed stops the audit. */
248
- async function runAuditWorker({ root, temporary, playwright, settings, apps, signal }) {
309
+ async function runAuditWorker({ root, temporary, playwright, settings, apps, signal, claimed, pages }) {
249
310
  const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
250
311
  rmSync(report, { force: true });
251
- writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, overlayLimit: limits.overlays, stateLimit: limits.controls, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
312
+ 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: pages, apps, output: temporary }));
252
313
  const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
253
314
  let cause;
254
315
  try {
@@ -259,10 +320,10 @@ async function runAuditWorker({ root, temporary, playwright, settings, apps, sig
259
320
  if (signal.aborted || error.code === "ADS_AUDIT_UNAVAILABLE") throw error;
260
321
  cause = clipCause(error.message);
261
322
  }
262
- if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], cause: cause ?? "Accessibility audit produced no bounded report." };
323
+ if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], capped: [], cause: cause ?? "Accessibility audit produced no bounded report." };
263
324
  const value = JSON.parse(readFileSync(report, "utf8"));
264
- if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
265
- return { runs: value.runs, cause };
325
+ if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], capped: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
326
+ return { runs: value.runs, capped: value.capped ?? [], cause };
266
327
  }
267
328
 
268
329
  /** A scenario that could not be audited is an error naming it and its last cause, never a pass. */
@@ -320,7 +381,7 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
320
381
  const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
321
382
  const floating = floatingScenarios(options, scenarios);
322
383
  const wanted = themes.flatMap(theme => (brands.length ? brands : [undefined]).flatMap(brand => scenarios.map(scenario => ({ scenario: scenario.id, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, ...(theme === themes[0] && containerKinds.includes(scenario.kind) && !floating.has(scenario.id) ? { container: containerWidth } : {}) }))));
323
- const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }]));
384
+ const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }])), capped = new Map();
324
385
  onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${wanted.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
325
386
  for (let attempt = 1; attempt <= auditAttempts; attempt++) {
326
387
  const pending = [...renders.values()].filter(render => !render.result);
@@ -338,7 +399,8 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
338
399
  if (app.brand) url.searchParams.set("brand", app.brand);
339
400
  return { ...app, url: url.href };
340
401
  });
341
- const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal }) : { runs: [] };
402
+ const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal, pages: options.config.mcp.auditPages, claimed: [...renders.values()].flatMap(render => render.result?.coverage?.claimed ?? []) }) : { runs: [], capped: [] };
403
+ for (const item of reached.capped ?? []) capped.set(item.claim, item);
342
404
  for (const run of reached.runs) {
343
405
  const render = renders.get(renderKey(run));
344
406
  if (!render) continue;
@@ -354,9 +416,10 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
354
416
  }
355
417
  const all = [...renders.values()], runs = all.map(render => render.result ?? render.partial).filter(Boolean);
356
418
  const retries = all.filter(render => render.result && render.attempts > 1).map(({ app, attempts, causes }) => ({ scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), attempts, causes }));
357
- const findings = [...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
419
+ const { coverage, findings: coverageItems } = auditCoverage(all.map(render => render.result).filter(Boolean), [...capped.values()], scenarios);
420
+ const findings = [...coverageItems, ...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...imageShapeFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
358
421
  const shifts = runs.filter(run => run.layoutShift).sort((a, b) => b.layoutShift.value - a.layoutShift.value);
359
- return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: findings.filter(finding => finding.rule === INCOMPLETE_RULE).length, overlaysOpened: runs.reduce((sum, run) => sum + (run.overlays ?? 0), 0), controlsMeasured: runs.reduce((sum, run) => sum + (run.controls ?? 0), 0), findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
422
+ return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: findings.filter(finding => finding.rule === INCOMPLETE_RULE).length, overlaysOpened: coverage.overlaysOpened, controlsMeasured: coverage.controlsMeasured, coverage, findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
360
423
  } finally {
361
424
  try { if (host !== previewHost) await host?.close(); } finally { rmSync(temporary, { recursive: true, force: true }); }
362
425
  }
@@ -7,19 +7,26 @@ import { createBunPreviewBuilder } from "./preview-bun.mjs";
7
7
  import { checkCandidate } from "./validation-checks.mjs";
8
8
  import { renderStoppingRules } from "./finding-rules.mjs";
9
9
 
10
- /** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
11
- export async function compilePreviews(directory=process.cwd(),{watched=false}={}) {
12
- const root=path.resolve(directory);
13
- const compilerFiles=[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))];
14
- async function validate(){
10
+ const compilerFiles=[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))];
11
+
12
+ function validator(root){
13
+ return async function validate(){
15
14
  const result=await checkCandidate(root);
16
15
  if(result.ok)return true;
17
16
  // A session the audit started renders despite policy errors and reports them; it records no pass.
18
17
  const stopping=process.env.ADS_PREVIEW_DESPITE_POLICY==="1"?result.diagnostics.filter(item=>renderStoppingRules.has(item.rule)):result.diagnostics;
19
18
  if(stopping.length)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:stopping});
20
19
  return false;
21
- }
20
+ };
21
+ }
22
+
23
+ /** The same ADS-owned Bun compiler serves MCP, standalone builds and CI. */
24
+ export async function compilePreviews(directory=process.cwd(),{watched=false}={}) {
25
+ const root=path.resolve(directory);
22
26
  if(!watched){const restored=await restoreCompiledPreviews(withPreviewSession(loadConfig(root),process.env.ADS_MCP_BUILD_SESSION),compilerFiles);if(restored)return restored;}
23
- return runScenarioCompiler(root,{watched,compilerFiles,validate,buildGraph:createBunPreviewBuilder()});
27
+ // Each root, the project's and every hosted draft's, gets its own validator and Bun builder.
28
+ const main=await runScenarioCompiler(root,projectRoot=>({watched,compilerFiles,validate:validator(projectRoot),buildGraph:createBunPreviewBuilder()}));
29
+ if(watched)for(const signal of ["SIGINT","SIGTERM"])process.once(signal,()=>main?.stop());
30
+ return main;
24
31
  }
25
32
  if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))await compilePreviews(process.cwd(),{watched:process.argv.includes("--watch")});
@@ -0,0 +1,83 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads";
3
+ import path from "node:path";
4
+ import { architectureTaskInputs } from "./task-cache.mjs";
5
+
6
+ // Long-lived ADS processes (the MCP server and its preview compiler) run `ads check` in one warm
7
+ // worker thread instead of a fresh Turbo task per check. The worker keeps its TypeScript programs
8
+ // and parsed files (program-cache.mjs), so a check after an edit reparses only what changed. An
9
+ // exact repeat of the same inputs returns the remembered report. One-shot CLI and CI checks keep
10
+ // the Turbo task and its persistent cache.
11
+
12
+ const hash = value => createHash("sha256").update(JSON.stringify(value)).digest("hex");
13
+
14
+ if (!isMainThread && workerData?.adsCheckService) {
15
+ const { checkProject } = await import("./check.mjs");
16
+ parentPort.on("message", ({ id, root, trackingRoot }) => {
17
+ try { parentPort.postMessage({ id, result: JSON.parse(JSON.stringify(checkProject(root, { trackingRoot }))) }); }
18
+ catch (error) { parentPort.postMessage({ id, error: error.message }); }
19
+ });
20
+ }
21
+
22
+ let worker, sequence = 0;
23
+ const pending = new Map(), remembered = new Map(), limit = 16;
24
+ let queue = Promise.resolve();
25
+
26
+ function start() {
27
+ if (worker) return worker;
28
+ worker = new Worker(new URL(import.meta.url), { workerData: { adsCheckService: true } });
29
+ worker.unref();
30
+ const current = worker;
31
+ worker.on("message", ({ id, result, error }) => {
32
+ const task = pending.get(id); pending.delete(id);
33
+ if (task) { if (error) task.reject(new Error(error)); else task.resolve(result); }
34
+ });
35
+ const fail = failure => { if (worker !== current) return; for (const task of pending.values()) task.reject(failure); pending.clear(); worker = undefined; };
36
+ worker.on("error", fail);
37
+ worker.on("exit", code => fail(new Error(`ADS check worker exited (${code}).`)));
38
+ return worker;
39
+ }
40
+
41
+ function cancelled() { return Object.assign(new Error("Mutation cancelled during validation."), { diagnostic: { rule: "mutation-cancelled", message: "Mutation cancelled during validation." } }); }
42
+
43
+ /** A synchronous check cannot be interrupted inside the thread, so cancelling ends the worker. */
44
+ function run(root, trackingRoot, signal) {
45
+ const id = ++sequence;
46
+ return new Promise((resolve, reject) => {
47
+ const abort = () => { if (pending.delete(id)) { reject(cancelled()); void stopWarmChecks(); } };
48
+ pending.set(id, { resolve: value => { signal?.removeEventListener("abort", abort); resolve(value); }, reject: error => { signal?.removeEventListener("abort", abort); reject(error); } });
49
+ signal?.addEventListener("abort", abort, { once: true });
50
+ start().postMessage({ id, root, trackingRoot });
51
+ });
52
+ }
53
+
54
+ /** End the warm worker; the next check starts a fresh one. The server calls this on shutdown. */
55
+ export async function stopWarmChecks() {
56
+ const current = worker; worker = undefined;
57
+ for (const task of pending.values()) task.reject(cancelled()); pending.clear();
58
+ await current?.terminate();
59
+ }
60
+
61
+ /** One check at a time in the warm worker, with the same result shape as the Turbo task. */
62
+ export function warmCheck(root, trackingRoot = root, signal, { fresh = false } = {}) {
63
+ const job = queue.then(async () => {
64
+ if (signal?.aborted) throw cancelled();
65
+ const started = Date.now(), key = hash(architectureTaskInputs(root, trackingRoot));
66
+ if (!fresh && remembered.has(key)) return { ...remembered.get(key), cache: { backend: "warm", task: "architecture", key, status: "hit", elapsedMs: Date.now() - started } };
67
+ const result = await run(root, trackingRoot, signal);
68
+ if (hash(architectureTaskInputs(root, trackingRoot)) !== key) throw Object.assign(new Error("Source, dependencies or Git tracking changed during the ADS task; retry against the current inputs."), { code: "ADS_SOURCE_CHANGED" });
69
+ // Only successful reports are remembered, as with the Turbo task.
70
+ if (result.ok !== false) { remembered.delete(key); remembered.set(key, result); while (remembered.size > limit) remembered.delete(remembered.keys().next().value); }
71
+ return { ...result, cache: { backend: "warm", task: "architecture", key, status: fresh ? "fresh" : "miss", elapsedMs: Date.now() - started } };
72
+ });
73
+ queue = job.catch(() => {});
74
+ return job;
75
+ }
76
+
77
+ // Projects whose checks run warm in this process: the MCP server registers its own root.
78
+ // A separate long-lived process (the preview compiler) opts in through ADS_WARM_CHECKS.
79
+ const warmRoots = new Set();
80
+ export function useWarmChecks(root) { warmRoots.add(path.resolve(root)); }
81
+ export function releaseWarmChecks(root) { warmRoots.delete(path.resolve(root)); if (!warmRoots.size) void stopWarmChecks(); }
82
+ /** Whether checks tracked against this project run in the warm worker. */
83
+ export function warmChecksFor(trackingRoot) { return process.env.ADS_WARM_CHECKS === "1" || warmRoots.has(path.resolve(trackingRoot)); }
package/dist/check.mjs CHANGED
@@ -8,14 +8,14 @@ import { inspectTokens, references } from "./tokens.mjs";
8
8
  import { displaySwitches, generatedPaletteFile, generatedThemeFiles } from "./themes-generated.mjs";
9
9
  import { createRenderColorProbe } from "./render-color-probe.mjs";
10
10
  import { themeAncestorSelector } from "./themes.mjs";
11
- import { foundationFiles, foundationImportTarget, isSharedToken } from "./token-policy.mjs";
11
+ import { isSharedToken } from "./token-policy.mjs";
12
12
  import { inspectAssets } from "./assets.mjs";
13
13
  import { a11ySourceAdvisories } from "./a11y.mjs";
14
14
  import { appImportViolation, showcaseImportViolation, checkComponentVariable, importResolver, projectCompilerOptions, isUiCssProperties, styleWriteViolation } from "./boundaries.mjs";
15
15
  import { inspectPublicProps } from "./public-props.mjs";
16
16
  import { adsFileRole } from "./config.mjs";
17
17
  import { inspectPaintContracts, inspectTokenValueFlows } from "./paint-contracts.mjs";
18
- import { runtimeBindingOwner } from "./unit-contracts.mjs";
18
+ import { ownerStylePolicy, runtimeBindingOwner } from "./unit-contracts.mjs";
19
19
  import { inspectRuntimeContracts } from "./runtime-contracts.mjs";
20
20
  import { inspectHtml, isMountCss } from "./html.mjs";
21
21
  import { inspectShowcasePages } from "./showcase.mjs";
@@ -27,6 +27,8 @@ import { inspectBehaviors, inspectControllers } from "./behaviors.mjs";
27
27
  import { numericCssUnit, tokenLengthLiteral } from "./css-values.mjs";
28
28
  import { foundationDeclaration, foundationSelector } from "./foundation.mjs";
29
29
  import { inspectUnits } from "./units.mjs";
30
+ import { generatedEntryDiagnostics } from "./generated-entries.mjs";
31
+ import { cachedProgram } from "./program-cache.mjs";
30
32
  import { createAtomicCompositionReview } from "./atomic-composition.mjs";
31
33
  import { createScenarioTrace } from "./scenario-trace.mjs";
32
34
  import { createScenarioSlots } from "./scenario-slots.mjs";
@@ -40,12 +42,13 @@ import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
40
42
  import { inspectUsage } from "./usage.mjs";
41
43
  import { controlPaddingAdvisories } from "./control-padding.mjs";
42
44
  import { createComponentContrast } from "./component-contrast.mjs";
45
+ import { createFontRules } from "./font-rules.mjs";
43
46
  import { createLayoutWidths, globMatcher } from "./layout-widths.mjs";
44
47
  import { imageAttributeFindings } from "./image-attributes.mjs";
45
48
  import { findingSeverity, routeFindings } from "./finding-rules.mjs";
46
49
 
47
50
  const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
48
- const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
51
+ const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve the owner contract's styles.inline for documented measured geometry, not demo layout.`;
49
52
 
50
53
  const showcaseControls = new Set(["a", "button", "input", "select", "textarea", "option", "optgroup", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "dialog", "details", "summary", "progress", "meter"]);
51
54
  const svgTags = new Set(["svg", "g", "path", "circle", "rect", "ellipse", "line", "polyline", "polygon", "text", "tspan", "use", "defs", "clipPath", "mask", "filter", "linearGradient", "radialGradient", "stop", "marker", "pattern"]);
@@ -60,6 +63,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
60
63
  if (!existsSync(file) || (field === "dsDir" ? !statSync(file).isDirectory() : !statSync(file).isFile())) diagnostics.push({ rule: "project-structure", file: path.relative(root, file), line: 1, column: 1, message: `Missing or invalid ${field}. Bootstrap an empty ADS or configure its actual path.` });
61
64
  }
62
65
  if (diagnostics.length) return architectureEvidence({ ok: false, diagnostics });
66
+ diagnostics.push(...generatedEntryDiagnostics(options, inspectUnits(options)));
63
67
  const tokenInventory = inspectTokens(root, options);
64
68
  const declaredTokens = new Set(tokenInventory.tokens.map((token) => token.name));
65
69
  // Display switches are defined by the generated themes.generated.css, not a token sheet.
@@ -74,10 +78,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
74
78
  const configurationScripts=new Set((units.units.find(unit=>unit.id==="configuration")?.files??[]).filter(file=>/\.[cm]?[jt]sx?$/.test(file)).map(file=>path.resolve(root,file)).filter(file=>existsSync(file)&&statSync(file).isFile()));
75
79
  const rootHtml = path.join(root, "index.html");
76
80
  const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...configurationScripts, ...(existsSync(rootHtml) ? [rootHtml] : [])])];
77
- const boundaryFiles = [...config.inlineStyleFiles, ...config.boundaries.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
81
+ const stylePolicy = ownerStylePolicy(options);
82
+ const boundaryFiles = [...stylePolicy.inlineStyleFiles, ...stylePolicy.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
78
83
  const scriptFiles = [...new Set([...layerSourceFiles([...new Set([...files, ...boundaryFiles])].filter((file) => /\.[cm]?[jt]sx?$/.test(file)), options), ...configurationScripts])];
79
84
  const compiler = projectCompilerOptions(options);
80
- const program = ts.createProgram(scriptFiles, { ...compiler, paths: { ...compiler.paths, [config.publicAlias]: [path.join(dsRoot, config.publicEntry)] }, allowJs: true, noResolve: true, noLib: true, types: [], target: ts.ScriptTarget.Latest, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.Preserve });
85
+ const program = cachedProgram(`check:${root}`, scriptFiles, { ...compiler, paths: { ...compiler.paths, [config.publicAlias]: [path.join(dsRoot, config.publicEntry)] }, allowJs: true, noResolve: true, noLib: true, types: [], target: ts.ScriptTarget.Latest, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.Preserve });
81
86
  const checker = program.getTypeChecker();
82
87
  diagnostics.push(...inspectBehaviorLibraries(options, program).diagnostics);
83
88
  const designValues = createDesignValues(program,options);
@@ -113,6 +118,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
113
118
  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
119
  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
120
  const ownerFixedWidths = [];
121
+ const fontRules = createFontRules(options, tokenInventory.tokens);
116
122
  function checkRegistrations(file,css,offset={line:1}){
117
123
  css.walkAtRules(/^property$/i,rule=>{
118
124
  const line=offset.line+(rule.source?.start.line??1)-1;
@@ -135,19 +141,13 @@ export function checkProject(directory, { trackingRoot } = {}) {
135
141
  }catch(error){report(file,"property-registration",`${error.message} See ads://guides/atomic-styles.`,line,rule.source?.start.column??1);diagnostics.at(-1).guidanceUri="ads://guides/atomic-styles";}
136
142
  });
137
143
  }
138
- try {
139
- const css = postcss.parse(readFileSync(foundationEntry, "utf8"), { from: foundationEntry });
140
- const imports = css.nodes.filter((node) => node.type !== "comment");
141
- const expected = foundationFiles.filter((name) => name !== "fonts.css" || existsSync(path.join(dsRoot, config.tokenDir, name))).map((name) => path.join(dsRoot, config.tokenDir, name));
142
- const actual = imports.map(node => foundationImportTarget(node, foundationEntry));
143
- if (actual.length !== expected.length || actual.some((file, index) => file !== expected[index] || !existsSync(file))) report(foundationEntry, "styles-entry", "Foundation CSS must import only fonts (when present), colors, typography, spacing, elevation, base and the generated themes.generated.css, in that order.");
144
- } catch (error) { report(foundationEntry, "css-syntax", error.reason ?? error.message, error.line ?? 1); }
145
144
  function checkCss(file, text, offset = { line: 1, column: 1 }, foundation = false) {
146
145
  let css;
147
146
  try { css = postcss.parse(text, { from: file }); }
148
147
  catch (error) { report(file, "css-syntax", error.reason ?? error.message, offset.line + (error.line ?? 1) - 1); return; }
149
148
  layers.collectComponentStyles(file, css);
150
149
  layerStyles.push({ file, css, offset });
150
+ if (foundation || !isDevelopmentFile(file, options)) fontRules.collect(css, file, offset);
151
151
  checkRegistrations(file,css,offset);
152
152
  if (!foundation && !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file))) componentContrast.collect(path.relative(root, file).replaceAll("\\", "/"), css, offset);
153
153
  if (!foundation && (isInside(path.join(dsRoot, "composition"), file) || !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file)))) {
@@ -234,8 +234,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
234
234
  }
235
235
  for (const file of files) {
236
236
  const role = adsFileRole(file);
237
- const roleExtension=role==="contract"?/\.[cm]?ts$/.test(file):["fixture","fixtures"].includes(role)?/\.(?:[cm]?[jt]sx?|json)$/.test(file):/\.[cm]?[jt]sx?$/.test(file);
238
- if (role && !configurationScripts.has(file) && (!["contract", "scenario", "fixture", "fixtures", "helpers", "test", "spec", "behavior.spec"].includes(role)||!roleExtension)) report(file, "development-role", `Unknown .ads. role or unsupported extension: ${role}. Use a TypeScript contract, a script scenario/fixture/helpers/test/behavior.spec, or JSON fixture; marking development code does not grant styling or mutation permissions.`);
237
+ const roleExtension=["contract","exports"].includes(role)?/\.[cm]?ts$/.test(file):["fixture","fixtures"].includes(role)?/\.(?:[cm]?[jt]sx?|json)$/.test(file):/\.[cm]?[jt]sx?$/.test(file);
238
+ if (role && !configurationScripts.has(file) && (!["contract", "exports", "scenario", "fixture", "fixtures", "helpers", "test", "spec", "behavior.spec"].includes(role)||!roleExtension)) report(file, "development-role", `Unknown .ads. role or unsupported extension: ${role}. Use a TypeScript contract, a script scenario/fixture/helpers/test/behavior.spec, or JSON fixture; marking development code does not grant styling or mutation permissions.`);
239
239
  // The generated theme sheet and palette are checked for freshness with the tokens, not authored.
240
240
  if (generatedThemeFiles.some(generated => file === path.join(dsRoot, config.tokenDir, generated))) continue;
241
241
  if (file.endsWith(".css") && isInside(path.join(dsRoot, config.tokenDir), file) && !isDevelopmentFile(file, options)) { checkCss(file, readFileSync(file, "utf8"), undefined, true); continue; }
@@ -254,7 +254,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
254
254
  const position = source.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
255
255
  report(file, "source-syntax", ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), position.line + 1, position.character + 1);
256
256
  }
257
- const inlineAllowed = config.inlineStyleFiles.some((allowed) => path.resolve(root, allowed) === file);
257
+ const inlineAllowed = stylePolicy.inlineStyleFiles.some((allowed) => path.resolve(root, allowed) === file);
258
258
  const showcase = isDevelopmentFile(file, options) && !isTestFile(file) && !isReviewFile(file, options);
259
259
  function nodeReport(node, rule, message, detail) {
260
260
  const position = source.getLineAndCharacterOfPosition(node.getStart(source));
@@ -309,6 +309,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
309
309
  if (svgPresentation.has(name)) nodeReport(node, "svg-attribute", `Native Preact SVG needs ${name.replace(/[A-Z]/g, letter => "-" + letter.toLowerCase())}; React-style ${name} is not normalized by its native renderer.`);
310
310
  }
311
311
  const lightDarkLiterals = ["components", "patterns"].some(section => isInside(path.join(dsRoot, section), file)) && !isDevelopmentFile(file, options);
312
+ // Per-file facts, computed once rather than at every syntax node.
313
+ const fileInDs = isInside(dsRoot, file);
312
314
  function inLinariaTemplate(node) {
313
315
  const template = ts.isTemplateMiddle(node) || ts.isTemplateTail(node) ? node.parent.parent : node.parent;
314
316
  const tagged = ts.isTemplateExpression(template) ? template.parent : template;
@@ -337,11 +339,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
337
339
  if (showcaseControls.has(tag.text) || role && ts.isStringLiteralLike(role) && widgetRoles.has(role.text)) scenarioControl(node, showcaseControls.has(tag.text));
338
340
  }
339
341
  }
340
- if (isInside(dsRoot, file) && (ts.isIdentifier(node) && ["fetch", "XMLHttpRequest", "WebSocket", "EventSource"].includes(node.text) && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node))) {
342
+ if (fileInDs && (ts.isIdentifier(node) && ["fetch", "XMLHttpRequest", "WebSocket", "EventSource"].includes(node.text) && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node))) {
341
343
  const declarations = checker.getSymbolAtLocation(node)?.declarations ?? [];
342
344
  if (!declarations.some((declaration) => !declaration.getSourceFile().isDeclarationFile)) nodeReport(node, "data-access", "ADS UI and scenarios receive business data through typed inputs or injected services. Direct network access belongs in an application adapter; fixture services remain local.");
343
345
  }
344
- if (isInside(dsRoot, file) && ts.isPropertyAccessExpression(node) && ["window", "globalThis", "self"].includes(node.expression.getText(source)) && ["fetch", "XMLHttpRequest", "WebSocket", "EventSource"].includes(node.name.text)) nodeReport(node, "data-access", "Inject the data service instead of using a global network API in ADS UI or scenarios.");
346
+ if (fileInDs && ts.isPropertyAccessExpression(node) && ["window", "globalThis", "self"].includes(node.expression.getText(source)) && ["fetch", "XMLHttpRequest", "WebSocket", "EventSource"].includes(node.name.text)) nodeReport(node, "data-access", "Inject the data service instead of using a global network API in ADS UI or scenarios.");
345
347
  if (showcase && (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) && ts.isIdentifier(node.tagName) && /^[a-z]/.test(node.tagName.text)) {
346
348
  const role = node.attributes.properties.find((attr) => ts.isJsxAttribute(attr) && attr.name.text === "role")?.initializer;
347
349
  const roleValue = role && ts.isStringLiteralLike(role) ? role.text : role && ts.isJsxExpression(role) && role.expression && ts.isStringLiteralLike(role.expression) ? role.expression.text : null;
@@ -383,7 +385,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
383
385
  }
384
386
  inspectDesignAliases(layerStyles,options,report);
385
387
  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));
388
+ advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths), ...fontRules.findings());
387
389
  // Errors block by class; bounded clients see review items before informational limits.
388
390
  const routed=routeFindings(diagnostics,advisories);
389
391
  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
@@ -28,7 +28,8 @@ Usage: ads create <directory> --framework react|preact New design-system proje
28
28
  --format dtcg prints them as W3C Design Tokens JSON;
29
29
  --theme <name> exports that theme's values (default: the first)
30
30
  --brand <name> exports that brand's values (default: the first)
31
- assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts
31
+ assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts,
32
+ the styles entry, and the public/review barrels from .ads.exports.ts files
32
33
  lint-config [dir] Generate .ds/oxlintrc.json with core and project plugins
33
34
  mcp [directory] Serve stdio MCP tools/Apps and the local showcase website
34
35
  showcase [directory] Serve the built-in MCP client website (no stdio connection)
@@ -186,7 +187,7 @@ async function main(args) {
186
187
  }
187
188
  else if (command === "tokens" && format === "dtcg") { const { exportTokensDtcg } = await import("./token-export.mjs"); console.log(JSON.stringify(exportTokensDtcg(target, { theme, brand }), null, 2)); return; }
188
189
  else if (command === "tokens") result = inspectTokens(target);
189
- else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const themes = refreshThemesCss(target); result = { ...await generateBrandAssets(target), themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written }, ...(themes.files[2] ? { fontPreloads: { file: themes.files[2].file, written: themes.files[2].written } } : {}) } : {}) }; }
190
+ else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const { writeGeneratedEntries } = await import("./generated-entries.mjs"); const themes = refreshThemesCss(target), barrels = writeGeneratedEntries(loadConfig(target)).files.map(({ file, changed }) => ({ file, written: changed })); result = { ...await generateBrandAssets(target), barrels, themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written }, ...(themes.files[2] ? { fontPreloads: { file: themes.files[2].file, written: themes.files[2].written } } : {}) } : {}) }; }
190
191
  else if (command === "lint-config") result = generateLintConfig(target);
191
192
  else throw new Error(`Unknown command: ${command}. Run ads --help.`);
192
193
  // Bun ends a piped stdout at its buffer unless the write is awaited.
@@ -198,11 +199,12 @@ async function main(args) {
198
199
  const themesFile = path.relative(process.cwd(), result.themes.file) || result.themes.file;
199
200
  console.log(result.themes.skipped ? `Skipped ${themesFile}: the token sheets still use the old theme form.` : `${result.themes.written ? "Wrote" : "Unchanged"} ${themesFile}.`);
200
201
  if (result.palette) console.log(`${result.palette.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.palette.file) || result.palette.file}.`);
202
+ for (const barrel of result.barrels) console.log(`${barrel.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), barrel.file) || barrel.file}.`);
201
203
  if (result.fontPreloads) console.log(`${result.fontPreloads.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.fontPreloads.file) || result.fontPreloads.file}.`);
202
204
  }
203
205
  else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
204
206
  else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
205
- else if (command === "audit") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS accessibility audit (${result.engine}): ${findingCounts(result.diagnostics.length, result.findings.filter(finding => finding.severity === "review").length)}, ${result.incomplete ?? 0} that axe could not decide across ${result.scenarios} scenarios × ${result.themes.length} themes (${result.themes.join(", ")})${result.brands ? ` × ${result.brands.length} brands (${result.brands.join(", ")})` : ""}.`); if (result.retries) console.log(`Retried ${result.retries.length} render${result.retries.length === 1 ? "" : "s"} that then passed: ${result.retries.map(retry => `${retry.scenario} [${[retry.theme, retry.brand].filter(Boolean).join(", ")}] in ${retry.attempts} attempts`).join("; ")}.`); for (const finding of result.findings) console.error(`${finding.file}:${finding.line}:${finding.column} [${finding.severity}:${finding.rule}] ${finding.message}`); }
207
+ 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}`); }
206
208
  else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
207
209
  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})`:""}`);}
208
210
  else if (command === "tokens") {