@reqvire-org/ads 0.3.46 → 0.3.48

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 (122) hide show
  1. package/README.md +21 -11
  2. package/dist/a11y.mjs +4 -2
  3. package/dist/assets.mjs +20 -15
  4. package/dist/atomic-composition.mjs +3 -2
  5. package/dist/brand-assets.mjs +48 -11
  6. package/dist/brands.mjs +82 -0
  7. package/dist/browser-audit/worker.mjs +51 -0
  8. package/dist/browser-audit.mjs +147 -0
  9. package/dist/capture/worker.mjs +1 -0
  10. package/dist/capture-store.mjs +2 -0
  11. package/dist/capture.mjs +7 -4
  12. package/dist/check.mjs +38 -8
  13. package/dist/cli.mjs +45 -10
  14. package/dist/color-values.mjs +325 -0
  15. package/dist/config.mjs +16 -2
  16. package/dist/control-padding.mjs +93 -0
  17. package/dist/design-values.mjs +3 -2
  18. package/dist/finding-rules.mjs +61 -0
  19. package/dist/foundation.mjs +17 -4
  20. package/dist/icons.mjs +107 -0
  21. package/dist/init.mjs +3 -0
  22. package/dist/mcp/apps.mjs +9 -6
  23. package/dist/mcp/context.mjs +1 -1
  24. package/dist/mcp/drafts.mjs +3 -0
  25. package/dist/mcp/mutations.mjs +40 -1
  26. package/dist/mcp/preview-widget.bundle.js +36 -36
  27. package/dist/mcp/project-widget.bundle.js +12 -12
  28. package/dist/mcp/server.mjs +23 -11
  29. package/dist/mcp/widget.bundle.js +17 -17
  30. package/dist/palette-generated.mjs +180 -0
  31. package/dist/preview-resources.mjs +12 -3
  32. package/dist/render-color-probe.mjs +148 -0
  33. package/dist/runtime-contracts.mjs +14 -4
  34. package/dist/scenarios.mjs +1 -1
  35. package/dist/showcase/client.bundle.js +28 -28
  36. package/dist/showcase/icons.js +146 -0
  37. package/dist/showcase/index.html +2 -1
  38. package/dist/showcase/style.css +19 -2
  39. package/dist/skills/README.md +2 -1
  40. package/dist/skills/ads-break-ui/SKILL.md +6 -5
  41. package/dist/skills/ads-break-ui/references/atomic-styles.md +12 -12
  42. package/dist/skills/ads-break-ui/references/contracts.md +13 -10
  43. package/dist/skills/ads-break-ui/references/design-data.md +137 -29
  44. package/dist/skills/ads-break-ui/references/drafts.md +3 -1
  45. package/dist/skills/ads-break-ui/references/guarded-editing.md +3 -2
  46. package/dist/skills/ads-break-ui/references/validation.md +13 -4
  47. package/dist/skills/ads-designer/SKILL.md +23 -16
  48. package/dist/skills/ads-designer/references/accessibility.md +41 -5
  49. package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
  50. package/dist/skills/ads-designer/references/branding.md +37 -10
  51. package/dist/skills/ads-designer/references/cli.md +8 -2
  52. package/dist/skills/ads-designer/references/contracts.md +13 -10
  53. package/dist/skills/ads-designer/references/design-data.md +137 -29
  54. package/dist/skills/ads-designer/references/drafts.md +3 -1
  55. package/dist/skills/ads-designer/references/guarded-editing.md +3 -2
  56. package/dist/skills/ads-designer/references/validation.md +13 -4
  57. package/dist/skills/ads-import/SKILL.md +9 -8
  58. package/dist/skills/ads-import/references/atomic-styles.md +12 -12
  59. package/dist/skills/ads-import/references/cli.md +8 -2
  60. package/dist/skills/ads-import/references/contracts.md +13 -10
  61. package/dist/skills/ads-import/references/design-data.md +137 -29
  62. package/dist/skills/ads-import/references/drafts.md +3 -1
  63. package/dist/skills/ads-import/references/guarded-editing.md +3 -2
  64. package/dist/skills/ads-import/references/tokens.md +7 -3
  65. package/dist/skills/ads-import/references/validation.md +13 -4
  66. package/dist/skills/ads-motion/SKILL.md +6 -5
  67. package/dist/skills/ads-motion/references/atomic-styles.md +12 -12
  68. package/dist/skills/ads-motion/references/contracts.md +13 -10
  69. package/dist/skills/ads-motion/references/design-data.md +137 -29
  70. package/dist/skills/ads-motion/references/drafts.md +3 -1
  71. package/dist/skills/ads-motion/references/guarded-editing.md +3 -2
  72. package/dist/skills/ads-motion/references/validation.md +13 -4
  73. package/dist/skills/ads-port/SKILL.md +6 -5
  74. package/dist/skills/ads-port/references/atomic-styles.md +12 -12
  75. package/dist/skills/ads-port/references/cli.md +8 -2
  76. package/dist/skills/ads-port/references/contracts.md +13 -10
  77. package/dist/skills/ads-port/references/design-data.md +137 -29
  78. package/dist/skills/ads-port/references/drafts.md +3 -1
  79. package/dist/skills/ads-port/references/guarded-editing.md +3 -2
  80. package/dist/skills/ads-port/references/validation.md +13 -4
  81. package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +11 -2
  82. package/dist/starters/react/ADS.md +43 -10
  83. package/dist/starters/react/README.md +14 -9
  84. package/dist/starters/react/design-system/assets/brand/README.md +8 -3
  85. package/dist/starters/react/design-system/assets/glyphs/README.md +4 -1
  86. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -1
  87. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +3 -2
  88. package/dist/starters/react/design-system/components/Content/Icon/README.md +2 -1
  89. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +3 -9
  90. package/dist/starters/react/design-system/components/Content/Logo/README.md +4 -2
  91. package/dist/starters/react/design-system/controllers/Palette/Palette.ts +164 -0
  92. package/dist/starters/react/design-system/index.ts +3 -0
  93. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
  94. package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +11 -2
  95. package/dist/starters/react/design-system/styles.css +1 -0
  96. package/dist/starters/react/design-system/tokens/base.css +8 -5
  97. package/dist/starters/react/design-system/tokens/colors.css +167 -175
  98. package/dist/starters/react/design-system/tokens/elevation.css +14 -21
  99. package/dist/starters/react/design-system/tokens/themes.generated.css +142 -0
  100. package/dist/starters/react/design-system/tokens/themes.generated.ts +402 -0
  101. package/dist/style-boundaries.mjs +2 -1
  102. package/dist/themes-generated.mjs +150 -0
  103. package/dist/themes-watch.mjs +42 -0
  104. package/dist/themes.mjs +214 -63
  105. package/dist/token-export.mjs +22 -11
  106. package/dist/token-policy.mjs +2 -1
  107. package/dist/token-quality.mjs +28 -25
  108. package/dist/tokens.mjs +27 -32
  109. package/dist/validation.mjs +17 -1
  110. package/dist/verification/browser.mjs +14 -3
  111. package/dist/verification.mjs +25 -4
  112. package/docs/ADS.md +41 -27
  113. package/docs/ARCHITECTURE.md +49 -22
  114. package/docs/CACHING.md +2 -3
  115. package/docs/CHANGELOG.md +117 -13
  116. package/docs/CONTRACTS.md +13 -10
  117. package/docs/GUIDE.md +94 -22
  118. package/docs/MCP.md +50 -30
  119. package/docs/benchmarks/bun-previews.md +5 -5
  120. package/docs/benchmarks/{gidi-preview-memory.md → preview-memory.md} +14 -12
  121. package/docs/benchmarks/turbo-poc.md +24 -6
  122. package/package.json +2 -1
@@ -0,0 +1,180 @@
1
+ import valueParser from "postcss-value-parser";
2
+ import { contextValues } from "./themes.mjs";
3
+ import { isSharedToken, tokenContract } from "./token-policy.mjs";
4
+ import { canonicalCss, parseCssColor, singleFunction, srgb8 } from "./color-values.mjs";
5
+
6
+ // themes.generated.ts: the renderer palette ADS writes beside themes.generated.css, from the
7
+ // same token sheets and ds.config.json themes and brands, with the same triggers. For every
8
+ // shared token whose value is a color, in every context (each theme of the default brand,
9
+ // <brand>/<theme> for every other brand), it holds the canonical CSS string and sRGB channels,
10
+ // resolved the way the generated sheet resolves them on an element in that context: halves,
11
+ // aliases and var() fallbacks followed, light-dark() by the theme's scheme, color-mix() and
12
+ // every absolute color syntax evaluated, then clipped to sRGB as a 2D canvas draws it.
13
+ // Unconditional values only: @media/@supports variants are not part of a context.
14
+ // A token that cannot be resolved statically in some context (currentColor, relative color
15
+ // syntax, an unknown function) is left out of the palette and listed in `unresolved`.
16
+
17
+ export const generatedPaletteFile = "themes.generated.ts";
18
+ const header = "/* Generated by ADS from the token sheets' per-theme halves and ds.config.json themes and brands.\n The showcase and MCP server rewrite it when they change; do not edit it. */\n";
19
+ const compare = (a, b) => a.localeCompare(b, "en", { numeric: true });
20
+
21
+ class Invalid extends Error {}
22
+ // Functions whose value is a length, number, time, easing, image, filter, transform or shape.
23
+ const nonColorFunctions = /^(?:calc|min|max|clamp|round|mod|rem|abs|sign|sin|cos|tan|asin|acos|atan|atan2|pow|sqrt|hypot|log|exp|fit-content|minmax|repeat|cubic-bezier|steps|linear|url|attr|env|counter|counters|format|local|image|image-set|cross-fade|element|paint|(?:repeating-)?(?:linear|radial|conic)-gradient|(?:translate|scale|rotate|skew)(?:[xyz3d]|3d)?|matrix(?:3d)?|perspective|blur|brightness|contrast|drop-shadow|grayscale|hue-rotate|invert|opacity|saturate|sepia|inset|circle|ellipse|polygon|path|rect|xywh|anchor|anchor-size|var)$/i;
24
+
25
+ /** A value with every var() substituted in one context; throws Invalid for a cycle or an
26
+ * undefined reference without a fallback (the browser's invalid-at-computed-value-time). */
27
+ function substitute(values, text, seen) {
28
+ if (!text.includes("var(")) return text;
29
+ const parsed = valueParser(text);
30
+ const walk = nodes => {
31
+ for (const node of nodes) {
32
+ if (node.type !== "function") continue;
33
+ if (node.value.toLowerCase() !== "var") { walk(node.nodes); continue; }
34
+ const comma = node.nodes.findIndex(child => child.type === "div" && child.value === ",");
35
+ const name = node.nodes.find(child => child.type === "word")?.value;
36
+ const fallback = comma < 0 ? null : valueParser.stringify(node.nodes.slice(comma + 1)).trim();
37
+ let result = null;
38
+ if (name && values.has(name) && !seen.has(name)) {
39
+ try { result = substitute(values, values.get(name).value.trim(), new Set([...seen, name])); } catch (error) { if (!(error instanceof Invalid)) throw error; }
40
+ if (result === "") result = null;
41
+ } else if (name && seen.has(name)) throw new Invalid(`${name} refers to itself`);
42
+ if (result === null && fallback !== null) result = substitute(values, fallback, seen);
43
+ if (result === null) throw new Invalid(`${name ?? "var()"} is not defined here`);
44
+ Object.assign(node, { type: "word", value: result, nodes: undefined });
45
+ }
46
+ };
47
+ walk(parsed.nodes);
48
+ return parsed.toString();
49
+ }
50
+
51
+ /** One token in one context: { color: [r, g, b, a] }, { unresolved: reason, value } or null. */
52
+ function resolveToken(values, name, scheme) {
53
+ const own = values.get(name);
54
+ if (!own) return null;
55
+ let text;
56
+ try { text = substitute(values, own.value.trim(), new Set([name])); }
57
+ catch (error) { if (error instanceof Invalid) return { unresolved: error.message, value: own.value.trim(), invalid: true }; throw error; }
58
+ const parsed = parseCssColor(text, { scheme });
59
+ if (parsed?.color) return { color: srgb8(parsed.color) };
60
+ if (parsed?.unresolved) return { unresolved: parsed.unresolved, value: text };
61
+ const fn = singleFunction(text);
62
+ return fn && !nonColorFunctions.test(fn) ? { unresolved: `${fn}() is not resolved statically`, value: text } : { other: true, value: text };
63
+ }
64
+
65
+ /** The palette contexts: each declared theme of the default brand, then <brand>/<theme> for
66
+ * every other brand. */
67
+ export function paletteContexts({ themes, brands = [] }) {
68
+ const contexts = themes.map(theme => ({ key: theme.name, theme, brand: undefined }));
69
+ for (const brand of brands.slice(1)) for (const theme of themes) contexts.push({ key: `${brand.name}/${theme.name}`, theme, brand: brand.name });
70
+ return contexts;
71
+ }
72
+
73
+ /** The theme each OS color scheme selects with followSystemTheme, or null without it. */
74
+ export function systemThemeMap({ themes, followSystemTheme = false }) {
75
+ if (!followSystemTheme) return null;
76
+ return Object.fromEntries(["light", "dark"].map(scheme => [scheme, (themes.find(theme => theme.scheme === scheme) ?? themes[0]).name]));
77
+ }
78
+
79
+ /** The resolved palette: { contexts, tokens, palette: { [context]: { [token]: { css, rgba } } }, unresolved }. */
80
+ export function resolvePalette(tokens, config) {
81
+ const { themes, brands = [] } = config;
82
+ const contexts = paletteContexts({ themes, brands });
83
+ const names = tokens.filter(token => isSharedToken(token.name) && token.definitions.some(definition => !definition.conditional)).map(token => token.name).sort(compare);
84
+ const results = new Map(names.map(name => [name, []]));
85
+ for (const context of contexts) {
86
+ const values = contextValues(tokens, { theme: context.theme.name, brand: context.brand, themes });
87
+ for (const name of names) results.get(name).push(resolveToken(values, name, context.theme.scheme));
88
+ }
89
+ const palette = Object.fromEntries(contexts.map(context => [context.key, {}])), unresolved = [], included = [];
90
+ for (const name of names) {
91
+ const entries = results.get(name), typed = tokenContract.tokens[name]?.type === "color";
92
+ const colorful = entries.some(entry => entry?.color) || entries.some(entry => entry?.unresolved && !entry.invalid) || typed && entries.some(entry => entry?.unresolved);
93
+ if (!colorful) continue;
94
+ if (entries.every(entry => entry?.color)) {
95
+ included.push(name);
96
+ for (const [index, context] of contexts.entries()) palette[context.key][name] = { css: canonicalCss(entries[index].color), rgba: entries[index].color };
97
+ continue;
98
+ }
99
+ for (const [index, context] of contexts.entries()) {
100
+ const entry = entries[index];
101
+ if (entry?.color) continue;
102
+ unresolved.push({ context: context.key, token: name, value: entry?.value ?? "", reason: entry?.unresolved ?? (entry ? "not a color in this context" : "not set in this context") });
103
+ }
104
+ }
105
+ return { contexts, tokens: included, palette, unresolved };
106
+ }
107
+
108
+ const quote = JSON.stringify;
109
+ const union = (items, empty = "never") => items.length ? items.map(item => `\n | ${quote(item)}`).join("") : ` ${empty}`;
110
+
111
+ const identifier = /^[A-Za-z_$][\w$]*$/;
112
+ const member = (object, key) => identifier.test(key) ? `${object}.${key}` : `${object}[${quote(key)}]`;
113
+ /** One switch expression per declared theme over the given value expressions, as a template literal. */
114
+ const switchTemplate = (themes, valueOf) => `\`${themes.map(theme => `var(--ads-if-${theme.name}, \${${valueOf(theme)}})`).join("")}\``;
115
+
116
+ /** The runtime theme helpers: Theme, themeSchemes, themed() and themedByScheme(). Each returns
117
+ * the switch expression the generated sheet uses for token halves, so a value set inline (a
118
+ * style attribute, an inline custom property or a <style> rule) follows the nearest data-theme
119
+ * like any token. */
120
+ function themedTs(themes) {
121
+ return [
122
+ "/** A declared theme. */",
123
+ "export type Theme = (typeof themes)[number];",
124
+ "/** Each declared theme's color scheme. */",
125
+ `export const themeSchemes = { ${themes.map(theme => `${identifier.test(theme.name) ? theme.name : quote(theme.name)}: ${quote(theme.scheme)}`).join(", ")} } as const satisfies { readonly [theme in Theme]: "light" | "dark" };`,
126
+ "",
127
+ "/** A runtime value per declared theme (complete CSS values, such as colors from data) as one",
128
+ " * expression that follows the nearest data-theme, like a token's halves. Use it for inline",
129
+ " * styles and inline custom properties; never light-dark(). */",
130
+ "export function themed(values: { readonly [theme in Theme]: string }): string {",
131
+ ` return ${switchTemplate(themes, theme => member("values", theme.name))};`,
132
+ "}",
133
+ "",
134
+ "/** themed() from a light and a dark value: each declared theme takes the value of its color scheme. */",
135
+ "export function themedByScheme(values: { readonly light: string; readonly dark: string }): string {",
136
+ ` return ${switchTemplate(themes, theme => `values.${theme.scheme}`)};`,
137
+ "}",
138
+ ];
139
+ }
140
+
141
+ /** The generated TypeScript palette module for a token inventory and the declared themes and brands. */
142
+ export function paletteTs(tokens, config) {
143
+ const { themes, brands = [] } = config;
144
+ const { contexts, tokens: names, palette, unresolved } = resolvePalette(tokens, config);
145
+ const system = systemThemeMap(config);
146
+ const out = [header,
147
+ "/** A palette context: a theme of the default brand, or <brand>/<theme> for another brand. */",
148
+ `export type PaletteContext =${union(contexts.map(context => context.key))};`,
149
+ "/** A shared token whose value is a color in every context. */",
150
+ `export type ColorToken =${union(names)};`,
151
+ "/** A resolved color: its canonical CSS string and sRGB channels 0–255 with alpha 0–1. */",
152
+ "export interface PaletteColor { readonly css: string; readonly rgba: readonly [r: number, g: number, b: number, a: number] }",
153
+ "/** Every color token of one context. */",
154
+ "export type Palette = { readonly [token in ColorToken]: PaletteColor };",
155
+ "",
156
+ `export const themes = [${themes.map(theme => quote(theme.name)).join(", ")}] as const;`,
157
+ `export const brands = [${brands.map(brand => quote(brand.name)).join(", ")}] as const;`,
158
+ `export const contexts = [${contexts.map(context => quote(context.key)).join(", ")}] as const satisfies readonly PaletteContext[];`,
159
+ `export const defaultContext: PaletteContext = ${quote(contexts[0].key)};`,
160
+ "/** The theme each OS color scheme selects on a root without data-theme (followSystemTheme), or null. */",
161
+ `export const systemThemes: { readonly light: (typeof themes)[number]; readonly dark: (typeof themes)[number] } | null = ${system ? `{ light: ${quote(system.light)}, dark: ${quote(system.dark)} }` : "null"};`,
162
+ "",
163
+ ...themedTs(themes),
164
+ "",
165
+ "export const palette = {"];
166
+ for (const context of contexts) {
167
+ out.push(` ${quote(context.key)}: {`);
168
+ for (const name of names) {
169
+ const { css, rgba } = palette[context.key][name];
170
+ out.push(` ${quote(name)}: { css: ${quote(css)}, rgba: [${rgba.join(", ")}] },`);
171
+ }
172
+ out.push(" },");
173
+ }
174
+ out.push("} as const satisfies { readonly [context in PaletteContext]: Palette };", "",
175
+ "/** Color tokens ADS cannot resolve statically in some context; they are not in the palette. */",
176
+ "export const unresolved: readonly { readonly context: PaletteContext; readonly token: string; readonly value: string; readonly reason: string }[] = [");
177
+ for (const entry of unresolved) out.push(` { context: ${quote(entry.context)}, token: ${quote(entry.token)}, value: ${quote(entry.value)}, reason: ${quote(entry.reason)} },`);
178
+ out.push("];", "");
179
+ return out.join("\n");
180
+ }
@@ -178,7 +178,9 @@ export function createPreviewResources(output, options, entries, {retain, prune
178
178
  const scenarios = entries.map((entry, index) => {
179
179
  const chunk = bundle.find(item => item.type === "chunk" && item.facadeModuleId === `\0ads-preview-entry:${index}`);
180
180
  if (!chunk) throw new Error(`Missing compiled scenario entry: ${entry.id}`);
181
- return retain?.manifest.scenarios.find(previous=>previous.id===entry.id) ?? { id: entry.id, title: entry.title, kind: entry.kind, ...(entry.samples ? { samples: entry.samples } : {}), ...(entry.paintBindings?.length ? {paintBindings:entry.paintBindings} : {}), ...(entry.paintAudit?{paintAudit:true}:{}), module: uris.get(chunk.fileName) };
181
+ // Retain only the compiled closure. Metadata always follows the current
182
+ // registry: identical source can be rediscovered with different metadata.
183
+ return scenarioRecord(entry, retain?.manifest.scenarios.find(previous=>previous.id===entry.id)?.module ?? uris.get(chunk.fileName));
182
184
  });
183
185
  // Rechunking a growing warm graph must not replace already compiled views.
184
186
  // Retain their exact closures for identical source/compiler modes, then prune
@@ -187,12 +189,19 @@ export function createPreviewResources(output, options, entries, {retain, prune
187
189
  function visit(uri){if(used.has(uri))return;const record=records[uri];if(!record)throw new Error("Missing retained preview dependency: "+uri);used.add(uri);for(const target of [...record.imports,...record.dynamicImports,...record.styles,...record.references])visit(target);}
188
190
  if(retain||prune){for(const scenario of scenarios)visit(scenario.module);
189
191
  for(const uri of Object.keys(records))if(!used.has(uri)){delete records[uri];contents.delete(uri);}}
190
- const graph = { schemaVersion: 1, framework: options.config.framework, themes: options.config.themes, assets: records, scenarios };
192
+ const graph = { schemaVersion: 1, framework: options.config.framework, themes: options.config.themes, ...(options.config.brands?.length ? { brands: options.config.brands } : {}), assets: records, scenarios };
191
193
  const revision = hash(JSON.stringify(graph));
192
194
  validateManifest({ ...graph, revision });
193
195
  return publication(options, entries, { ...graph, revision }, contents);
194
196
  }
195
197
 
198
+ /** The registry metadata a manifest exposes. Cached graphs are valid only for
199
+ * entries projecting to the same records, so unrelated registry fields do not
200
+ * invalidate compiled output. */
201
+ function scenarioRecord(entry, module) {
202
+ return { id: entry.id, title: entry.title, kind: entry.kind, ...(entry.samples ? { samples: entry.samples } : {}), ...(entry.paintBindings?.length ? {paintBindings:entry.paintBindings} : {}), ...(entry.paintAudit?{paintAudit:true}:{}), module };
203
+ }
204
+
196
205
  export function previewArtifactHtml(id, revision) {
197
206
  const descriptor = JSON.stringify({ schemaVersion: 1, manifestUri: PREVIEW_MANIFEST_URI, revision, id });
198
207
  return `<!doctype html><html><head></head><body><script type="application/json" id="ads-preview-resource">${descriptor.replaceAll("<", "\\u003c")}</script></body></html>`;
@@ -208,7 +217,7 @@ export function cachedPreviewPublication(options, entries, revision, target = op
208
217
  try {
209
218
  const cached = cacheOptions(options, revision), manifest = readPreviewManifest(cached, { verify: true });
210
219
  if (!manifest || manifest.revision !== revision || manifest.framework !== options.config.framework
211
- || JSON.stringify(manifest.scenarios.map(entry => entry.id)) !== JSON.stringify(entries.map(entry => entry.id))) return null;
220
+ || JSON.stringify(manifest.scenarios) !== JSON.stringify(entries.map((entry, index) => scenarioRecord(entry, manifest.scenarios[index]?.module)))) return null;
212
221
  const contents = new Map(Object.keys(manifest.assets).map(uri => {
213
222
  const value = readPreviewAsset(cached, uri, manifest);
214
223
  return [uri, "text" in value ? Buffer.from(value.text) : Buffer.from(value.blob, "base64")];
@@ -0,0 +1,148 @@
1
+ import ts from "typescript";
2
+ import { findingSeverity } from "./finding-rules.mjs";
3
+
4
+ // render-color-probe: a computed-style color read (getComputedStyle(...).getPropertyValue(),
5
+ // .color, .fill, …) or a canvas pixel read in a per-item render path. Measured renderers that
6
+ // normalize a color per node or edge insert and read DOM on every hover pass; the generated
7
+ // palette (paletteFor(element)) resolves every token once per context instead. Per-item paths
8
+ // are callbacks passed to array iteration (.map, .forEach, .reduce, …), the bodies of for, for…of
9
+ // and for…in loops, and known per-item renderer hooks: Sigma's nodeReducer/edgeReducer,
10
+ // force-graph's nodeColor/linkColor/nodeCanvasObject/linkCanvasObject, and d3 .attr()/.style()/
11
+ // .each() callbacks. A probe is found directly or through a helper the path calls, followed
12
+ // through the project's own functions. Kept conservative: getComputedStyle for layout or a
13
+ // createElement that builds markup is not a color probe.
14
+
15
+ const message = "Read colors outside per-item render paths: use paletteFor(element) from the generated palette.";
16
+ const iterators = new Set(["map", "forEach", "reduce", "reduceRight", "flatMap", "filter", "some", "every", "find", "findIndex", "findLast", "findLastIndex"]);
17
+ const rendererHooks = new Set(["nodeReducer", "edgeReducer", "nodeColor", "linkColor", "nodeCanvasObject", "linkCanvasObject"]);
18
+ const d3Callbacks = new Set(["attr", "style", "each"]);
19
+ const colorProperty = /^(?:getPropertyValue|color|backgroundColor|background|borderColor|border(?:Top|Right|Bottom|Left|Block|Inline)\w*Color|outlineColor|fill|stroke|caretColor|accentColor|textDecorationColor|columnRuleColor|floodColor|stopColor|lightingColor)$/;
20
+
21
+ const isFunction = node => node && (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node));
22
+ const callName = expression => ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : null;
23
+ const memberName = node => node && (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) ? node.text : null;
24
+
25
+ /** Whether a getComputedStyle(...) call feeds a color read: a color property or
26
+ * getPropertyValue on it, directly or through the variable it is stored in. */
27
+ function readsColor(call) {
28
+ const parent = call.parent;
29
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === call) return colorProperty.test(parent.name.text);
30
+ if (ts.isElementAccessExpression(parent) && parent.expression === call) return ts.isStringLiteralLike(parent.argumentExpression) && colorProperty.test(parent.argumentExpression.text);
31
+ if (!ts.isVariableDeclaration(parent) || !ts.isIdentifier(parent.name)) return false;
32
+ const name = parent.name.text;
33
+ let scope = parent;
34
+ while (scope && !isFunction(scope) && !ts.isSourceFile(scope)) scope = scope.parent;
35
+ let found = false;
36
+ const visit = node => {
37
+ if (found) return;
38
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === name && colorProperty.test(node.name.text)) found = true;
39
+ else ts.forEachChild(node, visit);
40
+ };
41
+ if (scope) visit(scope);
42
+ return found;
43
+ }
44
+
45
+ /** A direct probe in one call: a computed color read or a canvas pixel read. */
46
+ function directProbe(node) {
47
+ if (!ts.isCallExpression(node)) return null;
48
+ const name = callName(node.expression);
49
+ if (name === "getComputedStyle" && readsColor(node)) return "getComputedStyle()";
50
+ if (name === "getImageData" && ts.isPropertyAccessExpression(node.expression)) return "getImageData()";
51
+ return null;
52
+ }
53
+
54
+ export function createRenderColorProbe(program) {
55
+ const checker = program.getTypeChecker(), probing = new Map();
56
+
57
+ /** The declaration body a call or reference reaches in the project's own source. */
58
+ function target(expression) {
59
+ let symbol = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(expression) ? expression.name : expression);
60
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) { try { symbol = checker.getAliasedSymbol(symbol); } catch { return null; } }
61
+ for (const declaration of symbol?.declarations ?? []) {
62
+ const source = declaration.getSourceFile();
63
+ if (source.isDeclarationFile || /[\\/]node_modules[\\/]/.test(source.fileName)) continue;
64
+ if (isFunction(declaration)) return declaration;
65
+ if (ts.isVariableDeclaration(declaration) && isFunction(declaration.initializer)) return declaration.initializer;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /** The probe a function performs, directly or through a helper it calls; null otherwise. */
71
+ function probeOf(fn, stack = new Set()) {
72
+ if (probing.has(fn)) return probing.get(fn);
73
+ if (stack.has(fn)) return null;
74
+ stack.add(fn);
75
+ let found = null;
76
+ const visit = node => {
77
+ if (found) return;
78
+ if (node !== fn && isFunction(node)) return;
79
+ const direct = directProbe(node);
80
+ if (direct) { found = direct; return; }
81
+ if (ts.isCallExpression(node)) {
82
+ const callee = target(node.expression);
83
+ const inner = callee && probeOf(callee, stack);
84
+ if (inner) { found = `${callName(node.expression) ?? "a helper"}() → ${inner}`; return; }
85
+ }
86
+ ts.forEachChild(node, visit);
87
+ };
88
+ if (fn.body) visit(fn.body);
89
+ stack.delete(fn);
90
+ probing.set(fn, found);
91
+ return found;
92
+ }
93
+
94
+ /** What makes a function a per-item render path, or null. */
95
+ function perItem(fn) {
96
+ const parent = fn.parent;
97
+ if (!parent) return null;
98
+ if (ts.isCallExpression(parent) && parent.arguments.includes(fn)) {
99
+ const name = callName(parent.expression), index = parent.arguments.indexOf(fn);
100
+ if (ts.isPropertyAccessExpression(parent.expression) && iterators.has(name) && index === 0) return `a .${name}() callback`;
101
+ if (ts.isPropertyAccessExpression(parent.expression) && d3Callbacks.has(name) && index === (name === "each" ? 0 : 1)) return `a .${name}() callback`;
102
+ if (ts.isPropertyAccessExpression(parent.expression) && rendererHooks.has(name) && index === 0) return `the ${name} hook`;
103
+ if (name === "setSetting" && index === 1 && rendererHooks.has(memberName(parent.arguments[0]))) return `the ${parent.arguments[0].text} hook`;
104
+ if (name === "from" && index === 1 && ts.isPropertyAccessExpression(parent.expression) && ts.isIdentifier(parent.expression.expression) && parent.expression.expression.text === "Array") return "an Array.from() callback";
105
+ }
106
+ if ((ts.isPropertyAssignment(parent) || ts.isJsxAttribute(parent)) && rendererHooks.has(memberName(parent.name))) return `the ${memberName(parent.name)} hook`;
107
+ if (ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent) && rendererHooks.has(memberName(parent.parent.name))) return `the ${memberName(parent.parent.name)} hook`;
108
+ return null;
109
+ }
110
+
111
+ /** Review findings for one component or pattern source file. */
112
+ return function renderColorProbeAdvisories(source) {
113
+ const findings = [], seen = new Set();
114
+ const report = (node, probe, where) => {
115
+ const at = source.getLineAndCharacterOfPosition(node.getStart(source)), key = `${at.line}:${at.character}`;
116
+ if (seen.has(key)) return;
117
+ seen.add(key);
118
+ findings.push({ rule: "render-color-probe", severity: findingSeverity("render-color-probe"), line: at.line + 1, column: at.character + 1, message: `${message} Found ${probe} in ${where}.` });
119
+ };
120
+ /** Probes inside one per-item body. Nested functions and loops are not descended into: a
121
+ * nested per-item path is scanned on its own, and other nested functions run later. */
122
+ const scan = (body, where) => {
123
+ const visit = node => {
124
+ if (node !== body && (isFunction(node) || ts.isForOfStatement(node) || ts.isForInStatement(node) || ts.isForStatement(node))) return;
125
+ const direct = directProbe(node);
126
+ if (direct) { report(node, direct, where); return; }
127
+ if (ts.isCallExpression(node)) {
128
+ const callee = target(node.expression), inner = callee && probeOf(callee);
129
+ if (inner) { report(node, `${callName(node.expression) ?? "a helper"}() → ${inner}`, where); return; }
130
+ }
131
+ ts.forEachChild(node, visit);
132
+ };
133
+ visit(body);
134
+ };
135
+ const visit = node => {
136
+ if (isFunction(node) && node.body) { const where = perItem(node); if (where) scan(node.body, where); }
137
+ if (ts.isForOfStatement(node) || ts.isForInStatement(node) || ts.isForStatement(node)) scan(node.statement, ts.isForOfStatement(node) ? "a for…of loop" : ts.isForInStatement(node) ? "a for…in loop" : "a for loop");
138
+ // A probing function passed by name: nodes.map(colorOf).
139
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && iterators.has(node.expression.name.text) && node.arguments[0] && ts.isIdentifier(node.arguments[0])) {
140
+ const reference = target(node.arguments[0]), passed = reference && probeOf(reference);
141
+ if (passed) report(node.arguments[0], `${node.arguments[0].text}() → ${passed}`, `a .${node.expression.name.text}() callback`);
142
+ }
143
+ ts.forEachChild(node, visit);
144
+ };
145
+ visit(source);
146
+ return findings;
147
+ };
148
+ }
@@ -4,6 +4,7 @@ import selectorParser from "postcss-selector-parser";
4
4
  import { isDevelopmentFile, isReviewFile } from "./config.mjs";
5
5
  import { inspectUnitContracts, implementationIdentity, implementationNode } from "./unit-contracts.mjs";
6
6
  import { tokenContract } from "./token-policy.mjs";
7
+ import { generatedPaletteFile } from "./palette-generated.mjs";
7
8
  import { uiOperation } from "./ui-framework.mjs";
8
9
  import { createChildFlow } from "./declarative-flow.mjs";
9
10
  import { unwrap, createSourceValues, reference } from "./source-values.mjs";
@@ -30,6 +31,10 @@ export function inspectRuntimeContracts(options, program) {
30
31
  return symbol?.valueDeclaration;
31
32
  };
32
33
  const same=(node,reference)=>{const declaration=canonical(node);return declaration&&implementationIdentity(declaration,options.root)===reference.identity;};
34
+ // themed()/themedByScheme() exported by this design system's generated palette module; its
35
+ // freshness check keeps their bodies the generated switch expressions.
36
+ const generatedModule=path.join(options.dsRoot,options.config.tokenDir,generatedPaletteFile);
37
+ const generatedHelper=node=>{const declaration=canonical(node);return declaration&&ts.isFunctionDeclaration(declaration)&&["themed","themedByScheme"].includes(declaration.name?.text)&&path.resolve(declaration.getSourceFile().fileName)===generatedModule?declaration.name.text:null;};
33
38
  function report(contract,message,code="runtime-contract") {result.diagnostics.push({file:contract.file,rule:code,line:1,column:1,message});}
34
39
  function localCalls(node,seen=new Set()) {
35
40
  if(!node||seen.has(node)||seen.size>32)return [];
@@ -110,9 +115,14 @@ export function inspectRuntimeContracts(options, program) {
110
115
  return expression&&checker.getSymbolAtLocation(expression)===valueSymbol&&valuePaths.includes(fields.join("."));
111
116
  }
112
117
  if(entryValue(value))return true;
113
- return ts.isTemplateExpression(value)&&value.head.text==="light-dark("&&value.templateSpans.length===2
114
- &&/^\s*,\s*$/.test(value.templateSpans[0].literal.text)&&value.templateSpans[1].literal.text===")"
115
- &&value.templateSpans.every(span=>entryValue(span.expression));
118
+ // A themed value: the generated themed()/themedByScheme() over declared entry paths only,
119
+ // with exactly the keys the helper takes (every declared theme, or light and dark).
120
+ const helper=ts.isCallExpression(value)&&value.arguments.length===1&&generatedHelper(value.expression);
121
+ const values=helper&&unwrap(value.arguments[0]);
122
+ if(!values||!ts.isObjectLiteralExpression(values))return false;
123
+ const keys=values.properties.map(property=>ts.isPropertyAssignment(property)&&(ts.isIdentifier(property.name)||ts.isStringLiteral(property.name))&&entryValue(property.initializer)?property.name.text:null);
124
+ const expected=helper==="themed"?options.config.themes.map(theme=>theme.name):["light","dark"];
125
+ return keys.every(Boolean)&&new Set(keys).size===keys.length&&keys.length===expected.length&&expected.every(name=>keys.includes(name));
116
126
  }
117
127
  function proveMap(body,seen=new Set()) {
118
128
  if(!body?.parameters?.[0]||!ts.isIdentifier(body.parameters[0].name)||seen.has(body)||seen.size>8)return null;
@@ -152,7 +162,7 @@ export function inspectRuntimeContracts(options, program) {
152
162
  return mapSymbol&&!escapes&&checker.getSymbolAtLocation(returned)===mapSymbol?[body]:null;
153
163
  }
154
164
  const proof=proveMap(producer);
155
- if(!proof){report(contract,`${name}: producer must return only the declared config-entry paint map. Declare every source path in valueFrom (one path or an array), with matching paintInputs; theme pairs may use an exact light-dark() template over two declared paths. Use Object.entries with a loop or Object.fromEntries/map, guard keys with /^[A-Za-z0-9_-]+$/ before writing (throw or continue), and the exact computed family. Owner-local helper returns are supported; escaped maps, extra writes and unknown returns grant no permission.`,"binding-producer");continue;}
165
+ if(!proof){report(contract,`${name}: producer must return only the declared config-entry paint map. Declare every source path in valueFrom (one path or an array), with matching paintInputs; per-theme values may use themed() or themedByScheme() from the generated ${options.config.tokenDir}/${generatedPaletteFile} over declared paths only. Use Object.entries with a loop or Object.fromEntries/map, guard keys with /^[A-Za-z0-9_-]+$/ before writing (throw or continue), and the exact computed family. Owner-local helper returns are supported; escaped maps, extra writes and unknown returns grant no permission.`,"binding-producer");continue;}
156
166
  const scope=fn(implementationNode(program,binding.scope.api,options.root));
157
167
  let attached=false;
158
168
  const returnedElements=new Set();
@@ -176,7 +176,7 @@ export function inspectScenarios(options, suppliedProgram) {
176
176
  const reachable = new Set(metadata.covers);
177
177
  function findBindings(node) { if(ts.isJsxElement(node)||ts.isJsxSelfClosingElement(node))for(const name of bindingTrace.traceRenders(node).rendered)reachable.add(name);ts.forEachChild(node,findBindings); }
178
178
  if(bindingTrace) findBindings(source);
179
- const paintBindings = inspectRuntimeContracts(options,program).bindings.filter(binding=>reachable.has(binding.scope.apiName)).map(binding=>({owner:binding.unit,name:binding.name,scope:binding.scope.selector,prefix:binding.prefix,suffix:binding.suffix,tokens:tokenInventory.tokens.filter(token=>!token.owner||token.owner==="tokens"||token.owner===binding.unit).map(token=>token.name)}));
179
+ const paintBindings = inspectRuntimeContracts(options,program).bindings.filter(binding=>reachable.has(binding.scope.apiName)).map(binding=>({owner:binding.unit,name:binding.name,scope:binding.scope.selector,prefix:binding.prefix,suffix:binding.suffix,themes:options.config.themes.map(theme=>theme.name),tokens:tokenInventory.tokens.filter(token=>!token.owner||token.owner==="tokens"||token.owner===binding.unit).map(token=>token.name)}));
180
180
  const paintAudit=contractDeclarations.some(contract=>contract.paintInputs?.some(input=>reachable.has(input.apiName)));
181
181
  scenarios.push({ id, kind, title: metadata.title, ...(group ? { group } : {}), ...(fixture ? { fixture: path.relative(root, fixture).replaceAll("\\", "/") } : {}), covers: [...new Set(metadata.covers)], ...(captureTargets ? { captureTargets } : {}), ...(Object.hasOwn(metadata, "exercises") ? { exercises: [...new Set(exercises)] } : {}), tokens, ...(metadata.samples ? { samples: metadata.samples } : {}), ...(paintBindings.length?{paintBindings}:{}), ...(paintAudit?{paintAudit:true}:{}), file: path.relative(root, file).replaceAll("\\", "/"), artifact: path.relative(root, scenarioArtifact(root, id)).replaceAll("\\", "/") });
182
182
  }