Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(build): resolve defineConsts read across files in astryxStylex (#8075)

Christopher Chedeau8d0a84712cfa
diff --git a/.changeset/build-stylex-cross-file-consts.md b/.changeset/build-stylex-cross-file-consts.md
new file mode 100644
index 0000000000..736b20da43
--- /dev/null
+++ b/.changeset/build-stylex-cross-file-consts.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/build': patch
+---
+
+[fix] `astryxStylex` resolves `defineConsts` values read from another file. With the `{stylexOptions}` form (the one Storybook uses), a file that read only constants from a `.stylex.ts` module lost that import once StyleX compiled it, so the constants never reached the CSS: a constant used as a media-query key failed the build ("Invalid empty selector") and one used as a value shipped as a custom property nothing declares. In either form, a constant defined on the other side of the layer split, or in an Astryx package (compiled with the library class-name prefix) and read from an app file (compiled with its own), stayed unresolved.
+
+@vjeux
diff --git a/.changeset/build-stylex-undefined-variables.md b/.changeset/build-stylex-undefined-variables.md
new file mode 100644
index 0000000000..f96458edef
--- /dev/null
+++ b/.changeset/build-stylex-undefined-variables.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/build': patch
+---
+
+[feat] A production build with `astryxStylex` warns when its stylesheet reads a StyleX-generated custom property that nothing declares, naming the variable and the rule that reads it. It checks the class-name prefixes the build uses, `stylexOverrides.classNamePrefix` included, and never reports a custom property an app declares in its own CSS.
+
+@vjeux
diff --git a/packages/build/README.md b/packages/build/README.md
index 0bc69e79c6..301e0df247 100644
--- a/packages/build/README.md
+++ b/packages/build/README.md
@@ -239,6 +239,8 @@ Wraps `@stylexjs/unplugin` and intercepts the dev CSS endpoint (`/virtual:stylex
Unsupported declarations fail the build by default with StyleX's replacement guidance. Set `propertyValidationMode` explicitly in `stylexOverrides` (modern API) or `stylexOptions` (legacy API) only when a migration needs the upstream `warn` or `silent` behavior.
+A production build also checks the StyleX stylesheet for generated custom properties (`--<prefix><hash>`) that it reads but no stylesheet in the build declares, which browsers drop: a `.stylex.ts` export read in a style that is not a `defineVars`/`defineConsts` value, or one whose module never reached the build. It warns, naming the variable and the rule that reads it. Only stylesheets count as declarations, so a property the app sets at runtime (an inline style) is reported too: give it a name outside the StyleX class-name prefixes.
+
---
## Advanced Options
diff --git a/packages/build/__fixtures__/stylex-app-vars/App.tsx b/packages/build/__fixtures__/stylex-app-vars/App.tsx
new file mode 100644
index 0000000000..cb6fb63927
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-app-vars/App.tsx
@@ -0,0 +1,18 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Reads the app's own custom properties, declared in its own CSS rather than
+ * by StyleX. Their names happen to start with the product prefix (`x`): one
+ * short (`--xl`), one as long as a StyleX hash (`--xlarge`). Neither is a
+ * dropped declaration.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ root: {paddingTop: 'var(--xlarge)', marginTop: 'var(--xl)'},
+});
+
+export function App() {
+ return <div {...stylex.props(styles.root)}>app vars</div>;
+}
diff --git a/packages/build/__fixtures__/stylex-app-vars/app.css b/packages/build/__fixtures__/stylex-app-vars/app.css
new file mode 100644
index 0000000000..39c13b7e6e
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-app-vars/app.css
@@ -0,0 +1,7 @@
+/* Copyright (c) Meta Platforms, Inc. and affiliates. */
+
+/* The app's own custom properties, declared in its own stylesheet. */
+:root {
+ --xl: 4px;
+ --xlarge: 24px;
+}
diff --git a/packages/build/__fixtures__/stylex-app-vars/index.html b/packages/build/__fixtures__/stylex-app-vars/index.html
new file mode 100644
index 0000000000..abc3638de5
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-app-vars/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>stylex-app-vars fixture — an app's own custom properties</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./main.tsx"></script>
+ </body>
+</html>
diff --git a/packages/build/__fixtures__/stylex-app-vars/main.tsx b/packages/build/__fixtures__/stylex-app-vars/main.tsx
new file mode 100644
index 0000000000..794f0df713
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-app-vars/main.tsx
@@ -0,0 +1,7 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createRoot} from 'react-dom/client';
+import './app.css';
+import {App} from './App';
+
+createRoot(document.getElementById('root')!).render(<App />);
diff --git a/packages/build/__fixtures__/stylex-consts/App.tsx b/packages/build/__fixtures__/stylex-consts/App.tsx
new file mode 100644
index 0000000000..5e839e5372
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/App.tsx
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Reads `defineConsts` values from other files, as a media-query key and as a
+ * plain value, from both sides of the layer split and from a file compiled
+ * with the library class-name prefix. Only the constants are
+ * imported: once StyleX compiles `stylex.create`, nothing in this file uses
+ * the imports at runtime any more.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {appConsts} from './appConsts.stylex';
+import {libraryConsts} from './library/libraryConsts.stylex';
+import {packageConsts} from './packages/core/packageConsts.stylex';
+
+const styles = stylex.create({
+ row: {
+ minHeight: appConsts.rowHeight,
+ transitionProperty: {default: 'color', [appConsts.narrow]: 'none'},
+ },
+ panel: {
+ paddingTop: libraryConsts.inset,
+ paddingBottom: packageConsts.gap,
+ maxWidth: {default: null, [libraryConsts.wide]: '640px'},
+ },
+});
+
+export function App() {
+ return (
+ <div {...stylex.props(styles.panel)}>
+ <div {...stylex.props(styles.row)}>row</div>
+ </div>
+ );
+}
diff --git a/packages/build/__fixtures__/stylex-consts/appConsts.stylex.ts b/packages/build/__fixtures__/stylex-consts/appConsts.stylex.ts
new file mode 100644
index 0000000000..5e41328b69
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/appConsts.stylex.ts
@@ -0,0 +1,9 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/** Constants the app defines itself, beside the file that reads them. */
+export const appConsts = stylex.defineConsts({
+ narrow: '@media (max-width: 599px)',
+ rowHeight: '52px',
+});
diff --git a/packages/build/__fixtures__/stylex-consts/index.html b/packages/build/__fixtures__/stylex-consts/index.html
new file mode 100644
index 0000000000..ba86fc975f
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>stylex-consts fixture — defineConsts imported across files</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./main.tsx"></script>
+ </body>
+</html>
diff --git a/packages/build/__fixtures__/stylex-consts/library/libraryConsts.stylex.ts b/packages/build/__fixtures__/stylex-consts/library/libraryConsts.stylex.ts
new file mode 100644
index 0000000000..92dda6955e
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/library/libraryConsts.stylex.ts
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Constants on the library side of the layer split (the build test points
+ * `libraryPattern` at this folder), read by an app file on the product side.
+ */
+export const libraryConsts = stylex.defineConsts({
+ wide: '@media (min-width: 900px)',
+ inset: '13px',
+});
diff --git a/packages/build/__fixtures__/stylex-consts/main.tsx b/packages/build/__fixtures__/stylex-consts/main.tsx
new file mode 100644
index 0000000000..5811fe017b
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/main.tsx
@@ -0,0 +1,6 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createRoot} from 'react-dom/client';
+import {App} from './App';
+
+createRoot(document.getElementById('root')!).render(<App />);
diff --git a/packages/build/__fixtures__/stylex-consts/packages/core/packageConsts.stylex.ts b/packages/build/__fixtures__/stylex-consts/packages/core/packageConsts.stylex.ts
new file mode 100644
index 0000000000..b4be85d7a3
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/packages/core/packageConsts.stylex.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Constants as an Astryx package defines them: the path holds `packages/core/`,
+ * so the babel wrapper compiles this file with the library class-name prefix
+ * (`astryx`), as it does a real package. The app file reading them compiles
+ * with its own prefix (`x`).
+ */
+export const packageConsts = stylex.defineConsts({
+ gap: '17px',
+});
diff --git a/packages/build/__fixtures__/stylex-undefined-var/App.tsx b/packages/build/__fixtures__/stylex-undefined-var/App.tsx
new file mode 100644
index 0000000000..fbd157f143
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-undefined-var/App.tsx
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Reads a plain `.stylex.ts` export as if it were a token. The build must fail
+ * and name the variable rather than ship a declaration every browser drops.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {plainTokens} from './plainTokens.stylex';
+
+const styles = stylex.create({
+ root: {rowGap: plainTokens.gap},
+});
+
+export function App() {
+ return <div {...stylex.props(styles.root)}>gap</div>;
+}
diff --git a/packages/build/__fixtures__/stylex-undefined-var/index.html b/packages/build/__fixtures__/stylex-undefined-var/index.html
new file mode 100644
index 0000000000..a7732d7969
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-undefined-var/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>stylex-undefined-var fixture — a plain export read as a token</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./main.tsx"></script>
+ </body>
+</html>
diff --git a/packages/build/__fixtures__/stylex-undefined-var/main.tsx b/packages/build/__fixtures__/stylex-undefined-var/main.tsx
new file mode 100644
index 0000000000..5811fe017b
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-undefined-var/main.tsx
@@ -0,0 +1,6 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createRoot} from 'react-dom/client';
+import {App} from './App';
+
+createRoot(document.getElementById('root')!).render(<App />);
diff --git a/packages/build/__fixtures__/stylex-undefined-var/plainTokens.stylex.ts b/packages/build/__fixtures__/stylex-undefined-var/plainTokens.stylex.ts
new file mode 100644
index 0000000000..fdb800e145
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-undefined-var/plainTokens.stylex.ts
@@ -0,0 +1,7 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * A plain export, not `defineVars`/`defineConsts`: StyleX compiles a read of
+ * it in another file to a custom property that nothing declares.
+ */
+export const plainTokens = {gap: '12px'};
diff --git a/packages/build/src/undefinedVariables.ts b/packages/build/src/undefinedVariables.ts
new file mode 100644
index 0000000000..4ebcfaea71
--- /dev/null
+++ b/packages/build/src/undefinedVariables.ts
@@ -0,0 +1,57 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file undefinedVariables.ts
+ * @input A stylesheet's text, the StyleX class-name prefixes, and the other
+ * stylesheets the build emits
+ * @output undefinedGeneratedVariables, the generated custom properties the
+ * stylesheet reads but never declares
+ * @position Internal to @astryxdesign/build: astryxStylex (vite.ts) runs it
+ * on a production stylesheet and warns about what it finds. Not exported
+ * from any package entry.
+ */
+
+/**
+ * The StyleX-generated custom properties `css` reads that it never declares.
+ *
+ * StyleX names the variables it generates `--<prefix><hash>` (a theme
+ * variable, or a constant waiting for its value). One that is read but never
+ * declared is a value that compiled to a variable nothing sets, so browsers
+ * drop the declaration or take its fallback: a constant whose defining module
+ * never reached the build, or a plain export read from a `.stylex.ts` file as
+ * if it were a token. The dynamic-style variables StyleX sets inline
+ * (`--<prefix>-<property>`) and component variables with a dash after the
+ * prefix are not generated names and are never reported.
+ *
+ * Only a hash-shaped name counts as generated: the prefix and four to seven
+ * base-36 characters (StyleX's hash is a 32-bit value in base 36, shorter than
+ * four characters about once in a hundred thousand). An app's own short names
+ * (`--xl`) are never reported, and a property declared in any stylesheet the
+ * build emits (`others`, the app's own CSS) is declared.
+ *
+ * SYNC: scripts/build-css.mjs `undefinedStyleXVariables` is the same check
+ * for the prebuilt package stylesheets.
+ */
+export function undefinedGeneratedVariables(
+ css: string,
+ prefixes: readonly string[],
+ others: readonly string[] = [],
+): string[] {
+ const names = prefixes
+ .map(prefix => prefix.replace(/[^a-zA-Z0-9_-]/g, ''))
+ .filter(Boolean)
+ .join('|');
+ const declared = new Set(
+ [css, ...others].flatMap(text =>
+ [...text.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map(match => match[1]),
+ ),
+ );
+ const read = new Set(
+ [
+ ...css.matchAll(
+ new RegExp(`var\\(\\s*(--(?:${names})[a-z0-9]{4,7})\\s*[,)]`, 'g'),
+ ),
+ ].map(match => match[1]),
+ );
+ return [...read].filter(name => !declared.has(name)).sort();
+}
diff --git a/packages/build/src/vite.build.test.ts b/packages/build/src/vite.build.test.ts
index ee860275a2..65d9b2ac8f 100644
--- a/packages/build/src/vite.build.test.ts
+++ b/packages/build/src/vite.build.test.ts
@@ -31,7 +31,7 @@
*/
import {describe, it, expect, beforeAll, afterAll} from 'vitest';
-import {build} from 'vite';
+import {build, createLogger} from 'vite';
import react from '@vitejs/plugin-react';
import {
mkdirSync,
@@ -70,6 +70,21 @@ type Built = {
async function buildFixture(
name: string,
htmlNames: string[] = ['index.html'],
+ {
+ libraryPattern = 'packages/core/',
+ zeroConfig = false,
+ stylexOverrides,
+ warnings = [],
+ }: {
+ /** Which source paths land in the library layer. */
+ libraryPattern?: string;
+ /** Use `astryxStylex({...})` instead of the legacy `{stylexOptions}` form. */
+ zeroConfig?: boolean;
+ /** Zero-config form only: `stylexOverrides`. */
+ stylexOverrides?: Record<string, unknown>;
+ /** Receives every warning the build logs. */
+ warnings?: string[];
+ } = {},
): Promise<Built> {
const root = path.join(FIXTURES, name);
const outDir = mkdtempSync(path.join(tmpdir(), `astryx-${name}-`));
@@ -77,6 +92,11 @@ async function buildFixture(
await build({
root,
logLevel: 'error',
+ customLogger: {
+ ...createLogger('error'),
+ warn: (message: string) => void warnings.push(message),
+ warnOnce: (message: string) => void warnings.push(message),
+ },
build: {
outDir,
emptyOutDir: true,
@@ -94,17 +114,27 @@ async function buildFixture(
resolve: {alias: {'@astryxdesign/core': CORE_SRC}},
plugins: [
react(),
- ...astryxStylex({
- stylexOptions: {
- dev: false,
- unstable_moduleResolution: {type: 'commonJS', rootDir: REPO_ROOT},
- aliases: {
- '@astryxdesign/core/*': [path.join(CORE_SRC, '*')],
- '@astryxdesign/core': [CORE_SRC],
- },
- },
- libraryPattern: 'packages/core/',
- }),
+ ...(zeroConfig
+ ? astryxStylex({
+ dev: false,
+ rootDir: REPO_ROOT,
+ libraryPattern,
+ stylexOverrides,
+ })
+ : astryxStylex({
+ stylexOptions: {
+ dev: false,
+ unstable_moduleResolution: {
+ type: 'commonJS',
+ rootDir: REPO_ROOT,
+ },
+ aliases: {
+ '@astryxdesign/core/*': [path.join(CORE_SRC, '*')],
+ '@astryxdesign/core': [CORE_SRC],
+ },
+ },
+ libraryPattern,
+ })),
],
});
} catch (error) {
@@ -338,6 +368,105 @@ describe('a production build separates Astryx and product styles by layer', () =
});
});
+// `defineConsts` values are compiled into the reading file as placeholders,
+// `var(--<prefix><hash>)`, and the defining file contributes the values; the
+// final CSS pass substitutes one for the other. Both halves must reach that
+// pass. Storybook builds through the legacy `{stylexOptions}` form, whose
+// StyleX instance ran without `treeshakeCompensation`: once `stylex.create`
+// was compiled, nothing used the import at runtime, the TypeScript transform
+// dropped it, and the defining module was never loaded. A media-query key was
+// left as `var(--x…){…}` and failed the build ("Invalid empty selector"); a
+// value shipped as a custom property nothing defines. And a constant defined
+// on one side of the layer split and read on the other was substituted only
+// within its own side, and one an Astryx package defines (compiled with the
+// library class-name prefix) never matched an app file's placeholder (written
+// with the product prefix).
+describe('a production build resolves defineConsts imported across files', () => {
+ /** A constant reference StyleX left unsubstituted. */
+ const PLACEHOLDER = /var\(--(?:astryx|x)[a-z0-9]{4,}\)/;
+
+ for (const zeroConfig of [false, true]) {
+ describe(
+ zeroConfig ? 'zero-config form' : 'legacy stylexOptions form (Storybook)',
+ () => {
+ let built: Built;
+ beforeAll(async () => {
+ built = await buildFixture('stylex-consts', ['index.html'], {
+ libraryPattern: '__fixtures__/stylex-consts/library/',
+ zeroConfig,
+ });
+ }, 180_000);
+ afterAll(
+ () => built && rmSync(built.outDir, {recursive: true, force: true}),
+ );
+
+ it('substitutes a constant read as a value', () => {
+ expect(built.css).toMatch(/min-height:\s*52px/);
+ });
+
+ it('substitutes a constant read as a media-query key', () => {
+ expect(built.css).toMatch(
+ /@media \((?:max-width: ?599px|width ?<= ?599px)\)\s*\{[^}]*transition-property:\s*none/,
+ );
+ });
+
+ it('substitutes a library-side constant read from the product side', () => {
+ expect(built.css).toMatch(/padding-top:\s*13px/);
+ expect(built.css).toMatch(
+ /@media \((?:min-width: ?900px|width ?>= ?900px)\)\s*\{[^}]*max-width:\s*640px/,
+ );
+ });
+
+ it('substitutes a constant an Astryx package defines under the library prefix', () => {
+ expect(built.css).toMatch(/padding-bottom:\s*17px/);
+ });
+
+ it('leaves no constant placeholder behind', () => {
+ expect(built.css).not.toMatch(PLACEHOLDER);
+ });
+ },
+ );
+ }
+});
+
+describe('a production build checks the custom properties its stylesheet reads', () => {
+ const MESSAGE =
+ /reads 1 generated custom property that no stylesheet in the build declares[\s\S]*--x[a-z0-9]+, read by: [^\n]*row-gap/;
+
+ it('warns, naming the variable and the rule that reads it', async () => {
+ const warnings: string[] = [];
+ const built = await buildFixture('stylex-undefined-var', ['index.html'], {
+ warnings,
+ });
+ rmSync(built.outDir, {recursive: true, force: true});
+ expect(warnings.join('\n')).toMatch(MESSAGE);
+ }, 180_000);
+
+ it('checks the product prefix a zero-config build sets in stylexOverrides', async () => {
+ const warnings: string[] = [];
+ const built = await buildFixture('stylex-undefined-var', ['index.html'], {
+ zeroConfig: true,
+ stylexOverrides: {classNamePrefix: 'app'},
+ warnings,
+ });
+ rmSync(built.outDir, {recursive: true, force: true});
+ expect(warnings.join('\n')).toMatch(
+ /reads 1 generated custom property that no stylesheet in the build declares[\s\S]*--app[a-z0-9]+, read by: [^\n]*row-gap/,
+ );
+ }, 180_000);
+
+ it("never reports an app's own custom properties, declared in its own CSS", async () => {
+ const warnings: string[] = [];
+ const built = await buildFixture('stylex-app-vars', ['index.html'], {
+ warnings,
+ });
+ rmSync(built.outDir, {recursive: true, force: true});
+ expect(warnings.join('\n')).not.toMatch(
+ /no stylesheet in the build declares/,
+ );
+ }, 180_000);
+});
+
describe('a production build validates StyleX declarations', () => {
it('fails with longhand guidance instead of dropping a border shorthand', async () => {
await expect(buildFixture('invalid-border')).rejects.toThrow(
diff --git a/packages/build/src/vite.test.ts b/packages/build/src/vite.test.ts
index 8f618832c8..2282e49900 100644
--- a/packages/build/src/vite.test.ts
+++ b/packages/build/src/vite.test.ts
@@ -14,6 +14,7 @@ import path from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
import stylex from '@stylexjs/unplugin';
import {astryxStylex, LIGHTNINGCSS_TARGETS} from './vite';
+import {undefinedGeneratedVariables} from './undefinedVariables';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -272,3 +273,57 @@ describe('astryxStylex optimizeDeps package discovery', () => {
}
});
});
+
+describe('undefinedGeneratedVariables', () => {
+ it('reports a generated variable that is read but never declared', () => {
+ expect(
+ undefinedGeneratedVariables(
+ '.a{min-height:var(--astryx1abc2)}.b{color:var(--x9zz9z, red)}',
+ ['astryx', 'x'],
+ ),
+ ).toEqual(['--astryx1abc2', '--x9zz9z']);
+ });
+
+ it('accepts a variable declared anywhere in the stylesheet', () => {
+ expect(
+ undefinedGeneratedVariables(
+ ':root{--astryx1abc2:4px}.a{padding:var(--astryx1abc2)}',
+ ['astryx', 'x'],
+ ),
+ ).toEqual([]);
+ });
+
+ it('ignores dynamic-style and component variables, which carry a dash', () => {
+ expect(
+ undefinedGeneratedVariables(
+ '.a{width:var(--x-width)}.b{padding:var(--astryx-card-padding,8px)}',
+ ['astryx', 'x'],
+ ),
+ ).toEqual([]);
+ });
+
+ it('counts a declaration in any other stylesheet the build emits', () => {
+ expect(
+ undefinedGeneratedVariables(
+ '.a{padding:var(--xlarge)}',
+ ['astryx', 'x'],
+ [':root{--xlarge:24px}'],
+ ),
+ ).toEqual([]);
+ });
+
+ it('reports only hash-shaped names: four to seven characters after the prefix', () => {
+ expect(
+ undefinedGeneratedVariables(
+ '.a{margin:var(--xl)}.b{gap:var(--xs1)}.c{inset:var(--x1abc2de)}.d{top:var(--x1abc2def)}',
+ ['astryx', 'x'],
+ ),
+ ).toEqual(['--x1abc2de']);
+ });
+
+ it('checks only the prefixes it is given', () => {
+ expect(
+ undefinedGeneratedVariables('.a{color:var(--x1abc2)}', ['astryx']),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.ts
index 0581b58675..0c17469b35 100644
--- a/packages/build/src/vite.ts
+++ b/packages/build/src/vite.ts
@@ -8,6 +8,7 @@ import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {createRequire} from 'node:module';
import {createHash} from 'node:crypto';
+import {undefinedGeneratedVariables} from './undefinedVariables';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -136,6 +137,12 @@ export function astryxStylex(
const libraryLayer = layers.library ?? 'astryx-base';
const productLayer = layers.product ?? 'product';
+ // Library files compile with `stylexPrefix`, product files with StyleX's
+ // `classNamePrefix` (the babel wrapper routes them).
+ const classNamePrefixes = [
+ stylexPrefix,
+ (stylexOverrides as {classNamePrefix?: string}).classNamePrefix ?? 'x',
+ ];
const overrideLightningcssOptions = (
stylexOverrides as {lightningcssOptions?: Record<string, unknown>}
@@ -284,6 +291,7 @@ export function astryxStylex(
libraryPattern,
libraryLayer,
productLayer,
+ classNamePrefixes,
}),
);
},
@@ -302,6 +310,7 @@ export function astryxStylex(
libraryLayer,
productLayer,
lightningcssOptions: stylexOptions.lightningcssOptions,
+ classNamePrefixes,
}),
];
}
@@ -330,24 +339,43 @@ function renderSplitLayers(
libraryPattern: string;
libraryLayer: string;
productLayer: string;
+ /** The StyleX class-name prefixes in play: library, then product. */
+ classNamePrefixes: readonly string[];
},
): string {
if (!rulesById || rulesById.size === 0) return '';
const libraryRules: unknown[] = [];
const productRules: unknown[] = [];
+ // `defineConsts` values. A file that reads a constant compiles it to a
+ // placeholder, `var(--<prefix><hash>)`, and `processStylexRules` substitutes
+ // the value from the defining file's rules, but only among the rules it is
+ // given. The defining file and the reading one can sit on opposite sides of
+ // the split, so every layer gets every constant, under every class-name
+ // prefix (see constantRulesForEveryPrefix). Constant rules emit no CSS of
+ // their own, so repeating them adds nothing to the output.
+ const collectedConstants: unknown[] = [];
for (const [filePath, rules] of rulesById.entries()) {
- if (filePath.includes(options.libraryPattern)) {
- libraryRules.push(...rules);
- } else {
- productRules.push(...rules);
+ const own = filePath.includes(options.libraryPattern)
+ ? libraryRules
+ : productRules;
+ for (const rule of rules) {
+ if (isConstantRule(rule)) {
+ collectedConstants.push(rule);
+ } else {
+ own.push(rule);
+ }
}
}
+ const constantRules = constantRulesForEveryPrefix(
+ collectedConstants,
+ options.classNamePrefixes,
+ );
const render = (rules: unknown[], layer: string) =>
rules.length
- ? `@layer ${layer} {\n${stylexBabelPlugin.processStylexRules(rules as never, {useLayers: true})}\n}`
+ ? `@layer ${layer} {\n${stylexBabelPlugin.processStylexRules([...constantRules, ...rules] as never, {useLayers: true})}\n}`
: '';
return [
@@ -358,6 +386,56 @@ function renderSplitLayers(
.join('\n\n');
}
+/**
+ * Each `defineConsts` rule once under every class-name prefix in play.
+ *
+ * StyleX keys a constant by its defining file's prefix, `<prefix><hash>` (or
+ * `<name>-<prefix><hash>` with debug class names), where the hash depends on
+ * the export and key alone, and a file that reads it writes the placeholder
+ * with its own prefix. An Astryx package compiles with the library prefix and
+ * an app with the product one, so an app reading a package's constant writes
+ * `var(--x<hash>)` while the package's rule is keyed `astryx<hash>`; the
+ * copies make every prefix's placeholder resolve. A key StyleX took verbatim
+ * (`'--name'`) carries no prefix and is kept as it is.
+ */
+function constantRulesForEveryPrefix(
+ rules: readonly unknown[],
+ prefixes: readonly string[],
+): unknown[] {
+ const ordered = [...new Set(prefixes)]
+ .filter(Boolean)
+ .sort((a, b) => b.length - a.length);
+ const out: unknown[] = [];
+ const keys = new Set<string>();
+ const add = (rule: unknown[], key: string) => {
+ if (keys.has(key)) return;
+ keys.add(key);
+ const [, body, ...rest] = rule;
+ out.push([key, {...(body as object), constKey: key}, ...rest]);
+ };
+ for (const rule of rules as unknown[][]) {
+ const key = String((rule[1] as {constKey: unknown}).constKey);
+ add(rule, key);
+ for (const prefix of ordered) {
+ const match = new RegExp(`^(|.*-)${prefix}([0-9a-z]+)$`).exec(key);
+ if (match == null) continue;
+ for (const other of ordered) {
+ add(rule, `${match[1]}${other}${match[2]}`);
+ }
+ break;
+ }
+ }
+ return out;
+}
+
+/** A `defineConsts` value as StyleX collects it: a rule with `constKey`/`constVal`. */
+function isConstantRule(rule: unknown): boolean {
+ const body = Array.isArray(rule)
+ ? (rule[1] as {constKey?: unknown; constVal?: unknown} | undefined)
+ : undefined;
+ return body?.constKey != null && body?.constVal != null;
+}
+
/**
* The build half of the split. StyleX appends one merged block of CSS to the
* build's stylesheet, in its own top-level `@layer priority1…priorityN` — which
@@ -387,6 +465,8 @@ function buildLayerSplitPlugin(
libraryLayer: string;
productLayer: string;
lightningcssOptions?: unknown;
+ /** The StyleX class-name prefixes in play: library, then product. */
+ classNamePrefixes: readonly string[];
},
): Plugin {
const stylex = basePlugin as {
@@ -402,7 +482,7 @@ function buildLayerSplitPlugin(
configResolved(config) {
base = config.base ?? '/';
},
- writeBundle(outputOptions) {
+ writeBundle(outputOptions, bundle) {
const rulesById = stylex.__stylexGetSharedStore?.().rulesById;
if (!rulesById || rulesById.size === 0) return;
@@ -414,6 +494,42 @@ function buildLayerSplitPlugin(
options.lightningcssOptions,
);
+ // An app's own stylesheets declare its own custom properties.
+ const emittedCss = Object.values(bundle)
+ .filter(
+ (output): output is Extract<typeof output, {type: 'asset'}> =>
+ output.type === 'asset' && output.fileName.endsWith('.css'),
+ )
+ .map(asset =>
+ typeof asset.source === 'string'
+ ? asset.source
+ : Buffer.from(asset.source).toString('utf8'),
+ );
+ const undeclared = undefinedGeneratedVariables(
+ split,
+ options.classNamePrefixes,
+ emittedCss,
+ );
+ if (undeclared.length > 0) {
+ this.warn(
+ 'astryx-build-layer-split: the StyleX stylesheet reads ' +
+ `${undeclared.length} generated custom ` +
+ `propert${undeclared.length === 1 ? 'y' : 'ies'} ` +
+ 'that no stylesheet in the build declares:\n' +
+ undeclared
+ .map(
+ name =>
+ ` ${name}, read by: ${rulesReading(split, name).join(' ') || '(rule not found)'}`,
+ )
+ .join('\n') +
+ '\nWith no declaration, browsers drop the declarations that read ' +
+ 'it. A `.stylex.ts` export read in a style must be a ' +
+ '`defineVars`/`defineConsts` value whose module reaches the build; ' +
+ 'a property the app sets at runtime (an inline style) needs a name ' +
+ 'outside the StyleX class-name prefixes.',
+ );
+ }
+
const outDir = outputOptions.dir
? outputOptions.dir
: outputOptions.file
@@ -472,6 +588,14 @@ function buildLayerSplitPlugin(
};
}
+/** The rules of `css` that read `name`, for the failure message. */
+function rulesReading(css: string, name: string): string[] {
+ return [...css.matchAll(/[^{}]+\{[^{}]*\}/g)]
+ .map(match => match[0].trim().replace(/\s+/g, ' '))
+ .filter(rule => rule.includes(`var(${name}`))
+ .slice(0, 3);
+}
+
/** Every `.css` file under a directory, recursively. */
function listCssFiles(dir: string): string[] {
const out: string[] = [];
@@ -586,12 +710,25 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
).lightningcssOptions;
const validatedStylexOptions = {
propertyValidationMode: 'throw',
+ // The unplugin applies its Vite default (true) only to its own StyleX
+ // instance, which runs after the babel wrapper below has already compiled
+ // every StyleX call. Without it here, a file that reads only `defineConsts`
+ // from a `.stylex.ts` module loses that import once `stylex.create` is
+ // compiled (the TypeScript transform drops it as unused), the module is
+ // never loaded, and its constants never reach the CSS: a media-query key
+ // fails the build and a value ships as an undefined custom property.
+ treeshakeCompensation: true,
...(stylexOptions as any),
lightningcssOptions: {
targets: LIGHTNINGCSS_TARGETS,
...legacyLightningcssOptions,
},
};
+ const classNamePrefixes = [
+ stylexPrefix,
+ (validatedStylexOptions as {classNamePrefix?: string}).classNamePrefix ??
+ 'x',
+ ];
const astryxBabelPlugin = path.resolve(__dirname, 'babel.js');
const existingPlugins = validatedStylexOptions.babelConfig?.plugins ?? [];
@@ -658,6 +795,7 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
libraryPattern,
libraryLayer,
productLayer,
+ classNamePrefixes,
}),
);
},
@@ -677,6 +815,7 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
lightningcssOptions: (
validatedStylexOptions as {lightningcssOptions?: unknown}
).lightningcssOptions,
+ classNamePrefixes,
}),
];
}
diff --git a/scripts/build-css.graph.test.mjs b/scripts/build-css.graph.test.mjs
index f01899ceec..4ae90bfaa9 100644
--- a/scripts/build-css.graph.test.mjs
+++ b/scripts/build-css.graph.test.mjs
@@ -296,10 +296,11 @@ export const styles = stylex.create({
});
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([]);
+ // A hash-shaped name: StyleX's hash is four to seven base-36 characters.
+ const satellite = '.xabc{color:var(--x1prov7)}';
+ expect(undefinedStyleXVariables(satellite)).toEqual(['--x1prov7']);
+ expect(undefinedStyleXVariables(satellite, ':root{--x1prov7:red}')).toEqual(
+ [],
+ );
});
});
diff --git a/scripts/build-css.mjs b/scripts/build-css.mjs
index 6be7c276f0..6ce7d25b5b 100644
--- a/scripts/build-css.mjs
+++ b/scripts/build-css.mjs
@@ -376,16 +376,22 @@ export function composePackageStylesheet(banner, css) {
* 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.
+ * are not generated names and are never reported, nor is a name that is not
+ * hash-shaped (StyleX's hash is four to seven base-36 characters).
+ *
+ * SYNC: packages/build/src/undefinedVariables.ts is the same check for an
+ * app's production build.
*/
export function undefinedStyleXVariables(css, providerCss = '') {
const declared = new Set(
- [...`${css}\n${providerCss}`.matchAll(/(--x[a-z0-9]+)\s*:/g)].map(
+ [...`${css}\n${providerCss}`.matchAll(/(--[A-Za-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]),
+ [...css.matchAll(/var\(\s*(--x[a-z0-9]{4,7})\s*[,)]/g)].map(
+ match => match[1],
+ ),
);
return [...read].filter(name => !declared.has(name)).sort();
}