An open source design system that's fully customizable and agent ready
TypeScript
test(cli): guard public component theme vars against being documented but unsettable (#5409)
Cindy Zhang3c52d510c933
diff --git a/.changeset/theming-var-enumeration.md b/.changeset/theming-var-enumeration.mdnew file mode 100644index 0000000000..57c5b8e817--- /dev/null+++ b/.changeset/theming-var-enumeration.md@@ -0,0 +1,13 @@+---+'@astryxdesign/cli': patch+---++[chore] Public component theming vars are enumerable, and guarded against being documented but unsettable+@cixzhang++`collectThemingVars` joins `collectThemingTargets` as part of the one+enumeration the theming surface is read from. Two guards ride on it: a+documented public var no component reads compiles to a declaration that never+applies, and a var the component writes inline outranks every cascade layer, so+no theme can reach it. Both had shipped; neither is visible in the generated+theme CSS the jsdom suites assert on.diff --git a/packages/cli/foundation/discovery/theming-targets.mjs b/packages/cli/foundation/discovery/theming-targets.mjsindex 3434e4d76c..d1f4c21f5b 100644--- a/packages/cli/foundation/discovery/theming-targets.mjs+++ b/packages/cli/foundation/discovery/theming-targets.mjs@@ -108,6 +108,73 @@ export async function collectThemingTargets(coreSrc) {return targets;}+/**+ * One public custom property a theme may set on a component's target.+ * @typedef {object} ThemingVar+ * @property {string} name - the custom property, e.g. `--tree-list-indent`+ * @property {string} component - the component whose doc declares it+ * @property {string} dir - absolute path to the directory the doc lives in+ * @property {string} default - the documented default value+ */++/**+ * Every PUBLIC theming var declared under a core `src` directory, sorted by+ * name. Private `--_*` vars are a component's own plumbing, not a theme's to+ * set, so they are not enumerated here.+ *+ * @param {string} coreSrc - absolute path to `<core>/src`+ * @returns {Promise<ThemingVar[]>}+ */+export async function collectThemingVars(coreSrc) {+ if (!coreSrc || !fs.existsSync(coreSrc)) return [];++ /** @type {Map<string, ThemingVar>} */+ const vars = new Map();++ /** @param {string} dir */+ async function scan(dir) {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (SKIP_DIRS.has(entry.name)) continue;+ await scan(full);+ continue;+ }+ if (!entry.name.endsWith('.doc.mjs')) continue;++ /** @type {any} */+ let doc;+ try {+ doc = await loadComponentDoc(full);+ } catch {+ continue;+ }++ const component =+ typeof doc?.name === 'string' && doc.name+ ? doc.name+ : path.basename(path.dirname(full));++ for (const entryVar of doc?.theming?.vars || []) {+ const name = entryVar?.name;+ if (typeof name !== 'string') continue;+ if (entryVar.private === true || name.startsWith('--_')) continue;+ if (vars.has(name)) continue;+ vars.set(name, {+ name,+ component,+ dir: path.dirname(full),+ default: typeof entryVar.default === 'string' ? entryVar.default : '',+ });+ }+ }+ }++ await scan(coreSrc);++ return [...vars.values()].sort((a, b) => a.name.localeCompare(b.name));+}+/*** Collapse the enumeration into the `{key: [props and states]}` map theme* validation checks override keys against — both are legal override keys, sodiff --git a/packages/cli/foundation/discovery/theming-targets.test.mjs b/packages/cli/foundation/discovery/theming-targets.test.mjsindex f61e812b9d..4ef70a5c5e 100644--- a/packages/cli/foundation/discovery/theming-targets.test.mjs+++ b/packages/cli/foundation/discovery/theming-targets.test.mjs@@ -10,9 +10,19 @@* while `theme targets` says another. That divergence is the failure the* listing exists to prevent: a target list that can drift from the components* is worse than no list.+ *+ * The public vars a target carries get the same treatment, one step further:+ * being enumerable is not the same as being settable. A documented var no+ * component reads compiles to a declaration that never applies (#5012), and a+ * var the component writes inline outranks every cascade layer, so no theme can+ * reach it (#4530). Both shipped. Neither is visible in the generated theme CSS+ * — the artifact the jsdom suites assert on — so the wiring is checked here+ * against source. Whether the cascade then lands the value on the element is a+ * browser fact and no jsdom test can stand in for it.*/import {describe, it, expect} from 'vitest';+import * as fs from 'node:fs';import * as path from 'node:path';import {findCoreDir} from '../fs/paths.mjs';import {@@ -20,7 +30,11 @@ import {findComponentReadme,} from './component-discovery.mjs';import {loadComponentDoc} from './component-loader.mjs';-import {collectThemingTargets, targetsByKey} from './theming-targets.mjs';+import {+ collectThemingTargets,+ collectThemingVars,+ targetsByKey,+} from './theming-targets.mjs';const coreDir = /** @type {string} */ (findCoreDir(process.cwd()));const coreSrc = path.join(coreDir, 'src');@@ -125,3 +139,107 @@ describe('collectThemingTargets', () => {expect(missing).toEqual([]);}, 60_000);});++// ---------------------------------------------------------------------------+// Public vars — enumerable is not the same as settable+// ---------------------------------------------------------------------------++/** @type {Promise<import('./theming-targets.mjs').ThemingVar[]>} */+const enumeratedVars = collectThemingVars(coreSrc);++/** Every non-test source file under a component directory. */+function sourcesIn(dir) {+ /** @type {string[]} */+ const out = [];+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ if (entry.isDirectory()) {+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;+ out.push(...sourcesIn(path.join(dir, entry.name)));+ continue;+ }+ if (!/\.tsx?$/.test(entry.name)) continue;+ if (/\.(test|stories)\.tsx?$/.test(entry.name)) continue;+ out.push(path.join(dir, entry.name));+ }+ return out;+}++/**+ * The text of every inline style a file writes — `style={{…}}` objects and+ * `setProperty` calls. A custom property written from either outranks every+ * cascade layer, so a theme cannot reach it.+ */+function inlineStyleText(src) {+ const chunks = [];+ for (const m of src.matchAll(/style=\{\{/g)) {+ const end = src.indexOf('}}', m.index);+ chunks.push(src.slice(m.index, end === -1 ? src.length : end));+ }+ for (const m of src.matchAll(/setProperty\(\s*'[^']+'/g)) chunks.push(m[0]);+ return chunks.join('\n');+}++describe('collectThemingVars', () => {+ it('enumerates the public vars and drops the private plumbing', async () => {+ const names = (await enumeratedVars).map(v => v.name);+ expect(names.length).toBeGreaterThan(0);+ expect(names.every(n => !n.startsWith('--_'))).toBe(true);+ expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)));+ expect(names).toEqual([...new Set(names)]);+ });++ it('carries the component and the documented default', async () => {+ const indent = (await enumeratedVars).find(+ v => v.name === '--tree-list-indent',+ );+ expect(indent).toMatchObject({+ name: '--tree-list-indent',+ component: 'TreeList',+ default: 'var(--spacing-4)',+ });+ });++ // #5012: the theme docs advertised `--button-press-scale`, which no component+ // ever read. A theme setting it compiled to a declaration nothing consumed,+ // and nothing failed — the var was in the docs, so every existence check+ // passed. Reading it is the minimum that makes a documented var mean anything.+ it('every documented var is read by the component that documents it', async () => {+ /** @type {string[]} */+ const unread = [];+ for (const v of await enumeratedVars) {+ const read = sourcesIn(v.dir).some(f =>+ fs.readFileSync(f, 'utf-8').includes(`var(${v.name}`),+ );+ if (!read) unread.push(`${v.component}: nothing reads var(${v.name})`);+ }+ expect(+ unread,+ `A documented public var no component reads compiles to a declaration ` ++ `that never applies (#5012). Either wire it up or drop it from the doc.`,+ ).toEqual([]);+ });++ // #4530: TreeList's indent was an inline `margin-inline-start` on the element+ // carrying the theme target. An inline declaration outranks every cascade+ // layer, so `@layer astryx-theme` could not reach it — the var was real, read,+ // and documented, and still unsettable. The fix moved it into a StyleX rule.+ it('no documented var is written inline, where no theme can outrank it', async () => {+ /** @type {string[]} */+ const clobbered = [];+ for (const v of await enumeratedVars) {+ for (const f of sourcesIn(v.dir)) {+ if (inlineStyleText(fs.readFileSync(f, 'utf-8')).includes(v.name)) {+ clobbered.push(+ `${v.component}: ${path.basename(f)} sets ${v.name} inline`,+ );+ }+ }+ }+ expect(+ clobbered,+ `An inline custom property beats every cascade layer, so a theme setting ` ++ `it through @layer astryx-theme is silently ignored (#4530). Declare it ` ++ `in a StyleX rule instead.`,+ ).toEqual([]);+ });+});