@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
package/dist/config.mjs CHANGED
@@ -3,7 +3,6 @@ import path from "node:path";
3
3
  import { hasProjectConfig } from "./project-boundary.mjs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { isDraftFile, draftImportViolation } from "./draft-boundary.mjs";
6
- import { isSharedToken } from "./token-policy.mjs";
7
6
  import { defaultThemes, validateThemes } from "./themes.mjs";
8
7
  import { validateBrands } from "./brands.mjs";
9
8
 
@@ -26,16 +25,14 @@ export const defaultConfig = {
26
25
  brands: [],
27
26
  // With no data-theme on the root, the OS color scheme picks the first theme of that scheme.
28
27
  followSystemTheme: false,
29
- inlineStyleFiles: [],
30
- boundaries: { styleWrites: [], componentVariables: [] },
31
- assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null, imageBudgetKb: null },
28
+ assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null, targets: [], glyphs: null, imageBudgetKb: null, fontBudgetKb: null, preloadFonts: null },
32
29
  oxlint: { plugins: [], rules: {}, overrides: [] },
33
- acceptance: { checks: [], behaviorChecks: false, browserAudit: true },
30
+ acceptance: { checks: [], behaviorChecks: false, browserAudit: "owners" },
34
31
  validation: { checks: [], behaviorChecks: true, browserAudit: true, inputs: [] },
35
32
  resources: { memoryLimitMb: null },
36
33
  // Width tokens and owners allowed fixed widths; see src/layout-widths.mjs.
37
34
  layout: { widthTokens: [], fixedWidthUnits: [] },
38
- mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {}, resultRetention: {maxRuns:50,maxAgeDays:7,maxBytesMb:256} },
35
+ mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, previewBuildTimeoutMs: 300000, auditPages: 4, behaviorProfiles: {}, capture: {}, resultRetention: {maxRuns:50,maxAgeDays:7,maxBytesMb:256} },
39
36
  };
40
37
 
41
38
  export function isInside(parent, file) {
@@ -115,12 +112,11 @@ export function loadConfig(directory = process.cwd()) {
115
112
  if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
116
113
  }
117
114
  if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
118
- if (user.mcp && Object.hasOwn(user.mcp,"mutationChecks")) throw new Error("Move mcp.mutationChecks to acceptance.checks; choose acceptance.behaviorChecks explicitly. ADS no longer infers project scripts.");
119
- for (const field of ["boundaries", "assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources", "layout"]) {
115
+ for (const field of ["assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources", "layout"]) {
120
116
  if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
121
117
  for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
122
118
  }
123
- const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, acceptance: { ...defaultConfig.acceptance, ...user.acceptance }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources }, layout: { ...defaultConfig.layout, ...user.layout } };
119
+ const config = { ...defaultConfig, ...user, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, acceptance: { ...defaultConfig.acceptance, ...user.acceptance }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources }, layout: { ...defaultConfig.layout, ...user.layout } };
124
120
  validateThemes(config.themes);
125
121
  validateBrands(config.brands);
126
122
  if (typeof config.followSystemTheme !== "boolean") throw new Error("followSystemTheme must be true or false.");
@@ -131,6 +127,8 @@ export function loadConfig(directory = process.cwd()) {
131
127
  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
128
  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
129
  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.");
130
+ 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 }.');
131
+ 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
132
  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
133
  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
134
  if (!Array.isArray(config.usage.notifications) || config.usage.notifications.length > 100) throw new Error("usage.notifications must be an array of notification API registrations.");
@@ -150,7 +148,8 @@ export function loadConfig(directory = process.cwd()) {
150
148
  const policy=config[name];
151
149
  if (!Array.isArray(policy.checks) || policy.checks.length>20 || new Set(policy.checks).size!==policy.checks.length || policy.checks.some(script=>typeof script!=="string" || !/^[a-zA-Z0-9][\w:.-]*$/.test(script))) throw new Error(`${name}.checks must contain up to 20 unique package script names.`);
152
150
  if(typeof policy.behaviorChecks!=="boolean")throw new Error(`${name}.behaviorChecks must be a boolean.`);
153
- if(typeof policy.browserAudit!=="boolean")throw new Error(`${name}.browserAudit must be a boolean.`);
151
+ // Acceptance audits the draft's own owners, or everything they affect; the validation stage audits fully.
152
+ if(name==="acceptance"?!["owners","affected",false].includes(policy.browserAudit):typeof policy.browserAudit!=="boolean")throw new Error(name==="acceptance"?'acceptance.browserAudit must be "owners" (the draft owners\' own scenarios), "affected" (every scenario they reach) or false.':`${name}.browserAudit must be a boolean.`);
154
153
  }
155
154
  if (!Array.isArray(config.validation.inputs) || config.validation.inputs.length > 200 || new Set(config.validation.inputs).size !== config.validation.inputs.length) throw new Error("validation.inputs must contain at most 200 unique project-relative files or directories.");
156
155
  for (const file of config.validation.inputs) {
@@ -163,22 +162,10 @@ export function loadConfig(directory = process.cwd()) {
163
162
  || new Set(config.behaviorLibraries).size !== config.behaviorLibraries.length
164
163
  || config.behaviorLibraries.some(name => typeof name !== "string" || name.length > 214 || !/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(name))) throw new Error("behaviorLibraries must contain up to 100 unique npm package names, without versions, subpaths or wildcards.");
165
164
  if (typeof config.publicAlias !== "string" || !config.publicAlias.trim()) throw new Error("publicAlias must be a non-empty string.");
166
- if (!Array.isArray(config.inlineStyleFiles)) throw new Error("inlineStyleFiles must be an array of relative paths.");
167
165
  const sourceRoot = projectPath(root, config.sourceDir, "sourceDir");
168
166
  const dsRoot = projectPath(root, config.dsDir, "dsDir");
169
167
  for (const field of ["publicEntry", "reviewEntry", "stylesEntry", "tokenDir"]) projectPath(dsRoot, config[field], field);
170
168
  if (!isInside(path.join(dsRoot, "review"), path.resolve(dsRoot, config.reviewEntry)) || path.resolve(dsRoot, config.reviewEntry) === path.join(dsRoot, "review") || !/\.[cm]?[jt]sx?$/.test(config.reviewEntry)) throw new Error("reviewEntry must name a script entry inside the ADS review/ development layer.");
171
- for (const file of config.inlineStyleFiles) projectPath(root, file, "inlineStyleFiles");
172
- if (!Array.isArray(config.boundaries.componentVariables) || config.boundaries.componentVariables.some((name) => typeof name !== "string" || !/^--ds-[\w-]+$/.test(name) || isStateVariable(name))) throw new Error("boundaries.componentVariables must name non-state --ds-* customization variables.");
173
- if (!Array.isArray(config.boundaries.styleWrites)) throw new Error("boundaries.styleWrites must be an array.");
174
- const boundaryFiles = new Set();
175
- for (const boundary of config.boundaries.styleWrites) {
176
- if (!boundary || typeof boundary !== "object" || Array.isArray(boundary) || Object.keys(boundary).some((key) => !["file", "properties"].includes(key))) throw new Error("Each styleWrites boundary requires file and properties.");
177
- const file = projectPath(root, boundary.file, "boundaries.styleWrites.file");
178
- if (boundaryFiles.has(file)) throw new Error("Duplicate styleWrites file boundary.");
179
- boundaryFiles.add(file);
180
- if (!Array.isArray(boundary.properties) || !boundary.properties.length || boundary.properties.some((name) => typeof name !== "string" || !/^(?:--[\w-]+|[a-z][a-z0-9-]*)$/.test(name) || name === "css-text" || isStateVariable(name) || isSharedToken(name) || name.startsWith("--") && !/^(?:--ds-|--ux-|--showcase-)/.test(name))) throw new Error("styleWrites.properties must name explicit CSS properties; bulk cssText, shared tokens, foreign prefixes, and primitive-state writes cannot be allowed.");
181
- }
182
169
  for (const field of ["publicDirs", "generatedPaths", "generatedFiles"]) {
183
170
  if (!Array.isArray(config.assets[field])) throw new Error(`assets.${field} must be an array.`);
184
171
  for (const entry of config.assets[field]) {
@@ -236,6 +223,8 @@ export function loadConfig(directory = process.cwd()) {
236
223
  if(!config.mcp.resultRetention || typeof config.mcp.resultRetention!=="object" || Array.isArray(config.mcp.resultRetention) || Object.keys(config.mcp.resultRetention).some(key=>!["maxRuns","maxAgeDays","maxBytesMb"].includes(key)) || !Number.isInteger(retention.maxRuns) || retention.maxRuns<1 || retention.maxRuns>1000 || !Number.isInteger(retention.maxAgeDays) || retention.maxAgeDays<1 || retention.maxAgeDays>365 || !Number.isInteger(retention.maxBytesMb) || retention.maxBytesMb<8 || retention.maxBytesMb>16384)throw new Error("mcp.resultRetention requires maxRuns (1–1000), maxAgeDays (1–365), maxBytesMb (8–16384).");
237
224
  config.mcp.resultRetention=retention;
238
225
  if (!Number.isInteger(config.mcp.mutationCheckTimeoutMs) || config.mcp.mutationCheckTimeoutMs < 100 || config.mcp.mutationCheckTimeoutMs > 300000) throw new Error("mcp.mutationCheckTimeoutMs must be an integer from 100 to 300000. This budget applies to each registered project script, separately from behavior profiles.");
226
+ if (!Number.isInteger(config.mcp.auditPages) || config.mcp.auditPages < 1 || config.mcp.auditPages > 16) throw new Error("mcp.auditPages must be an integer from 1 to 16: how many pages the browser audit renders at once.");
227
+ if (!Number.isInteger(config.mcp.previewBuildTimeoutMs) || config.mcp.previewBuildTimeoutMs < 1000 || config.mcp.previewBuildTimeoutMs > 3600000) throw new Error("mcp.previewBuildTimeoutMs must be an integer from 1000 to 3600000. It is how long a preview waits for its build, including the first build after the MCP server starts.");
239
228
  if (config.mcp.previewManifest !== null) {
240
229
  const manifest = projectPath(root, config.mcp.previewManifest, "mcp.previewManifest");
241
230
  if (!isInside(path.join(root, ".ds"), manifest) || path.extname(manifest) !== ".json") throw new Error("mcp.previewManifest must name a generated JSON manifest inside .ds/.");
@@ -266,19 +255,11 @@ export function isTestFile(file) {
266
255
  }
267
256
 
268
257
  export function isScenarioFile(file) {
269
- return /(?:^|[\\/])Scenario\.[cm]?[jt]sx?$/.test(file) || /\.scenario\.[cm]?[jt]sx?$/.test(file);
270
- }
271
-
272
- export function isFixtureFile(file) {
273
- return /(?:^|[\\/])fixtures?\.(?:[cm]?[jt]sx?|json)$/.test(file) || /\.fixtures?\.(?:[cm]?[jt]sx?|json)$/.test(file);
274
- }
275
-
276
- /** File role, rather than folder location, keeps colocated preview code private. */
277
- export function isBehaviorFile(file) {
278
- return /(?:^|[\\/])behavior\.json$|\.behavior\.json$/.test(file);
258
+ return /\.ads\.scenario\.[cm]?[jt]sx?$/.test(file);
279
259
  }
280
260
 
281
- /** A visible development boundary, independent of whether its role is supported. */
261
+ /** A visible development boundary, independent of whether its role is supported.
262
+ * File role, rather than folder location, keeps colocated development code private. */
282
263
  export function adsFileRole(file) {
283
264
  const match = path.basename(file).match(/\.ads\.(.+)\.[^.]+$/);
284
265
  return match ? match[1] : null;
@@ -288,9 +269,9 @@ export function isContractFile(file) {
288
269
  return /\.ads\.contract\.[cm]?ts$/.test(file);
289
270
  }
290
271
 
291
- /** Filenames may change without changing the identity used by clients/checks. */
272
+ /** The ADS-relative path without `.ads.scenario.*`; a canonical `<Dir>/<Dir>.ads.scenario.*` identifies the directory. */
292
273
  export function scenarioIdentity(file, dsRoot) {
293
- let id = path.relative(dsRoot, file).replaceAll("\\", "/").replace(/\.ads(?=\.)/, "").replace(/(?:\/Scenario|\.scenario)\.[^.]+$/, "");
274
+ let id = path.relative(dsRoot, file).replaceAll("\\", "/").replace(/\.ads\.scenario\.[^.]+$/, "");
294
275
  if (adsFileRole(file) === "scenario" && path.posix.basename(id) === path.posix.basename(path.posix.dirname(id))) id = path.posix.dirname(id);
295
276
  return id;
296
277
  }
@@ -299,15 +280,13 @@ export function isDevelopmentFile(file, { dsRoot }) {
299
280
  if (isDraftFile(file)) return true;
300
281
  if (!isInside(dsRoot, file)) return isTestFile(file) || adsFileRole(file) !== null;
301
282
  const relative = path.relative(dsRoot, file).replaceAll("\\", "/");
302
- return adsFileRole(file) !== null || isTestFile(file) || isScenarioFile(file) || isFixtureFile(file) || isBehaviorFile(file)
303
- || /^(?:showcase|composition|review|brand)\//.test(relative)
304
- || /(?:^|\/)(?:scenario|fixtures)(?:\/|$)/.test(relative)
305
- || /\.scenario(?:-adapter)?\.[cm]?[jt]sx?$/.test(relative);
283
+ // An exports file belongs to its owner's layer: production for the public barrel, development under review/.
284
+ return adsFileRole(file) !== null && adsFileRole(file) !== "exports" || isTestFile(file) || /^(?:showcase|composition|review|brand)\//.test(relative);
306
285
  }
307
286
 
308
287
  /** Review implementations may own demo presentation; scenarios/fixtures may not. */
309
288
  export function isReviewFile(file, { dsRoot }) {
310
- return !isDraftFile(file) && isInside(path.join(dsRoot, "review"), file) && adsFileRole(file) === null && !isTestFile(file) && !isScenarioFile(file) && !isFixtureFile(file) && !isBehaviorFile(file);
289
+ return !isDraftFile(file) && isInside(path.join(dsRoot, "review"), file) && adsFileRole(file) === null && !isTestFile(file);
311
290
  }
312
291
 
313
292
  const ignored = new Set(["node_modules", "dist", "dist-showcase", "dist-kit", ".git", ".vite", ".ds", "coverage"]);
@@ -319,7 +298,7 @@ export function sourceFiles(root) {
319
298
  if (ignored.has(entry.name) || entry.isSymbolicLink() || isDraftFile(path.join(root, entry.name))) continue;
320
299
  const file = path.join(root, entry.name);
321
300
  if (entry.isDirectory()) { if (!hasProjectConfig(file)) files.push(...sourceFiles(file)); }
322
- else if (entry.isFile() && (/\.(css|html|[cm]?[jt]sx?)$/.test(entry.name) || isBehaviorFile(entry.name))) files.push(file);
301
+ else if (entry.isFile() && /\.(css|html|[cm]?[jt]sx?)$/.test(entry.name)) files.push(file);
323
302
  }
324
303
  return files.sort();
325
304
  }
@@ -3,6 +3,15 @@ export type Implementation = ((...args: never[]) => unknown) | (abstract new (..
3
3
  export interface BehaviorCheck { file: string; case: string; scenario?: string; profile: string; }
4
4
  export interface UnitContract {
5
5
  schemaVersion: 1;
6
+ /** The owner's own style permissions, by file path relative to this contract. */
7
+ styles?: {
8
+ /** CSS properties or owned --ds-/--ux-/--showcase- variables a file writes at runtime. */
9
+ writes?: Readonly<Record<string, readonly string[]>>;
10
+ /** Files that may use inline JSX/factory styles. */
11
+ inline?: readonly string[];
12
+ };
13
+ /** A component's --ds-* variables that patterns, the showcase and the application may set. */
14
+ customization?: readonly string[];
6
15
  paintInputs?: readonly { api: Implementation; property: string; kind: "paint-reference"; bindings?: readonly string[] }[];
7
16
  bindings?: Readonly<Record<string, {
8
17
  input: { api: Implementation; property: string };
@@ -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.
@@ -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,27 @@ 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";
13
+ /** The names fonts.preload.generated.ts exports; the generated public barrel re-exports them. */
14
+ export const fontPreloadExports = ["fontPreloadHeader", "fontPreloadTags", "fontPreloads", "preloadFonts"];
12
15
  const unquote = value => value.trim().replace(/^["']|["']$/g, "");
13
16
  const formats = { woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf" };
14
17
 
15
- function fontFaces(text) {
18
+ export function fontFaces(text) {
16
19
  const faces = [];
17
20
  postcss.parse(text).walkAtRules(/^font-face$/i, rule => {
18
21
  const value = name => rule.nodes.find(node => node.type === "decl" && node.prop.toLowerCase() === name)?.value;
19
22
  const url = /url\(\s*["']?([^"')]+)["']?\s*\)/i.exec(value("src") ?? "")?.[1];
20
23
  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") });
24
+ const auto = !value("font-weight") || /^auto$/i.test(value("font-weight").trim());
25
+ const [low, high = low] = (auto ? "400" : value("font-weight")).replace(/\bnormal\b/, "400").replace(/\bbold\b/, "700").trim().split(/\s+/).map(Number);
26
+ faces.push({ family: unquote(value("font-family") ?? ""), url, auto, low, high, slant: (value("font-style") ?? "normal").trim().toLowerCase(), range: value("unicode-range") });
23
27
  });
24
28
  return faces;
25
29
  }
@@ -27,6 +31,9 @@ function fontFaces(text) {
27
31
  /** Whether a unicode-range covers Latin capital A, the subset first text needs. */
28
32
  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
33
 
34
+ /** The face a named family and weight loads for first text: upright, covering Latin and that weight. */
35
+ 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));
36
+
30
37
  /** The font and weight of the body and of headings, as base.css sets them. */
31
38
  function firstTextFonts(text, values) {
32
39
  const read = pattern => {
@@ -47,11 +54,14 @@ function firstTextFonts(text, values) {
47
54
  /** The generated module for a project's tokens, or null when no first-text font is a project file. */
48
55
  export function fontPreloadText({ dsRoot, config }, values) {
49
56
  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;
57
+ const named = config.assets.preloadFonts;
58
+ if (!existsSync(fontsFile) || !named && !existsSync(baseFile)) return null;
51
59
  let faces, uses;
52
- try { faces = fontFaces(readFileSync(fontsFile, "utf8")); uses = firstTextFonts(readFileSync(baseFile, "utf8"), values); }
60
+ try { faces = fontFaces(readFileSync(fontsFile, "utf8")); uses = named ? [] : firstTextFonts(readFileSync(baseFile, "utf8"), values); }
53
61
  catch { return null; /* The core CSS syntax diagnostic owns malformed sheets. */ }
54
62
  const urls = new Set();
63
+ // Named in the config: exactly these, and font-preload-config reports one fonts.css does not have.
64
+ for (const entry of named ?? []) { const face = preloadFace(faces, entry); if (face) urls.add(face.url); }
55
65
  for (const { family, weight } of uses) {
56
66
  const name = (family ?? "").split(",").map(unquote).find(item => faces.some(face => face.family === item));
57
67
  if (!name) continue;
@@ -63,15 +73,25 @@ export function fontPreloadText({ dsRoot, config }, values) {
63
73
  const list = [...urls], local = url => !/^(?:[a-z]+:)?\/\//i.test(url) && !url.startsWith("/");
64
74
  const type = url => formats[/\.(\w+)(?:[?#].*)?$/.exec(url)?.[1]?.toLowerCase()] ?? "font/woff2";
65
75
  return [
66
- "/* Generated by ADS from fonts.css and base.css: the fonts the first text uses. `ads assets` and the",
76
+ "/* Generated by ADS from fonts.css and base.css or assets.preloadFonts: the fonts the first text uses. `ads assets` and the",
67
77
  " 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`)};`] : []),
78
+ " the first render, or put fontPreloadTags() or fontPreloadHeader() in the page from a build step. */",
79
+ ...list.flatMap((url, index) => local(url) ? [`import font${index} from ${JSON.stringify(url.startsWith(".") ? url : `./${url}`)};`] : []),
70
80
  "",
71
81
  "export const fontPreloads: readonly { readonly href: string; readonly type: string }[] = [",
72
82
  ...list.map((url, index) => ` { href: ${local(url) ? `font${index}` : JSON.stringify(url)}, type: ${JSON.stringify(type(url))} },`),
73
83
  "];",
74
84
  "",
85
+ "/** The same list for a build step or prerender: <link> tags for the page's HTML. */",
86
+ "export function fontPreloadTags(): string {",
87
+ ' return fontPreloads.map(({ href, type }) => `<link rel="preload" href="${href}" as="font" type="${type}" crossorigin="anonymous">`).join("\\n");',
88
+ "}",
89
+ "",
90
+ "/** The same list as a Link header value. */",
91
+ "export function fontPreloadHeader(): string {",
92
+ ' return fontPreloads.map(({ href, type }) => `<${href}>; rel=preload; as=font; type="${type}"; crossorigin=anonymous`).join(", ");',
93
+ "}",
94
+ "",
75
95
  "/** Adds one preload link per font. The crossorigin attribute matches how browsers fetch fonts. */",
76
96
  "export function preloadFonts(): void {",
77
97
  " for (const { href, type } of fontPreloads) {",
@@ -0,0 +1,131 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import ts from "typescript";
4
+ import { isInside, sourceFiles } from "./config.mjs";
5
+ import { foundationFiles } from "./token-policy.mjs";
6
+ import { fontPreloadExports, generatedFontsFile } from "./fonts-generated.mjs";
7
+
8
+ // Shared entries are generated, so every authored file has exactly one owner and drafts of
9
+ // different owners never meet in a shared file:
10
+ // - the public barrel (publicEntry, normally index.ts) and the development review entry
11
+ // (reviewEntry): each owner declares its own public names in <Owner>.ads.exports.ts beside its
12
+ // source, and ADS copies those named re-exports into the entry with rebased paths. The public
13
+ // barrel also publishes ADS's generated font preloads (tokens/fonts.preload.generated.ts) when
14
+ // `ads assets` has written them, so the app calls preloadFonts() through the public entry;
15
+ // - the foundation styles entry (stylesEntry): one @import per canonical token sheet present,
16
+ // in the fixed foundation order.
17
+ // The showcase and MCP server rewrite them whenever an exports file, token sheet or the config
18
+ // changes, `ads assets` writes them on demand, draft previews and acceptance candidates
19
+ // regenerate them, and `ads check` only verifies them.
20
+
21
+ export const isExportsFile = file => /\.ads\.exports\.[cm]?ts$/.test(file);
22
+ const slash = value => value.replaceAll("\\", "/");
23
+ export const barrelHeader = "// Generated by ADS from each owner's .ads.exports.ts; do not edit. Declare an owner's public names in its exports file.\n";
24
+ const stylesHeader = "/* Generated by ADS from the token sheets present in the token folder, in foundation order; do not edit. */\n";
25
+
26
+ /** Both generated entries with the exports files each one collects, in path order. */
27
+ export function barrelEntries({ dsRoot, config }) {
28
+ const review = path.join(dsRoot, "review"), files = sourceFiles(dsRoot).filter(isExportsFile);
29
+ return [
30
+ // Importing the public barrel loads the foundation styles first.
31
+ { kind: "public", file: path.join(dsRoot, config.publicEntry), styles: path.join(dsRoot, config.stylesEntry), fonts: path.join(dsRoot, config.tokenDir, generatedFontsFile), sources: files.filter(file => !isInside(review, file)) },
32
+ { kind: "review", file: path.join(dsRoot, config.reviewEntry), sources: files.filter(file => isInside(review, file)) },
33
+ ];
34
+ }
35
+
36
+ const specifier = (from, file, keepExtension = false) => {
37
+ const relative = slash(path.relative(path.dirname(from), file)), bare = keepExtension ? relative : relative.replace(/\.[cm]?ts$/, "");
38
+ return bare.startsWith(".") ? bare : `./${bare}`;
39
+ };
40
+
41
+ /**
42
+ * The exact generated text of one entry: each exports file's re-exports, in path order, with
43
+ * their paths rebased onto the entry. The barrel names every public export directly from its
44
+ * source, so a product build never reaches an exports file. Statements an exports file may not
45
+ * hold are left out; `ads check` reports them on that file. An entry without names stays a module.
46
+ */
47
+ export function barrelText(entry) {
48
+ const lines = [];
49
+ for (const source of entry.sources) {
50
+ const ast = ts.createSourceFile(source, readFileSync(source, "utf8"), ts.ScriptTarget.Latest, true);
51
+ for (const statement of ast.statements) {
52
+ if (!ts.isExportDeclaration(statement) || !statement.exportClause || !ts.isNamedExports(statement.exportClause) || !statement.moduleSpecifier || !ts.isStringLiteralLike(statement.moduleSpecifier) || !statement.moduleSpecifier.text.startsWith(".")) continue;
53
+ const names = statement.exportClause.elements.map(element => `${element.isTypeOnly ? "type " : ""}${element.propertyName ? `${element.propertyName.text} as ` : ""}${element.name.text}`);
54
+ const target = specifier(entry.file, path.resolve(path.dirname(source), statement.moduleSpecifier.text), true);
55
+ lines.push(`export ${statement.isTypeOnly ? "type " : ""}{ ${names.join(", ")} } from "${target}";\n`);
56
+ }
57
+ }
58
+ if (entry.fonts && existsSync(entry.fonts)) lines.push(`export { ${fontPreloadExports.join(", ")} } from "${specifier(entry.file, entry.fonts)}";\n`);
59
+ const styles = entry.styles ? `import "${specifier(entry.file, entry.styles, true)}";\n` : "";
60
+ return barrelHeader + styles + (lines.length ? lines.join("") : "export {};\n");
61
+ }
62
+
63
+ /** The foundation styles entry: an @import per canonical token sheet that exists. */
64
+ export function stylesEntryFile({ dsRoot, config }) {
65
+ const file = path.join(dsRoot, config.stylesEntry);
66
+ const sheets = foundationFiles.map(name => path.join(dsRoot, config.tokenDir, name)).filter(sheet => existsSync(sheet));
67
+ return { file, text: stylesHeader + sheets.map(sheet => `@import "${specifier(file, sheet, true)}";\n`).join("") };
68
+ }
69
+
70
+ /** Every generated entry as it should be, for writing or for overlaying a candidate project. */
71
+ export function generatedEntries(options) {
72
+ return [stylesEntryFile(options), ...barrelEntries(options).map(entry => ({ file: entry.file, text: barrelText(entry) }))];
73
+ }
74
+
75
+ /** Writes stale generated entries atomically and reports which changed. */
76
+ export function writeGeneratedEntries(options) {
77
+ const files = [];
78
+ for (const { file, text } of generatedEntries(options)) {
79
+ const current = existsSync(file) ? readFileSync(file, "utf8") : null;
80
+ if (current !== text) {
81
+ mkdirSync(path.dirname(file), { recursive: true });
82
+ const staging = `${file}.ads-generated.tmp`;
83
+ try { writeFileSync(staging, text); renameSync(staging, file); }
84
+ finally { rmSync(staging, { force: true }); }
85
+ }
86
+ files.push({ file, text, changed: current !== text });
87
+ }
88
+ return { files };
89
+ }
90
+
91
+ /** The names one exports file declares, or the reasons it is not a plain exports file. */
92
+ export function exportsDeclarations(file, text = readFileSync(file, "utf8")) {
93
+ const ast = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true), names = [], targets = [], problems = [];
94
+ for (const statement of ast.statements) {
95
+ const line = ast.getLineAndCharacterOfPosition(statement.getStart(ast)).line + 1;
96
+ if (!ts.isExportDeclaration(statement) || !statement.moduleSpecifier || !ts.isStringLiteralLike(statement.moduleSpecifier)) { problems.push({ line, message: "An exports file holds only `export { … } from \"./module\"` and `export type { … } from \"./module\"` re-exports of its owner's source." }); continue; }
97
+ if (!statement.exportClause || !ts.isNamedExports(statement.exportClause)) { problems.push({ line, message: "Name each public export: `export *` hides an owner's API from review." }); continue; }
98
+ if (!statement.moduleSpecifier.text.startsWith(".")) { problems.push({ line, message: "Re-export the owner's own modules by relative path." }); continue; }
99
+ targets.push({ line, specifier: statement.moduleSpecifier.text });
100
+ for (const element of statement.exportClause.elements) names.push({ name: element.name.text, line });
101
+ }
102
+ return { names, targets, problems };
103
+ }
104
+
105
+ /** Freshness of every generated entry; plain exports files, owner-local targets and unique public names. */
106
+ export function generatedEntryDiagnostics(options, inventory) {
107
+ const { root } = options, diagnostics = [], relative = file => slash(path.relative(root, file));
108
+ for (const { file, text } of generatedEntries(options)) {
109
+ const current = existsSync(file) ? readFileSync(file, "utf8") : null;
110
+ if (current !== text) diagnostics.push({ rule: "generated-entry", file: relative(file), line: 1, column: 1, message: `${path.basename(file)} is generated by ADS (${file.endsWith(".css") ? "from the token sheets" : "from .ads.exports.ts files"}) and is ${current === null ? "missing" : "stale or edited by hand"}. Run ads assets, or let the showcase/MCP server rewrite it.` });
111
+ }
112
+ for (const entry of barrelEntries(options)) {
113
+ const seen = new Map();
114
+ for (const source of entry.sources) {
115
+ const owner = inventory.owner(inventory.relative(relative(source))), { names, targets, problems } = exportsDeclarations(source);
116
+ for (const problem of problems) diagnostics.push({ rule: "exports-file", file: relative(source), line: problem.line, column: 1, message: problem.message });
117
+ for (const target of targets) {
118
+ const base = path.resolve(path.dirname(source), target.specifier);
119
+ const resolved = ["", ".ts", ".tsx", ".mts", ".js", ".jsx", "/index.ts", "/index.tsx"].map(extension => base + extension).find(file => existsSync(file) && statSync(file).isFile() && !isExportsFile(file));
120
+ const targetOwner = resolved && inventory.owner(inventory.relative(relative(resolved)));
121
+ if (!resolved) diagnostics.push({ rule: "exports-file", file: relative(source), line: target.line, column: 1, message: `Cannot resolve ${target.specifier}.` });
122
+ else if (targetOwner !== owner) diagnostics.push({ rule: "exports-file", file: relative(source), line: target.line, column: 1, message: `${owner}'s exports file can re-export only its own source; ${target.specifier} belongs to ${targetOwner ?? "no owner"}.` });
123
+ }
124
+ for (const { name, line } of names) {
125
+ if (seen.has(name)) diagnostics.push({ rule: "barrel-duplicate", file: relative(source), line, column: 1, message: `${name} is already exported by ${seen.get(name)}; public names must be unique across owners.` });
126
+ else seen.set(name, relative(source));
127
+ }
128
+ }
129
+ }
130
+ return diagnostics;
131
+ }
package/dist/icons.mjs CHANGED
@@ -53,7 +53,7 @@ function textSize({ dsRoot, config }, sizes) {
53
53
  const output = path.join(dsRoot, config.assets.glyphs.output), folder = path.dirname(output);
54
54
  for (const name of files(folder)) {
55
55
  const file = path.join(folder, name);
56
- if (file === output || !/\.[cm]?[jt]sx?$/.test(name) || isTestFile(name) || /\.(?:scenario|fixture)\.[jt]sx?$/.test(name)) continue;
56
+ if (file === output || !/\.[cm]?[jt]sx?$/.test(name) || isTestFile(name) || /\.ads\.(?:scenario|fixture)\.[jt]sx?$/.test(name)) continue;
57
57
  for (const match of readFileSync(file, "utf8").matchAll(/var\(\s*(--icon-[\w-]+)/g)) {
58
58
  const size = sizes.find(item => item.token === match[1]);
59
59
  if (size) return size;