An open source design system that's fully customizable and agent ready
TypeScript
build(css): fail when a stylesheet reads a StyleX variable nothing declares (#7730)
Christopher Chedeau917864de56d5
diff --git a/scripts/build-css.graph.test.mjs b/scripts/build-css.graph.test.mjsindex 1e6c2d2c50..884e06e828 100644--- a/scripts/build-css.graph.test.mjs+++ b/scripts/build-css.graph.test.mjs@@ -5,7 +5,7 @@ import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import {afterEach, describe, expect, it} from 'vitest';-import {collectStyleXCSS} from './build-css.mjs';+import {collectStyleXCSS, undefinedStyleXVariables} from './build-css.mjs';const temporaryRoots = [];@@ -128,3 +128,81 @@ describe('build-css dependency extraction', () => {expect(css).not.toContain('--probe-shared');});});++describe('build-css undefined StyleX variables', () => {+ async function compile(consumer, modules) {+ const {src, external} = await fixture();+ await fs.writeFile(path.join(src, 'Consumer.ts'), consumer);+ for (const [name, source] of Object.entries(modules)) {+ await fs.writeFile(path.join(external, name), source);+ }+ const rules = await collectStyleXCSS({+ src,+ aliases: {'@probe/*': [path.join(external, '*')]},+ });+ return stylexBabelPlugin.processStylexRules(rules, false);+ }++ const tokens = `import * as stylex from '@stylexjs/stylex';+export const probeVars = stylex.defineVars({'--probe-ring-width': '2px'});+export const probeConsts = stylex.defineConsts({cap: 'calc(100dvb - 32px)'});+export const PLAIN_PARTS = {outlineWidth: probeVars['--probe-ring-width']};+`;++ it('reports a plain object from a .stylex.ts module read inside stylex.create', async () => {+ const css = await compile(+ `import * as stylex from '@stylexjs/stylex';+import {PLAIN_PARTS} from '@probe/tokens.stylex';+export const styles = stylex.create({ring: {outlineWidth: PLAIN_PARTS.outlineWidth}});+`,+ {'tokens.stylex.ts': tokens},+ );+ const missing = undefinedStyleXVariables(css);+ expect(missing).toHaveLength(1);+ expect(css).toContain(`outline-width:var(${missing[0]})`);+ });++ it('reports a defineConsts member passed to firstThatWorks on its own, not one inside calc()', async () => {+ const alone = await compile(+ `import * as stylex from '@stylexjs/stylex';+import {probeConsts} from '@probe/tokens.stylex';+export const styles = stylex.create({box: {maxHeight: stylex.firstThatWorks(probeConsts.cap, '90vh')}});+`,+ {'tokens.stylex.ts': tokens},+ );+ expect(undefinedStyleXVariables(alone)).toHaveLength(1);++ const wrapped = await compile(+ `import * as stylex from '@stylexjs/stylex';+import {probeConsts} from '@probe/tokens.stylex';+export const styles = stylex.create({box: {maxHeight: stylex.firstThatWorks(\`calc(\${probeConsts.cap})\`, '90vh')}});+`,+ {'tokens.stylex.ts': tokens},+ );+ expect(undefinedStyleXVariables(wrapped)).toEqual([]);+ expect(wrapped).toContain('calc(calc(100dvb - 32px))');+ });++ it('accepts defineVars tokens and dynamic-style variables', async () => {+ const css = await compile(+ `import * as stylex from '@stylexjs/stylex';+import {probeVars} from '@probe/tokens.stylex';+export const styles = stylex.create({+ ring: {outlineWidth: probeVars['--probe-ring-width']},+ inset: (block) => ({marginBlockStart: block}),+});+`,+ {'tokens.stylex.ts': tokens},+ );+ expect(css).toMatch(/var\(--x-/);+ expect(undefinedStyleXVariables(css)).toEqual([]);+ });++ it("counts the provider stylesheet's declarations", () => {+ const satellite = '.xabc{color:var(--x1provided)}';+ expect(undefinedStyleXVariables(satellite)).toEqual(['--x1provided']);+ expect(+ undefinedStyleXVariables(satellite, ':root{--x1provided:red}'),+ ).toEqual([]);+ });+});diff --git a/scripts/build-css.mjs b/scripts/build-css.mjsindex 63cf04db66..1b7e71b9d5 100644--- a/scripts/build-css.mjs+++ b/scripts/build-css.mjs@@ -12,7 +12,9 @@* This script:* 1. Runs Babel with the StyleX plugin over the target package's source files* 2. Collects all StyleX rules- * 3. Outputs a combined stylesheet that registers the Astryx layer order and+ * 3. Fails when the stylesheet reads a StyleX-generated variable that nothing+ * declares (see undefinedStyleXVariables)+ * 4. Outputs a combined stylesheet that registers the Astryx layer order and* places all rules in @layer astryx-base** Dist consumers import the full stylesheet, e.g.:@@ -323,6 +325,51 @@ export function composePackageStylesheet(banner, css) {return `/* ${banner} */\n/* Auto-generated. Do not edit manually. */\n\n${ASTRYX_LAYER_ORDER}\n\n@layer astryx-base {\n${body}\n}\n`;}+/**+ * The StyleX-generated custom properties a stylesheet reads that neither it+ * nor its provider's stylesheet declares. StyleX names a variable it+ * generates `--x<hash>`. One that is read but never declared is a value that+ * compiled to a variable no rule sets, so every browser drops the declaration+ * or takes its fallback. That happens when a style reads, from a `.stylex.ts`+ * module, a value StyleX cannot inline in that position: a plain exported+ * object or string, or a `defineConsts` member passed to `firstThatWorks` on+ * its own. The dynamic-style variables StyleX sets inline (`--x-<property>`)+ * are not generated names and are never reported.+ */+export function undefinedStyleXVariables(css, providerCss = '') {+ const declared = new Set(+ [...`${css}\n${providerCss}`.matchAll(/(--x[a-z0-9]+)\s*:/g)].map(+ match => match[1],+ ),+ );+ const read = new Set(+ [...css.matchAll(/var\(\s*(--x[a-z0-9]+)\s*[,)]/g)].map(match => match[1]),+ );+ return [...read].filter(name => !declared.has(name)).sort();+}++/** The rules of `css` that read `name`, for the failure message. */+function rulesReading(css, name) {+ return [...css.matchAll(/[^{}]+\{[^{}]*\}/g)]+ .map(match => match[0].trim())+ .filter(rule => rule.includes(`var(${name}`));+}++/**+ * The provider package's built stylesheet, or `null` when it has not been+ * built: a satellite may read a variable group only the provider declares.+ */+async function readProviderCss(provider) {+ try {+ return await fs.readFile(+ path.resolve(provider.dist, provider.outFile),+ 'utf8',+ );+ } catch {+ return null;+ }+}+async function main() {const target = parseTarget();const allRules = await collectStyleXCSS(target);@@ -336,6 +383,31 @@ async function main() {const combinedCSS = stylexBabelPlugin.processStylexRules(allRules, false);+ const providerCss = target.provider+ ? await readProviderCss(target.provider)+ : '';+ if (providerCss === null) {+ console.warn(+ `${target.provider.outFile} is not built yet, so StyleX variables ${target.outFile} reads are not checked.`,+ );+ } else {+ const missing = undefinedStyleXVariables(combinedCSS, providerCss);+ if (missing.length > 0) {+ const detail = missing+ .flatMap(name => rulesReading(combinedCSS, name))+ .map(rule => ` ${rule}`)+ .join('\n');+ console.error(+ `${target.outFile} reads StyleX variables nothing declares: ${missing.join(', ')}.\n` ++ `A style reads, from a .stylex.ts module, a value StyleX cannot inline there:\n` ++ `a plain exported object or string (compose defineVars tokens instead), or a\n` ++ `defineConsts member passed to firstThatWorks on its own (wrap it in calc()).\n` ++ detail,+ );+ process.exit(1);+ }+ }+const outPath = path.resolve(target.dist, target.outFile);await fs.writeFile(outPath,