An open source design system that's fully customizable and agent ready
TypeScript
fix(build): split Astryx and product styles into their cascade layers in a production build (#5410)
Cindy Zhangc47e75495d5c
diff --git a/.changeset/theme-overrides-lost-in-vite-build.md b/.changeset/theme-overrides-lost-in-vite-build.mdnew file mode 100644index 0000000000..d52d16e7b9--- /dev/null+++ b/.changeset/theme-overrides-lost-in-vite-build.md@@ -0,0 +1,18 @@+---+'@astryxdesign/build': patch+---++[fix] Vite build: Astryx and product styles are split into their own cascade layers, so a theme's component overrides apply in a production build+@cixzhang++StyleX emits every rule it collects into one top-level `@layer+priority1…priorityN`. The dev server re-served those partitioned by source file+— Astryx's own styles into `astryx-base`, the app's into `product` — but a build+did neither, so the priority layers landed outside the `@layer reset,+astryx-base, astryx-theme, product` order and outranked all of it. Every+`components: {…}` override a theme set — a colour, a radius, a public custom+property — was silently dropped in the built app while working in dev.++The build now runs the same partition the dev server does, from the same helper,+so the promised order holds in both: Astryx's styles are overridable by a theme,+and an app's own styles still outrank everything.diff --git a/.github/scripts/theme-layer-cascade.js b/.github/scripts/theme-layer-cascade.jsnew file mode 100644index 0000000000..4a94a77d35--- /dev/null+++ b/.github/scripts/theme-layer-cascade.js@@ -0,0 +1,197 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @description Asserts a production build puts Astryx, theme and product styles in the right cascade order+ * @input [--port <n>]+ * @output One line per case; exit 1 if any layer loses to the wrong one+ *+ * `packages/build/src/vite.build.test.ts` reads the built stylesheet and proves+ * each rule landed in the layer it belongs to. It cannot prove what that means:+ * which declaration actually paints is a cascade fact, and jsdom resolves no+ * cascade. This builds the same fixture and looks.+ *+ * Three origins compete on one element, and the order between them is the whole+ * contract:+ *+ * Astryx's own rule @layer astryx-base loses to both+ * a theme override @layer astryx-theme beats Astryx, loses to the app+ * the app's StyleX @layer product beats both+ *+ * The middle row is what shipped broken — the build never split, so everything+ * StyleX emitted outranked `astryx-theme`. The fix for that then inverted the+ * bottom row for a while: wrapping instead of splitting put the app's own+ * styles in `astryx-base`, where a theme could silently restyle them. Both+ * failures are one assertion apart, which is why this checks both directions.+ */++const {chromium} = require('playwright');+const fs = require('node:fs');+const path = require('node:path');+const http = require('node:http');+const os = require('node:os');+const {pathToFileURL} = require('node:url');++const args = process.argv.slice(2);+const getArg = name => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};++const port = Number(getArg('port') || 6012);+const REPO_ROOT = process.cwd();+const FIXTURE = path.join(REPO_ROOT, 'packages/build/__fixtures__/layer-split');+const CORE_SRC = path.join(REPO_ROOT, 'packages/core/src');++/** Kept in step with the fixture; a mismatch here reads as a cascade failure. */+const THEME_COLOR = 'rgb(0, 120, 255)';+const PRODUCT_COLOR = 'rgb(255, 140, 0)';++const CONTENT_TYPES = {+ '.html': 'text/html',+ '.js': 'application/javascript',+ '.mjs': 'application/javascript',+ '.css': 'text/css',+ '.svg': 'image/svg+xml',+};++function createServer(dir, listenPort) {+ return new Promise(resolve => {+ const server = http.createServer((req, res) => {+ const rel = (req.url === '/' ? '/index.html' : req.url).split('?')[0];+ const resolved = path.resolve(path.join(dir, rel));+ if (!resolved.startsWith(path.resolve(dir))) {+ res.writeHead(403);+ res.end('Forbidden');+ return;+ }+ fs.readFile(resolved, (err, data) => {+ if (err) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.writeHead(200, {+ 'Content-Type': CONTENT_TYPES[path.extname(resolved)] || 'text/plain',+ });+ res.end(data);+ });+ });+ server.listen(listenPort, () => resolve(server));+ });+}++async function buildFixture(outDir) {+ const {build} = await import('vite');+ const react = (await import('@vitejs/plugin-react')).default;++ // .github/scripts is outside the workspace, so a bare specifier does not+ // resolve here. The Vite plugin ships as a build artifact.+ const pluginPath = path.join(REPO_ROOT, 'packages/build/dist/vite.mjs');+ if (!fs.existsSync(pluginPath)) {+ throw new Error(+ `${pluginPath} is missing — run \`pnpm -F @astryxdesign/build build\` first.`,+ );+ }+ const {astryxStylex} = await import(pathToFileURL(pluginPath).href);+ await build({+ root: FIXTURE,+ logLevel: 'error',+ build: {outDir, emptyOutDir: true},+ 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/',+ }),+ ],+ });+}++async function run() {+ const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cascade-'));+ let server;+ let browser;+ const failures = [];++ try {+ await buildFixture(outDir);+ server = await createServer(outDir, port);+ browser = await chromium.launch();+ const page = await browser.newPage({viewport: {width: 420, height: 220}});+ await page.goto(`http://localhost:${port}/`, {+ waitUntil: 'networkidle',+ timeout: 60000,+ });+ await page.waitForSelector('#library-only', {timeout: 20000});++ const seen = await page.evaluate(() => ({+ themed: getComputedStyle(document.getElementById('library-only'))+ .backgroundColor,+ product: getComputedStyle(document.getElementById('product-wins'))+ .backgroundColor,+ padding: getComputedStyle(document.getElementById('product-box')).padding,+ }));++ const check = (label, actual, expected, why) => {+ if (actual === expected) {+ console.log(`✓ ${label} — ${actual}`);+ } else {+ failures.push(label);+ console.error(+ `✗ ${label}: got ${actual}, expected ${expected} — ${why}`,+ );+ }+ };++ check(+ "a theme's component override beats Astryx's own rule",+ seen.themed,+ THEME_COLOR,+ 'StyleX is outranking @layer astryx-theme, so no theme can restyle a component',+ );+ check(+ "the app's own StyleX beats the theme",+ seen.product,+ PRODUCT_COLOR,+ 'product styles landed in the library layer, so a theme silently restyles app code',+ );+ check(+ "the app's own StyleX applies at all",+ seen.padding,+ '11px',+ 'the product layer is not reaching the page',+ );+ } finally {+ if (browser) await browser.close();+ if (server) server.close();+ fs.rmSync(outDir, {recursive: true, force: true});+ }++ if (failures.length > 0) {+ console.error(+ `\nFailing: ${failures.length} cascade rule(s) broken in a production ` ++ `build — ${failures.join('; ')}.`,+ );+ return 1;+ }+ console.log('\nAstryx < theme < product holds in a production build.');+ return 0;+}++run()+ .then(code => {+ process.exitCode = code;+ })+ .catch(e => {+ console.error('Theme layer cascade guard failed:', e);+ process.exit(1);+ });diff --git a/.github/scripts/theme-var-reachability.js b/.github/scripts/theme-var-reachability.jsnew file mode 100644index 0000000000..0da2648bfc--- /dev/null+++ b/.github/scripts/theme-var-reachability.js@@ -0,0 +1,279 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.+++/**+ * @description Asserts every documented public component var is settable from a theme+ * @input --storybook-dir <path> [--port <n>]+ * @output One line per var; exit 1 if any var cannot be reached from @layer astryx-theme+ *+ * A public var is a promise: set it on the component's theme target and the+ * component changes. Nothing in the unit suite can check that promise. jsdom+ * resolves no cascade, so the TreeList and Spinner theme tests assert on the+ * generated CSS text instead — which says the declaration was emitted, not that+ * it wins. A var can be documented, read, and emitted and still be beaten to+ * the element by a rule the theme cannot outrank.+ *+ * So this reproduces what a themer does. `Theme` injects component overrides as+ * `@layer astryx-theme { <selector> { … } }` (packages/core/src/theme/Theme.tsx),+ * and that is the exact shape written here, against the documented target class+ * — not against the element, which would prove a cascade a theme has no+ * selector for. Three ways to fail, all of them shipped at least once:+ *+ * 1. nothing declares the var — no component reads it (#5012)+ * 2. the declaring element carries no documented target class+ * — a theme has nothing to select+ * 3. the theme rule loses — an inline write or an unlayered+ * declaration outranks it (#4530)+ *+ * What it does NOT prove is the pixel: it stops at the value arriving on the+ * element. What the component then paints with it is that component's own test.+ */++const {chromium} = require('playwright');+const fs = require('node:fs');+const path = require('node:path');+const http = require('node:http');+const {pathToFileURL} = require('node:url');++const args = process.argv.slice(2);+const getArg = name => {+ const idx = args.indexOf(`--${name}`);+ return idx !== -1 ? args[idx + 1] : null;+};++const storybookDir = getArg('storybook-dir') || 'apps/storybook/dist';+const port = Number(getArg('port') || 6011);++/** Distinctive enough that a coincidental match is not a concern. */+const SENTINEL = '9987px';++/**+ * Stories tried per component before the var is reported unrenderable. A var+ * only some states declare (`--button-icon-only-aspect` needs `isIconOnly`)+ * is not reachable from the first story, so the sweep runs until one declares+ * it — the common case still exits on the first. The cap only bounds a+ * component with an unusually long story list.+ */+const STORY_BUDGET = 30;++const CONTENT_TYPES = {+ '.html': 'text/html',+ '.js': 'application/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.png': 'image/png',+ '.svg': 'image/svg+xml',+};++function createServer(dir, listenPort) {+ return new Promise(resolve => {+ const server = http.createServer((req, res) => {+ const filePath = path+ .join(dir, req.url === '/' ? 'index.html' : req.url)+ .split('?')[0];++ const resolved = path.resolve(filePath);+ if (!resolved.startsWith(path.resolve(dir))) {+ res.writeHead(403);+ res.end('Forbidden');+ return;+ }++ fs.readFile(resolved, (err, data) => {+ if (err) {+ res.writeHead(404);+ res.end('Not found');+ return;+ }+ res.writeHead(200, {+ 'Content-Type': CONTENT_TYPES[path.extname(resolved)] || 'text/plain',+ });+ res.end(data);+ });+ });++ server.listen(listenPort, () => resolve(server));+ });+}++/**+ * The public vars and the target classes their component documents, read from+ * the same enumeration `theme targets` and `theme build` read — so a var added+ * to a doc is guarded here without anyone remembering to add it.+ */+async function documentedVars(repoRoot) {+ const discovery = path.join(+ repoRoot,+ 'packages/cli/foundation/discovery/theming-targets.mjs',+ );+ const {collectThemingVars, collectThemingTargets} = await import(+ pathToFileURL(discovery).href+ );+ const coreSrc = path.join(repoRoot, 'packages/core/src');+ const [vars, targets] = await Promise.all([+ collectThemingVars(coreSrc),+ collectThemingTargets(coreSrc),+ ]);+ return vars.map(v => ({+ ...v,+ classNames: targets+ .filter(t => t.component === v.component)+ .map(t => t.className),+ }));+}++/** Story ids for a component, in declaration order. */+function storiesFor(index, component) {+ return Object.values(index.entries || {})+ .filter(e => e.type === 'story' && e.title.split('/').pop() === component)+ .map(e => e.id);+}++/**+ * In the page: find the element that declares `name`, check it carries one of+ * the component's documented target classes, then override through that class+ * from `@layer astryx-theme` and read the value back.+ */+function reachInPage([name, classNames, sentinel]) {+ const declaring = [...document.querySelectorAll('*')].find(el => {+ if (!getComputedStyle(el).getPropertyValue(name).trim()) return false;+ const parent = el.parentElement;+ return (+ !parent || !getComputedStyle(parent).getPropertyValue(name).trim()+ );+ });+ if (!declaring) return {status: 'undeclared'};++ const target = classNames.find(c => declaring.classList.contains(c));+ if (!target) {+ return {+ status: 'unselectable',+ classes: [...declaring.classList].filter(c => c.startsWith('astryx-')),+ };+ }++ const before = getComputedStyle(declaring).getPropertyValue(name).trim();+ const style = document.createElement('style');+ style.textContent = `@layer astryx-theme { .${target} { ${name}: ${sentinel}; } }`;+ document.head.appendChild(style);+ const after = getComputedStyle(declaring).getPropertyValue(name).trim();+ style.remove();++ return {+ status: after === sentinel ? 'reaches' : 'inert',+ target,+ before,+ after,+ };+}++async function probe(context, entry, index) {+ const ids = storiesFor(index, entry.component).slice(0, STORY_BUDGET);+ if (ids.length === 0) {+ return {status: 'nostory'};+ }+ let last = {status: 'undeclared'};+ for (const id of ids) {+ const page = await context.newPage();+ try {+ await page.goto(+ `http://localhost:${port}/iframe.html?id=${id}&viewMode=story`,+ {waitUntil: 'networkidle', timeout: 30000},+ );+ const result = await page.evaluate(reachInPage, [+ entry.name,+ entry.classNames,+ SENTINEL,+ ]);+ if (result.status !== 'undeclared') return {...result, story: id};+ last = {...result, story: id};+ } finally {+ await page.close();+ }+ }+ return last;+}++async function run() {+ const repoRoot = process.cwd();+ const dir = path.resolve(repoRoot, storybookDir);+ if (!fs.existsSync(dir)) {+ console.error(`Storybook build not found at ${dir}`);+ return 1;+ }+ const indexPath = path.join(dir, 'index.json');+ if (!fs.existsSync(indexPath)) {+ console.error(`Storybook index not found at ${indexPath}`);+ return 1;+ }+ const index = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));++ const entries = await documentedVars(repoRoot);+ if (entries.length === 0) {+ console.error(+ 'No public component vars were enumerated. The docs cannot have lost ' ++ 'all of them at once — the enumeration is broken.',+ );+ return 1;+ }++ const server = await createServer(dir, port);+ const browser = await chromium.launch();+ const failures = [];++ try {+ const context = await browser.newContext({+ viewport: {width: 900, height: 700},+ });++ for (const entry of entries) {+ const r = await probe(context, entry, index);+ const where = `${entry.component} ${entry.name}`;+ if (r.status === 'reaches') {+ console.log(`✓ ${where} — .${r.target} sets it (${r.before} → ${r.after})`);+ continue;+ }+ failures.push(where);+ if (r.status === 'nostory') {+ console.error(`✗ ${where}: no story renders ${entry.component}`);+ } else if (r.status === 'undeclared') {+ console.error(+ `✗ ${where}: nothing declares it — no element in any ${entry.component} story has a value (#5012)`,+ );+ } else if (r.status === 'unselectable') {+ console.error(+ `✗ ${where}: declared on an element carrying no documented target class ` ++ `(has ${r.classes.join(', ') || 'none'}) — a theme has no selector for it`,+ );+ } else {+ console.error(+ `✗ ${where}: .${r.target} in @layer astryx-theme did not win — stayed ${r.after} (#4530)`,+ );+ }+ }+ } finally {+ await browser.close();+ server.close();+ }++ if (failures.length > 0) {+ console.error(+ `\nFailing: ${failures.length} documented public var(s) a theme cannot set — ` ++ `${failures.join(', ')}. A var an author reads about and cannot use is ` ++ `worse than no var.`,+ );+ return 1;+ }+ console.log(`\nAll ${entries.length} public component vars are settable from a theme.`);+ return 0;+}++run()+ .then(code => {+ process.exitCode = code;+ })+ .catch(e => {+ console.error('Theme var reachability guard failed:', e);+ process.exit(1);+ });diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 01a892c80b..78b4af1f44 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -9,17 +9,16 @@ name: CIon:pull_request:- branches: ["main"]+ branches: ['main']merge_group:permissions: {}concurrency:- group: "ci-${{ github.event.merge_group.head_sha || github.head_ref }}"+ group: 'ci-${{ github.event.merge_group.head_sha || github.head_ref }}'cancel-in-progress: truejobs:-# Detect docsite-only changes — lets docsite PRs skip heavy jobscheck-scope:if: github.event_name == 'pull_request'@@ -463,6 +462,48 @@ jobs:- name: Run modal close visibility guardrun: node .github/scripts/modal-close-visibility.js --storybook-dir apps/storybook/dist+ # A public component var can be documented, read, and emitted into the+ # theme CSS and still be unreachable — an inline write or an unlayered+ # declaration outranks `@layer astryx-theme` (#4530). jsdom resolves no+ # cascade, so the unit suites assert on the generated CSS text, which+ # proves emission and not effect. Chromium is where the promise is+ # checkable. The source-side wiring half lives in+ # packages/cli/foundation/discovery/theming-targets.test.mjs.+ - name: Run theme var reachability guard+ run: node .github/scripts/theme-var-reachability.js --storybook-dir apps/storybook/dist++ # The layer order Astryx promises is Astryx < theme < product, and which+ # declaration paints is a cascade fact no jsdom test can settle: the build has+ # been wrong in both directions inside one week — unsplit, so StyleX outranked+ # every theme, then wrapped instead of split, so an app's own styles lost to+ # one. vite.build.test.ts reads the built stylesheet; this renders it.+ #+ # Its own job on purpose. pr-a11y, where the sibling Chromium guards live,+ # runs only when packages/core or packages/lab changed, and what this guards+ # is packages/build — so hosting it there would skip it on exactly the PRs+ # that can break it. Gated like `test` instead: everything but docsite-only.+ theme-layers:+ needs: [check-scope]+ if: needs.check-scope.outputs.docsite_only != 'true'+ runs-on: 2-core-ubuntu-arm+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v7++ - uses: ./.github/actions/setup++ - name: Install Playwright+ run: npx playwright install chromium++ # The guard imports the plugin's build artifact, the same one a consumer+ # installs.+ - name: Build the Vite plugin+ run: pnpm -F @astryxdesign/build build++ - name: Run theme layer cascade guard+ run: node .github/scripts/theme-layer-cascade.js+# RTL semantic audit. Sibling to pr-a11y: same build-storybook artifact, same# analysis.json scoping, so a PR only pays for the components it touched.# Unscoped this swept ~1400 stories and took ~26 min. The full sweep thatdiff --git a/package.json b/package.jsonindex a544d4f03d..150791f245 100644--- a/package.json+++ b/package.json@@ -25,14 +25,16 @@"lint": "pnpm check:repo && eslint . --cache","lint:strict": "pnpm check:repo && ASTRYX_STRICT_LINT=1 eslint . --cache","visual:plan": "node .github/scripts/visual-gate/gate.mjs plan",- "visual:check": "node .github/scripts/visual-gate/gate.mjs check",- "visual:flaky": "node .github/scripts/visual-gate/gate.mjs flaky",- "a11y:audit": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --fail-on-new",+ "visual:check": "node .github/scripts/visual-gate/gate.mjs check",+ "visual:flaky": "node .github/scripts/visual-gate/gate.mjs flaky",+ "a11y:audit": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --fail-on-new","a11y:baseline": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --update-baseline","rtl:audit": "node apps/storybook/rtl-audit/rtl-audit.mjs","lab:readiness": "node internal/lab-readiness/audit.mjs","lab:readiness:check": "node internal/lab-readiness/audit.mjs --check","guard:modal-close": "node .github/scripts/modal-close-visibility.js",+ "guard:theme-vars": "node .github/scripts/theme-var-reachability.js",+ "guard:theme-layers": "node .github/scripts/theme-layer-cascade.js","guard:disabled-hover": "node .github/scripts/disabled-hover-audit.js","guard:disabled-cursor": "node .github/scripts/disabled-cursor-audit.js","storybook": "pnpm -F @astryxdesign/storybook dev",diff --git a/packages/build/__fixtures__/layer-split-nocss/index.html b/packages/build/__fixtures__/layer-split-nocss/index.htmlnew file mode 100644index 0000000000..2d5676d090--- /dev/null+++ b/packages/build/__fixtures__/layer-split-nocss/index.html@@ -0,0 +1,12 @@+<!doctype html>+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title>layer-split fixture — no stylesheet of its own</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./main.tsx"></script>+ </body>+</html>diff --git a/packages/build/__fixtures__/layer-split-nocss/main.tsx b/packages/build/__fixtures__/layer-split-nocss/main.tsxnew file mode 100644index 0000000000..5473e598f1--- /dev/null+++ b/packages/build/__fixtures__/layer-split-nocss/main.tsx@@ -0,0 +1,19 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * The same app as the `layer-split` fixture, importing NO stylesheet of its+ * own. That is the whole point of it: with no CSS asset in the bundle, StyleX+ * writes its own file outside Rollup's graph, and both the split and the+ * `<link>` have to be handled by us.+ */++import {createRoot} from 'react-dom/client';+import {Theme} from '@astryxdesign/core/theme';+import {App} from '../layer-split/App';+import {fixtureTheme} from '../layer-split/theme';++createRoot(document.getElementById('root')!).render(+ <Theme theme={fixtureTheme} mode="light">+ <App />+ </Theme>,+);diff --git a/packages/build/__fixtures__/layer-split/App.tsx b/packages/build/__fixtures__/layer-split/App.tsxnew file mode 100644index 0000000000..1cf5eba474--- /dev/null+++ b/packages/build/__fixtures__/layer-split/App.tsx@@ -0,0 +1,38 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Product code, for the layer-split build fixture. It uses an Astryx component+ * AND authors its own StyleX in the same tree, which is the case the split+ * exists for: the two must not land in the same cascade layer.+ *+ * `themedButton` deliberately sets the same property the fixture theme+ * overrides on the same element, so the built stylesheet answers which layer+ * wins rather than only which rules were emitted.+ */++import * as stylex from '@stylexjs/stylex';+import {Button} from '@astryxdesign/core/Button';++const styles = stylex.create({+ productBox: {+ backgroundColor: 'rgb(238, 238, 238)',+ padding: '11px',+ },+ themedButton: {+ backgroundColor: 'rgb(255, 140, 0)',+ },+});++export function App() {+ return (+ <div id="product-box" {...stylex.props(styles.productBox)}>+ <Button id="library-only" label="Delete" variant="destructive" />+ <Button+ id="product-wins"+ label="Delete"+ variant="destructive"+ xstyle={styles.themedButton}+ />+ </div>+ );+}diff --git a/packages/build/__fixtures__/layer-split/index.css b/packages/build/__fixtures__/layer-split/index.cssnew file mode 100644index 0000000000..b7398f4f36--- /dev/null+++ b/packages/build/__fixtures__/layer-split/index.css@@ -0,0 +1,8 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++/* A real app imports CSS, which is what gives the build a stylesheet asset for+ StyleX to append to. Without one StyleX writes its own file that nothing+ links, and the page loads no styles at all. */+#root {+ margin: 0;+}diff --git a/packages/build/__fixtures__/layer-split/index.html b/packages/build/__fixtures__/layer-split/index.htmlnew file mode 100644index 0000000000..4c783a4cd0--- /dev/null+++ b/packages/build/__fixtures__/layer-split/index.html@@ -0,0 +1,12 @@+<!doctype html>+<!-- Copyright (c) Meta Platforms, Inc. and affiliates. -->+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title>layer-split fixture</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./main.tsx"></script>+ </body>+</html>diff --git a/packages/build/__fixtures__/layer-split/main.tsx b/packages/build/__fixtures__/layer-split/main.tsxnew file mode 100644index 0000000000..161757bcdb--- /dev/null+++ b/packages/build/__fixtures__/layer-split/main.tsx@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {createRoot} from 'react-dom/client';+import './index.css';+import {Theme} from '@astryxdesign/core/theme';+import {App} from './App';+import {fixtureTheme} from './theme';++createRoot(document.getElementById('root')!).render(+ <Theme theme={fixtureTheme} mode="light">+ <App />+ </Theme>,+);diff --git a/packages/build/__fixtures__/layer-split/theme.ts b/packages/build/__fixtures__/layer-split/theme.tsnew file mode 100644index 0000000000..6c007e34f6--- /dev/null+++ b/packages/build/__fixtures__/layer-split/theme.ts@@ -0,0 +1,17 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {defineTheme} from '@astryxdesign/core/theme';++/**+ * Overrides the same declaration Button's own StyleX rule sets, so the built+ * stylesheet answers "does @layer astryx-theme outrank the library layer?"+ * rather than only "did the rule get emitted?".+ */+export const fixtureTheme = defineTheme({+ name: 'layersplitfixture',+ components: {+ button: {+ 'variant:destructive': {backgroundColor: 'rgb(0, 120, 255)'},+ },+ },+});diff --git a/packages/build/src/vite.build.test.ts b/packages/build/src/vite.build.test.tsnew file mode 100644index 0000000000..887b1cfd4e--- /dev/null+++ b/packages/build/src/vite.build.test.ts@@ -0,0 +1,179 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Runs REAL Vite production builds of fixture apps and asserts on the+ * stylesheets they emit.+ *+ * The unit tests in vite.test.ts check the plugin's wiring, and they passed+ * while the build shipped a version that wrapped every StyleX rule — Astryx's+ * and the app's alike — in the library layer. That inverts the bug rather than+ * fixing it: product styles are supposed to outrank a theme, and wrapped in+ * `astryx-base` they lose to one. Only the built artifact shows it, so this+ * builds one.+ *+ * Two shapes, because StyleX emits through two different paths:+ *+ * `layer-split` the app imports a stylesheet, so the bundle has a CSS+ * asset and StyleX appends to it in `generateBundle`+ * `layer-split-nocss` the app imports none, so StyleX writes its own file in+ * `writeBundle`, outside Rollup's graph+ *+ * The second is the one that was missing, and it hid two defects: the split did+ * not run there at all, and the file StyleX writes is not linked by any page.+ *+ * What none of this can prove is which declaration actually paints — that is a+ * cascade fact, and it lives in .github/scripts/theme-layer-cascade.js.+ */++import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import {build} from 'vite';+import react from '@vitejs/plugin-react';+import {mkdtempSync, readdirSync, readFileSync, rmSync} from 'node:fs';+import {tmpdir} from 'node:os';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {astryxStylex} from './vite';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(__dirname, '../../..');+const FIXTURES = path.resolve(__dirname, '../__fixtures__');+const CORE_SRC = path.join(REPO_ROOT, 'packages/core/src');++/** The class prefixes @astryxdesign/build/babel assigns per origin. */+const LIBRARY_CLASS = /\.astryx[a-z0-9]{5,}/g;+const PRODUCT_CLASS = /\.x[a-z0-9]{5,}/g;++type Built = {css: string; cssName: string; html: string; outDir: string};++async function buildFixture(name: string): Promise<Built> {+ const root = path.join(FIXTURES, name);+ const outDir = mkdtempSync(path.join(tmpdir(), `astryx-${name}-`));+ await build({+ root,+ logLevel: 'error',+ build: {outDir, emptyOutDir: true},+ 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/',+ }),+ ],+ });++ const assets = path.join(outDir, 'assets');+ const cssName = readdirSync(assets).find(f => f.endsWith('.css'));+ if (!cssName) throw new Error(`no stylesheet emitted into ${assets}`);+ return {+ css: readFileSync(path.join(assets, cssName), 'utf-8'),+ cssName,+ html: readFileSync(path.join(outDir, 'index.html'), 'utf-8'),+ outDir,+ };+}++/** The slice of a stylesheet inside a given top-level layer block. */+function layerBlock(css: string, name: string): string {+ const start = css.indexOf(`@layer ${name} {`);+ expect(+ start,+ `@layer ${name} is not in the emitted stylesheet`,+ ).toBeGreaterThan(-1);+ let depth = 0;+ for (let i = css.indexOf('{', start); i < css.length; i++) {+ if (css[i] === '{') depth++;+ else if (css[i] === '}' && --depth === 0) return css.slice(start, i + 1);+ }+ throw new Error(`@layer ${name} is unterminated`);+}++/** Both shapes must satisfy the same contract, so both run the same checks. */+function itSplitsCorrectly(get: () => Built) {+ it('declares the layer order the split depends on', () => {+ expect(get().html).toContain(+ '@layer reset, astryx-base, astryx-theme, product;',+ );+ });++ it("puts Astryx's own rules in the library layer", () => {+ const library = layerBlock(get().css, 'astryx-base');+ expect(library.match(LIBRARY_CLASS)?.length ?? 0).toBeGreaterThan(50);+ // The fixture's Button pulls in real component CSS, so a token it styles+ // with is a fact about this block rather than about class-name shape.+ expect(library).toContain('--radius-element');+ });++ // The regression this file exists for. The wrapped-not-split version put the+ // app's own StyleX in astryx-base, below `astryx-theme`, so a theme could+ // silently restyle code the theme has no business reaching.+ it("puts the app's own rules in the product layer, not the library one", () => {+ const {css} = get();+ const product = layerBlock(css, 'product');+ const library = layerBlock(css, 'astryx-base');++ expect(product).toContain('11px');+ expect(library).not.toContain('11px');++ expect(product.match(LIBRARY_CLASS)).toBeNull();+ expect(library.match(PRODUCT_CLASS)).toBeNull();+ });++ it('leaves no StyleX rule outside the two layers', () => {+ const {css} = get();+ const outside = css+ .replace(layerBlock(css, 'astryx-base'), '')+ .replace(layerBlock(css, 'product'), '');+ expect(outside).not.toContain('@layer priority');+ });++ // StyleX runs its CSS through lightningcss before emitting it. Replacing that+ // output means running the same pass, or the build quietly loses the prefixes+ // the original had.+ it('keeps the vendor prefixing StyleX applies', () => {+ expect(get().css).toContain('-webkit-');+ });++ it('links the stylesheet from the page', () => {+ const {html, cssName} = get();+ expect(html).toContain(cssName);+ expect(html.split(cssName).length - 1, 'linked more than once').toBe(1);+ });+}++describe('a production build separates Astryx and product styles by layer', () => {+ describe('when the app imports a stylesheet of its own', () => {+ let built: Built;+ beforeAll(async () => {+ built = await buildFixture('layer-split');+ }, 180_000);+ afterAll(+ () => built && rmSync(built.outDir, {recursive: true, force: true}),+ );++ itSplitsCorrectly(() => built);+ });++ // StyleX has no bundle asset to append to here, so it writes its own file in+ // `writeBundle` — outside Rollup's graph, which is why Vite emits no `<link>`+ // for it. Every assertion below failed before this case was handled: the+ // stylesheet was unsplit AND the page loaded no styles at all.+ describe('when the app imports no stylesheet at all', () => {+ let built: Built;+ beforeAll(async () => {+ built = await buildFixture('layer-split-nocss');+ }, 180_000);+ afterAll(+ () => built && rmSync(built.outDir, {recursive: true, force: true}),+ );++ itSplitsCorrectly(() => built);+ });+});diff --git a/packages/build/src/vite.test.ts b/packages/build/src/vite.test.tsindex 3937645700..2de09a589b 100644--- a/packages/build/src/vite.test.ts+++ b/packages/build/src/vite.test.ts@@ -7,7 +7,7 @@* theme layer name is fixed at `astryx-theme`.*/-import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import {describe, it, expect, beforeAll, afterAll, vi} from 'vitest';import {mkdtempSync, mkdirSync, rmSync} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';@@ -53,6 +53,52 @@ describe('astryxStylex layer order (legacy API)', () => {});});+/**+ * A production build had no equivalent of the dev server's split-layer plugin,+ * so StyleX's `@layer priorityN` blocks sat outside the declared order and+ * outranked `astryx-theme` — every component override a theme set was dropped.+ * The first fix WRAPPED those blocks in the library layer instead of splitting+ * them, which fixed the theme and broke the app: product StyleX landed below+ * `astryx-theme` too, so a theme could silently restyle code it does not own.+ *+ * These pin the plugin's wiring. That the partition is right in a real build is+ * vite.build.test.ts, and what it means for the cascade is+ * .github/scripts/theme-layer-cascade.js — unit tests over this hook passed+ * throughout both bugs.+ */+describe('astryxStylex build-time layer split', () => {+ const find = (plugins: ReturnType<typeof astryxStylex>) =>+ plugins.find(p => p.name === 'astryx-build-layer-split');++ it('is present on both the modern and the legacy API', () => {+ expect(find(astryxStylex())).toBeTruthy();+ expect(find(astryxStylex({stylexOptions: {}}))).toBeTruthy();+ });++ it('runs on a build only, after the StyleX plugin that emits the CSS', () => {+ const plugin = find(astryxStylex());+ expect(plugin?.apply).toBe('build');+ expect(plugin?.enforce).toBe('post');+ });++ // The dev middleware and the build hook read the same partition, so a build+ // that emits nothing is a build where StyleX collected nothing — never a+ // silent pass-through of unsplit CSS.+ it('does nothing when StyleX collected no rules', () => {+ const plugin = find(astryxStylex());+ const hook = (plugin as any).writeBundle;+ const fn = typeof hook === 'function' ? hook : hook.handler;+ const error = vi.fn();+ expect(() =>+ fn.call(+ {error},+ {dir: mkdtempSync(path.join(tmpdir(), 'astryx-empty-'))},+ ),+ ).not.toThrow();+ expect(error).not.toHaveBeenCalled();+ });+});+describe('astryxStylex optimizeDeps package discovery', () => {let rootDir: string;diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.tsindex d5633d1253..e5c44c507d 100644--- a/packages/build/src/vite.ts+++ b/packages/build/src/vite.ts@@ -6,6 +6,7 @@ import stylex from '@stylexjs/unplugin';import fs from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';+import {createRequire} from 'node:module';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -242,62 +243,273 @@ export function astryxStylex(return next();}- if (!stylexPlugin) {- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.end('');- return;- }-- const shared = stylexPlugin.__stylexGetSharedStore?.();- const rulesById = shared?.rulesById;-- if (!rulesById || rulesById.size === 0) {- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.end('');- return;- }-- const libraryRules: any[] = [];- const productRules: any[] = [];-- for (const [filePath, rules] of rulesById.entries()) {- if (filePath.includes(libraryPattern)) {- libraryRules.push(...rules);- } else {- productRules.push(...rules);- }- }-- const libraryCss = libraryRules.length- ? stylexBabelPlugin.processStylexRules(libraryRules, {- useLayers: true,- })- : '';- const productCss = productRules.length- ? stylexBabelPlugin.processStylexRules(productRules, {- useLayers: true,- })- : '';-- const parts: string[] = [];- if (libraryCss)- parts.push(`@layer ${libraryLayer} {\n${libraryCss}\n}`);- if (productCss)- parts.push(`@layer ${productLayer} {\n${productCss}\n}`);+ const rulesById =+ stylexPlugin?.__stylexGetSharedStore?.()?.rulesById;res.statusCode = 200;res.setHeader('Content-Type', 'text/css');res.setHeader('Cache-Control', 'no-store');- res.end(parts.join('\n\n'));+ res.end(+ renderSplitLayers(rulesById, {+ libraryPattern,+ libraryLayer,+ productLayer,+ }),+ );},});};},};- return [configPlugin, layerOrderPlugin, basePlugin, splitLayerPlugin];+ return [+ configPlugin,+ layerOrderPlugin,+ basePlugin,+ splitLayerPlugin,+ buildLayerSplitPlugin(basePlugin, {+ libraryPattern,+ libraryLayer,+ productLayer,+ lightningcssOptions: stylexOptions.lightningcssOptions,+ }),+ ];+}++/**+ * Partition StyleX's collected rules by the source file that authored them and+ * render each half into its cascade layer: Astryx's own styles into the library+ * layer (below `astryx-theme`, so a theme can override them), product styles+ * into the product layer (above it, so an app always wins).+ *+ * This is the one implementation. The dev middleware and the build hook differ+ * only in when they run and what they do with the string — the partition itself+ * must not diverge, because it did: the build shipped a version that wrapped+ * everything in the library layer, which put product styles UNDER a theme.+ *+ * `rulesById` is keyed by absolute source path, which is the only place the+ * distinction survives — by the time the CSS is text, the origin is gone.+ */+function renderSplitLayers(+ rulesById: Map<string, unknown[]> | undefined,+ options: {+ libraryPattern: string;+ libraryLayer: string;+ productLayer: string;+ },+): string {+ if (!rulesById || rulesById.size === 0) return '';++ const libraryRules: unknown[] = [];+ const productRules: unknown[] = [];++ for (const [filePath, rules] of rulesById.entries()) {+ if (filePath.includes(options.libraryPattern)) {+ libraryRules.push(...rules);+ } else {+ productRules.push(...rules);+ }+ }++ const render = (rules: unknown[], layer: string) =>+ rules.length+ ? `@layer ${layer} {\n${stylexBabelPlugin.processStylexRules(rules as never, {useLayers: true})}\n}`+ : '';++ return [+ render(libraryRules, options.libraryLayer),+ render(productRules, options.productLayer),+ ]+ .filter(Boolean)+ .join('\n\n');+}++/**+ * 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+ * is declared after `@layer reset, astryx-base, astryx-theme, product;` and so+ * outranks every one of them. On the dev server `astryx-split-layers` re-serves+ * the same rules already partitioned; a build had no equivalent, so a theme's+ * component overrides were silently dropped in the built app while working in+ * dev.+ *+ * This replaces that merged block with the partitioned pair. It runs in+ * `writeBundle` because StyleX emits through two different paths depending on+ * whether the bundle already has a stylesheet to append to (`generateBundle`)+ * or has to write its own file (`writeBundle`) — on disk, after both, there is+ * one case instead of two.+ *+ * The block is located by an exact match against StyleX's own collector rather+ * than by looking for `@layer priority1`: a wrong guess about where the block+ * starts silently moves rules between layers, which is the failure this exists+ * to prevent. If the rules exist and the block cannot be found, the build+ * fails.+ */+function buildLayerSplitPlugin(+ basePlugin: unknown,+ options: {+ libraryPattern: string;+ libraryLayer: string;+ productLayer: string;+ lightningcssOptions?: unknown;+ },+): Plugin {+ const stylex = basePlugin as {+ __stylexGetSharedStore?: () => {rulesById: Map<string, unknown[]>};+ __stylexCollectCss?: () => string;+ };+ let base = '/';++ return {+ name: 'astryx-build-layer-split',+ apply: 'build',+ enforce: 'post',+ configResolved(config) {+ base = config.base ?? '/';+ },+ writeBundle(outputOptions) {+ const rulesById = stylex.__stylexGetSharedStore?.().rulesById;+ if (!rulesById || rulesById.size === 0) return;++ const merged = stylex.__stylexCollectCss?.();+ if (!merged) return;++ const split = postProcessCss(+ renderSplitLayers(rulesById, options),+ options.lightningcssOptions,+ );++ const outDir = outputOptions.dir+ ? outputOptions.dir+ : outputOptions.file+ ? path.dirname(outputOptions.file)+ : null;+ // `write: false` builds keep everything in memory; there is nothing to+ // patch and nothing was shipped, so this is not a failure.+ if (!outDir || !fs.existsSync(outDir)) return;++ const patched: string[] = [];+ for (const file of listCssFiles(outDir)) {+ const css = fs.readFileSync(file, 'utf-8');+ const at = css.lastIndexOf(merged);+ if (at === -1) continue;+ fs.writeFileSync(+ file,+ css.slice(0, at) + split + css.slice(at + merged.length),+ );+ patched.push(file);+ }++ if (patched.length === 0) {+ this.error(+ 'astryx-build-layer-split: StyleX emitted rules but its CSS block ' ++ `was not found in any stylesheet under ${outDir}, so Astryx and ` ++ 'product styles could not be separated into their cascade layers. ' ++ 'Leaving the build unsplit would let product styles lose to a ' ++ 'theme. This usually means the StyleX plugin version changed how ' ++ 'it emits CSS.',+ );+ return;+ }++ linkOrphanStylesheets(outDir, patched, base);+ },+ };+}++/** Every `.css` file under a directory, recursively. */+function listCssFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) out.push(...listCssFiles(full));+ else if (entry.name.endsWith('.css')) out.push(full);+ }+ return out;+}++/** Every `.html` file under a directory, recursively. */+function listHtmlFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) out.push(...listHtmlFiles(full));+ else if (entry.name.endsWith('.html')) out.push(full);+ }+ return out;+}++/**+ * Link a stylesheet the build wrote but no page loads.+ *+ * When an app imports no CSS of its own, StyleX has no bundle asset to append+ * to, so it writes `assets/stylex.css` itself — outside Rollup's graph, which+ * means Vite's HTML plugin never learns about it and emits no `<link>`. The app+ * ships every Astryx style correctly split into layers, and a completely+ * unstyled page. Importing any stylesheet hides it, which is why it survives:+ * the moment a project has one line of its own CSS the symptom disappears.+ *+ * Only orphans are linked. A stylesheet already referenced by a page is Vite's,+ * and touching it would duplicate the load. A build with no HTML at all —+ * library mode — is left alone: its consumer imports the CSS themselves.+ */+function linkOrphanStylesheets(+ outDir: string,+ cssFiles: string[],+ base: string,+): void {+ const pages = listHtmlFiles(outDir);+ if (pages.length === 0) return;++ const orphans = cssFiles.filter(css => {+ const name = path.basename(css);+ return !pages.some(page => fs.readFileSync(page, 'utf-8').includes(name));+ });+ if (orphans.length === 0) return;++ const links = orphans+ .map(css => {+ const href =+ base.replace(/\/$/, '') ++ '/' ++ path.relative(outDir, css).split(path.sep).join('/');+ return `<link rel="stylesheet" crossorigin href="${href}">`;+ })+ .join('\n ');++ for (const page of pages) {+ const html = fs.readFileSync(page, 'utf-8');+ if (!html.includes('</head>')) continue;+ fs.writeFileSync(page, html.replace('</head>', ` ${links}\n </head>`));+ }+}++/**+ * StyleX runs its collected CSS through lightningcss before emitting it, so+ * anything replacing that output has to run the same pass or the build quietly+ * loses the vendor prefixes and lowering the original had.+ *+ * lightningcss ships with both Vite and the StyleX plugin, either of which must+ * be installed for this plugin to run at all. If it somehow is not resolvable,+ * the unprocessed CSS is correct — just less compatible — so this degrades+ * rather than failing the build.+ */+function postProcessCss(css: string, lightningcssOptions: unknown): string {+ if (!css) return css;+ try {+ const require_ = createRequire(import.meta.url);+ const {transform, browserslistToTargets} = require_('lightningcss');+ const browserslist = require_('browserslist');+ const {code} = transform({+ targets: browserslistToTargets(browserslist()),+ ...(lightningcssOptions as object),+ filename: 'stylex.css',+ code: Buffer.from(css),+ });+ return code.toString();+ } catch {+ return css;+ }}/**@@ -370,60 +582,35 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {return next();}- if (!stylexPlugin) {- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.end('');- return;- }-- const shared = stylexPlugin.__stylexGetSharedStore?.();- const rulesById = shared?.rulesById;-- if (!rulesById || rulesById.size === 0) {- res.statusCode = 200;- res.setHeader('Content-Type', 'text/css');- res.end('');- return;- }-- const libraryRules: any[] = [];- const productRules: any[] = [];-- for (const [filePath, rules] of rulesById.entries()) {- if (filePath.includes(libraryPattern)) {- libraryRules.push(...rules);- } else {- productRules.push(...rules);- }- }-- const libraryCss = libraryRules.length- ? stylexBabelPlugin.processStylexRules(libraryRules, {- useLayers: true,- })- : '';- const productCss = productRules.length- ? stylexBabelPlugin.processStylexRules(productRules, {- useLayers: true,- })- : '';-- const parts: string[] = [];- if (libraryCss)- parts.push(`@layer ${libraryLayer} {\n${libraryCss}\n}`);- if (productCss)- parts.push(`@layer ${productLayer} {\n${productCss}\n}`);+ const rulesById =+ stylexPlugin?.__stylexGetSharedStore?.()?.rulesById;res.statusCode = 200;res.setHeader('Content-Type', 'text/css');res.setHeader('Cache-Control', 'no-store');- res.end(parts.join('\n\n'));+ res.end(+ renderSplitLayers(rulesById, {+ libraryPattern,+ libraryLayer,+ productLayer,+ }),+ );},});};},};- return [layerOrderPlugin, basePlugin, splitLayerPlugin];+ return [+ layerOrderPlugin,+ basePlugin,+ splitLayerPlugin,+ buildLayerSplitPlugin(basePlugin, {+ libraryPattern,+ libraryLayer,+ productLayer,+ lightningcssOptions: (stylexOptions as {lightningcssOptions?: unknown})+ ?.lightningcssOptions,+ }),+ ];}