Skip to content

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

TypeScript

fix(build): a swizzled copy compiles in the library pass, below the theme (#10334)

Cindy Zhangc909db9ce0e6
diff --git a/.changeset/build-swizzle-marker.md b/.changeset/build-swizzle-marker.md
new file mode 100644
index 0000000000..c40f2c479f
--- /dev/null
+++ b/.changeset/build-swizzle-marker.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/build': patch
+---
+
+[fix] A swizzled copy can now compile as Astryx source in the Babel, PostCSS, and Vite integrations. Every module under a folder that holds an `astryx-swizzle.json` marker gets the library class prefix and lands in `@layer astryx-base`, below `astryx-theme`, so a theme's component overrides reach it. `astryx swizzle` does not write the marker yet: add the file to the swizzle output folder. Under webpack, `withAstryx()` rebuilds a cached copy when its marker appears or disappears. Turbopack builds do not read the marker yet. No API changes.
+
+@cixzhang
diff --git a/docs/specs/AST-080-package-stylesheets/spec.md b/docs/specs/AST-080-package-stylesheets/spec.md
index 384b9944ca..6e4a805ac1 100644
--- a/docs/specs/AST-080-package-stylesheets/spec.md
+++ b/docs/specs/AST-080-package-stylesheets/spec.md
@@ -63,7 +63,8 @@ first.
- Which StyleX variable groups a package stylesheet contains, owned by
`spec:AST-066` FR3.
- How a product compiles its own code, including any StyleX settings it uses for
- its own styles or for components it ejects with `astryx swizzle`.
+ its own styles or for components it ejects with `astryx swizzle`, except where
+ a swizzled copy's rules land under `@astryxdesign/build` (FR5, FR7).
- How `@astryxdesign/build` plugs into a bundler other than through
`withAstryx()` (FR9), and how a source build chooses a subset of a package's
modules to compile.
@@ -137,6 +138,11 @@ first.
@import '@astryxdesign/theme-neutral/theme.css';
```
+ Under `@astryxdesign/build`, a swizzled copy whose folder holds an
+ `astryx-swizzle.json` marker builds through the library pass, so its rules
+ land in `astryx-base` below `astryx-theme` (`spec:AST-110` FR5); the stock
+ StyleX plugins have no library pass.
+
The documentation MAY also present a source build as an alternative to a default
setup: the source of one or more packages compiled through `@astryxdesign/build`
under FR7 (and FR9 for `withAstryx()`), each in place of that package's
@@ -161,8 +167,10 @@ first.
reproduces its prebuilt stylesheet's rules; compiling a subset produces the
rules those modules use. A source build of Core always includes the Core
definitions other packages' prebuilt stylesheets rely on under FR2, such as
- variable groups and keyframes. Product rules stay outside `astryx-base`. A
- source build needs no data beyond the package's own source, and holds in
+ variable groups and keyframes. Product rules stay outside `astryx-base`,
+ except a swizzled copy's: modules under a folder holding an
+ `astryx-swizzle.json` marker compile in the library pass into `astryx-base`
+ (`spec:AST-110` FR5). A source build needs no data beyond the package's own source, and holds in
development builds as in production builds.
- **FR8 — Stylesheet growth is reported and budgeted per component.** Every
@@ -197,8 +205,9 @@ first.
`@layer reset, astryx-base, astryx-theme`: Core's `reset.css` in `reset`,
each package's compiled block in `astryx-base`, and the theme in
`astryx-theme`. Each compiled block begins with the FR3 order registration
- (FR7). Product CSS, including the product's own StyleX output, stays
- unlayered and wins over every Astryx rule in any chunk or load order. A
+ (FR7). Product CSS, including the product's own StyleX output other than
+ a marked swizzled copy's (FR7), stays unlayered and wins over every Astryx
+ rule in any chunk or load order. A
non-Core block relies on Core's variables and keyframes as under FR2.
- **Stylesheet entry (Turbopack).** The product lists the PostCSS plugin
`@astryxdesign/build/next/postcss` in its PostCSS config and puts one
@@ -269,6 +278,12 @@ first.
emits no order registration in its own output (FR7), relying on `reset.css`,
the theme, or the product's line. Closing these gaps changes existing webpack
output.
+- The FR7 exception for a swizzled copy holds in the Babel, PostCSS, and Vite
+ integrations. `withAstryx()` under Turbopack does not read the
+ `astryx-swizzle.json` marker, and `astryx swizzle` does not write it, so a
+ product adds the marker to the copy's folder (FR5, FR7). Under webpack,
+ `withAstryx()` makes each app module depend on the marker paths above it, so
+ a cached build recompiles a copy when its marker appears or disappears (FR7).
- Under Turbopack no maintained StyleX compiler runs in the native pipeline, so
the FR9 fast path is a goal with a known gap: the Turbopack route compiles
Astryx modules through a JavaScript loader running Babel and the StyleX Babel
diff --git a/docs/specs/AST-110-swizzle-output/spec.md b/docs/specs/AST-110-swizzle-output/spec.md
index 76823392da..2d896cfab8 100644
--- a/docs/specs/AST-110-swizzle-output/spec.md
+++ b/docs/specs/AST-110-swizzle-output/spec.md
@@ -171,8 +171,8 @@ and the repository proves it before a change that could break it merges.
never replaced, with or without `--overwrite` (FR2), except an owner module
and its unexported style modules, which a changed copy refuses without
`--overwrite` and replaces with it (FR4).
-- `@astryxdesign/build`'s Vite, PostCSS, Babel, and Next integrations compile
- modules under an `astryx-swizzle.json` directory in the library pass (FR5).
+- `@astryxdesign/build`'s Next integration under Turbopack compiles modules
+ under an `astryx-swizzle.json` directory in the library pass (FR5).
- The styling overview states that a copy's rules land in `astryx-base` with
`@astryxdesign/build`, and above `astryx-theme` with the stock StyleX plugins
(FR5).
@@ -183,8 +183,9 @@ and the repository proves it before a change that could break it merges.
- The copy sends `../X/file` imports to the public `X` entry, which lacks the
internal helpers, and deep StyleX modules are missing from Core's exports
(FR1, FR2).
-- Copied styles land in the app's cascade layer above the theme's, so theme
- component overrides stop applying (FR5).
+- `astryx swizzle` does not write the `astryx-swizzle.json` marker, so a copy's
+ styles land in the app's cascade layer above the theme's, and theme component
+ overrides stop applying, until the product adds the marker (FR5).
- Copies include spec records and test files and leave out nested folders
(FR2), and `swizzle --list` offers folders that are not components
(`spec:AST-035` FR12).
@@ -210,11 +211,8 @@ and the repository proves it before a change that could break it merges.
- Products on the stock StyleX plugins have no library-pass setting, so a
copy's rules land above `astryx-theme` there and theme component overrides do
not reach it (FR5).
-- `spec:AST-080` FR5 presents the stock StyleX path as the default for ejected
- components, and its FR7 keeps every product rule, a copy's included, outside
- `astryx-base`. The pull request that makes this record current amends both
- with their swizzle case (FR5) and adds the `architecture:cli-surface` pointer
- to this record.
+- The pull request that makes this record current adds the
+ `architecture:cli-surface` pointer to this record.
## Verification
diff --git a/packages/build/README.md b/packages/build/README.md
index 0f4f5b9701..2975a04dec 100644
--- a/packages/build/README.md
+++ b/packages/build/README.md
@@ -156,7 +156,7 @@ module.exports = {
### 3. next.config.mjs
-Or `withAstryx()` from `@astryxdesign/build/next`, which sets both of these for you.
+Or `withAstryx()` from `@astryxdesign/build/next`, which sets both of these for you. Use `withAstryx()` when the app has a swizzled copy with an `astryx-swizzle.json` marker: this manual config does not rebuild the copy when its marker appears or goes.
Either way the work happens in the `webpack` hook, so the build has to run with
`--webpack` — see the note at the top of this section.
@@ -253,6 +253,8 @@ Library patterns (configurable):
- `packages/themes/`
- `node_modules/@astryxdesign/`
+A swizzled copy is library code too. The Babel, PostCSS, and Vite integrations compile every module under a folder that holds an `astryx-swizzle.json` marker with the library prefix into `@layer astryx-base`, so a theme's component overrides reach the copy as they reach the package component. `astryx swizzle` does not write the marker yet: add it to the swizzle output folder, naming the package the copy came from and its version, such as `{"packages": {"@astryxdesign/core": "0.7.10"}}`. The build reads only whether the file is there. Under webpack, use `withAstryx()` with a marked copy: it makes each app module depend on the marker paths above it, so a dev session or a cached build recompiles a copy when its marker appears or disappears. In another setup that caches transforms, restart the dev server and delete that cache after adding or removing a marker. Turbopack builds do not read the marker yet.
+
### PostCSS plugin (`@astryxdesign/build/postcss`)
Compiles StyleX from both library and product source files in two separate passes with different prefixes. Wraps the results in named `@layer` blocks:
diff --git a/packages/build/__fixtures__/layer-split-swizzled/App.tsx b/packages/build/__fixtures__/layer-split-swizzled/App.tsx
new file mode 100644
index 0000000000..0b98d6be97
--- /dev/null
+++ b/packages/build/__fixtures__/layer-split-swizzled/App.tsx
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Product code beside a swizzled copy, for the layer-split build fixture. The
+ * copy's folder holds the marker `astryx swizzle` writes, so its StyleX must
+ * land in the library layer while this file's stays in the product layer.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {Badge} from './components/astryx/Badge/Badge';
+
+const styles = stylex.create({
+ productBox: {padding: '11px'},
+});
+
+export function App() {
+ return (
+ <div {...stylex.props(styles.productBox)}>
+ <Badge />
+ </div>
+ );
+}
diff --git a/packages/build/__fixtures__/layer-split-swizzled/components/astryx/Badge/Badge.tsx b/packages/build/__fixtures__/layer-split-swizzled/components/astryx/Badge/Badge.tsx
new file mode 100644
index 0000000000..bf260a1a08
--- /dev/null
+++ b/packages/build/__fixtures__/layer-split-swizzled/components/astryx/Badge/Badge.tsx
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** A copy `astryx swizzle` wrote, for the layer-split build fixture. */
+
+import * as stylex from '@stylexjs/stylex';
+
+const styles = stylex.create({
+ badge: {padding: '13px', backgroundColor: 'rgb(10, 11, 12)'},
+});
+
+export function Badge() {
+ return <span {...stylex.props(styles.badge)}>copy</span>;
+}
diff --git a/packages/build/__fixtures__/layer-split-swizzled/components/astryx/astryx-swizzle.json b/packages/build/__fixtures__/layer-split-swizzled/components/astryx/astryx-swizzle.json
new file mode 100644
index 0000000000..9fe023bb53
--- /dev/null
+++ b/packages/build/__fixtures__/layer-split-swizzled/components/astryx/astryx-swizzle.json
@@ -0,0 +1 @@
+{"packages": {"@astryxdesign/core": "0.0.0"}}
diff --git a/packages/build/__fixtures__/layer-split-swizzled/index.css b/packages/build/__fixtures__/layer-split-swizzled/index.css
new file mode 100644
index 0000000000..b7398f4f36
--- /dev/null
+++ b/packages/build/__fixtures__/layer-split-swizzled/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-swizzled/index.html b/packages/build/__fixtures__/layer-split-swizzled/index.html
new file mode 100644
index 0000000000..bf4e6153c9
--- /dev/null
+++ b/packages/build/__fixtures__/layer-split-swizzled/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-swizzled 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-swizzled/main.tsx b/packages/build/__fixtures__/layer-split-swizzled/main.tsx
new file mode 100644
index 0000000000..441e4d5d48
--- /dev/null
+++ b/packages/build/__fixtures__/layer-split-swizzled/main.tsx
@@ -0,0 +1,7 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createRoot} from 'react-dom/client';
+import './index.css';
+import {App} from './App';
+
+createRoot(document.getElementById('root')!).render(<App />);
diff --git a/packages/build/build.mjs b/packages/build/build.mjs
index a37d3b4769..cd6ce23183 100644
--- a/packages/build/build.mjs
+++ b/packages/build/build.mjs
@@ -39,6 +39,11 @@ content = content.replaceAll(
'resolve(__dirname, "babel.js")',
'resolve(__dirname, "../src/babel.js")',
);
+// The marker reader also lives in src/, beside babel.js.
+content = content.replaceAll(
+ 'resolve(__dirname, "swizzle-marker.js")',
+ 'resolve(__dirname, "../src/swizzle-marker.js")',
+);
writeFileSync('dist/vite.mjs', content);
console.log('Built dist/vite.mjs');
diff --git a/packages/build/src/babel.js b/packages/build/src/babel.js
index acf49ae9b8..bddd523ce1 100644
--- a/packages/build/src/babel.js
+++ b/packages/build/src/babel.js
@@ -11,6 +11,9 @@
* Library files get 'astryx' prefix (.astryx78zum5), product files get 'x' (.x78zum5).
*/
+const path = require('node:path');
+const {isSwizzledSource} = require('./swizzle-marker');
+
const LIBRARY_PATTERNS = [
'packages/core/',
'packages/themes/',
@@ -47,8 +50,17 @@ module.exports = function astryxBabelPlugin(api, options) {
const libraryPlugin = stylexPlugin(api, libraryOpts);
const productPlugin = stylexPlugin(api, productOpts);
- function getPluginAndOpts(filename) {
- const isLibrary = libraryPatterns.some(p => filename.includes(p));
+ // Each transform's file is classified once, not on every visitor call.
+ const libraryFiles = new WeakMap();
+ function getPluginAndOpts(state) {
+ let isLibrary = libraryFiles.get(state.file);
+ if (isLibrary === undefined) {
+ const filename = state.filename || '';
+ isLibrary =
+ libraryPatterns.some(p => filename.includes(p)) ||
+ (filename !== '' && isSwizzledSource(path.resolve(filename)));
+ if (state.file != null) libraryFiles.set(state.file, isLibrary);
+ }
return isLibrary
? {plugin: libraryPlugin, opts: libraryOpts}
: {plugin: productPlugin, opts: productOpts};
@@ -56,7 +68,7 @@ module.exports = function astryxBabelPlugin(api, options) {
// Helper: call a visitor function with overridden state.opts
function callVisitor(visitor, key, path, state) {
- const {plugin, opts} = getPluginAndOpts(state.filename || '');
+ const {plugin, opts} = getPluginAndOpts(state);
const v = plugin.visitor[key];
if (!v) return;
diff --git a/packages/build/src/babel.test.mjs b/packages/build/src/babel.test.mjs
index c7947d3ed2..1e9bf07650 100644
--- a/packages/build/src/babel.test.mjs
+++ b/packages/build/src/babel.test.mjs
@@ -10,6 +10,7 @@
*/
import {describe, it, expect} from 'vitest';
+import * as os from 'node:os';
import * as fs from 'node:fs';
import {createRequire} from 'node:module';
import * as path from 'node:path';
@@ -168,3 +169,59 @@ describe('Astryx babel wrapper -- Astryx source under the strict default', () =>
expect(failures).toEqual([]);
}, 120_000);
});
+
+/** A product module with many StyleX calls, so many visitor calls. */
+const MANY_STYLES = `
+import * as stylex from '@stylexjs/stylex';
+${Array.from({length: 20}, (_, i) => `export const s${i} = stylex.create({box: {width: '${i + 1}px'}});`).join('\n')}
+`;
+
+describe('Astryx babel wrapper -- a swizzled copy', () => {
+ it('gives a module under a swizzle marker the library prefix', () => {
+ const app = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-babel-swizzle-'));
+ try {
+ const output = path.join(app, 'src/components/astryx');
+ fs.mkdirSync(path.join(output, 'Box'), {recursive: true});
+ fs.writeFileSync(
+ path.join(output, 'astryx-swizzle.json'),
+ JSON.stringify({packages: {'@astryxdesign/core': '0.0.0'}}),
+ );
+ const compile = (filename, source = SOURCE) =>
+ babel.transformSync(source, {
+ filename,
+ babelrc: false,
+ configFile: false,
+ plugins: [
+ [
+ astryxBabelPlugin,
+ {unstable_moduleResolution: {type: 'commonJS', rootDir: app}},
+ ],
+ ],
+ })?.code ?? '';
+ const copied = atomicClasses(compile(path.join(output, 'Box/Box.tsx')));
+ expect(copied.length).toBeGreaterThan(0);
+ expect(copied.every(c => c.startsWith('astryx'))).toBe(true);
+ // The wrapper classifies a file once, not on every StyleX visitor call.
+ const lookups = [];
+ const nodeFs = require('node:fs');
+ const existsSync = nodeFs.existsSync;
+ nodeFs.existsSync = file => {
+ if (String(file).endsWith('astryx-swizzle.json')) lookups.push(file);
+ return existsSync(file);
+ };
+ try {
+ compile(path.join(app, 'src/Many.tsx'), MANY_STYLES);
+ } finally {
+ nodeFs.existsSync = existsSync;
+ }
+ const folders = path.join(app, 'src').split(path.sep).length;
+ expect(lookups.length).toBeLessThanOrEqual(folders);
+ // Product code beside the copy keeps the product prefix.
+ expect(atomicClasses(compile(path.join(app, 'src/Page.tsx')))).toEqual(
+ [],
+ );
+ } finally {
+ fs.rmSync(app, {recursive: true, force: true});
+ }
+ });
+});
diff --git a/packages/build/src/index.js b/packages/build/src/index.js
index 4484d9b05e..9bab0baec1 100644
--- a/packages/build/src/index.js
+++ b/packages/build/src/index.js
@@ -23,6 +23,7 @@
*/
const path = require('node:path');
+const {isSwizzledSource} = require('./swizzle-marker');
const fs = require('node:fs');
const babel = require('@babel/core');
const stylexBabelPlugin = require('@stylexjs/babel-plugin');
@@ -242,11 +243,24 @@ function createPlugin() {
// Partition files into library vs product, then compile
// each group with its own babel config (different prefix)
const transforms = [];
+ // A swizzled copy is Astryx source too: it compiles in the library pass.
+ const markerMemo = new Map();
for (const filePath of files) {
+ // Classify every file on each pass: when a marker appears or goes,
+ // `withAstryx()` rebuilds the copy with the other prefix.
+ const isLibrary =
+ libraryPatterns.some(p => filePath.includes(p)) ||
+ isSwizzledSource(filePath, markerMemo);
+ const rulesMap = isLibrary ? libraryRulesMap : productRulesMap;
+ const movedSides = (
+ isLibrary ? productRulesMap : libraryRulesMap
+ ).delete(filePath);
+
const mtimeMs = fs.existsSync(filePath)
? fs.statSync(filePath).mtimeMs
: -Infinity;
if (
+ !movedSides &&
fileModifiedMap.has(filePath) &&
mtimeMs === fileModifiedMap.get(filePath)
) {
@@ -257,9 +271,7 @@ function createPlugin() {
const contents = fs.readFileSync(filePath, 'utf-8');
if (!contents.includes(STYLEX_IMPORT_SOURCE)) continue;
- const isLibrary = libraryPatterns.some(p => filePath.includes(p));
const config = isLibrary ? libraryBabelConfig : productBabelConfig;
- const rulesMap = isLibrary ? libraryRulesMap : productRulesMap;
transforms.push(
babel
diff --git a/packages/build/src/next.js b/packages/build/src/next.js
index 0245639db5..2f95b99af4 100644
--- a/packages/build/src/next.js
+++ b/packages/build/src/next.js
@@ -30,6 +30,7 @@ const ASTRYX_MODULE = /[\\/]node_modules[\\/]@astryxdesign[\\/]/;
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const TURBOPACK_LOADER = require.resolve('./turbopack-loader.js');
+const SWIZZLE_MARKER_LOADER = require.resolve('./swizzle-marker-loader.js');
/**
* Match a wildcard alias key such as `@astryxdesign/*` against a request. The
@@ -370,6 +371,14 @@ function withAstryx(nextConfig = {}) {
.map(name => findPackageDir(name, from))
.filter(dir => dir != null)
.map(dir => escapeRegExp(fs.realpathSync(dir) + path.sep));
+ // The app's own modules depend on the swizzle markers above them, so a
+ // cached build recompiles a copy when its marker appears or disappears.
+ config.module.rules.unshift({
+ test: /\.[cm]?[jt]sx?$/,
+ exclude: /[\\/]node_modules[\\/]/,
+ enforce: 'pre',
+ use: [{loader: SWIZZLE_MARKER_LOADER}],
+ });
config.module.rules.unshift({
test:
realPackageDirs.length === 0
diff --git a/packages/build/src/postcss.test.mjs b/packages/build/src/postcss.test.mjs
index 1efa6232f6..0c161f2db5 100644
--- a/packages/build/src/postcss.test.mjs
+++ b/packages/build/src/postcss.test.mjs
@@ -20,6 +20,8 @@ const {postcss} = require('./config.js');
const LIBRARY_FILE = 'node_modules/@astryxdesign/core/src/Box/Box.tsx';
const PRODUCT_FILE = 'src/page.tsx';
+/** A copy `astryx swizzle` wrote: its output folder holds the marker. */
+const SWIZZLED_FILE = 'src/components/astryx/Badge/Badge.tsx';
let appDir;
@@ -62,6 +64,14 @@ beforeAll(() => {
"export const styles = stylex.create({page: {color: 'blue'}});",
'',
].join('\n'),
+ 'src/components/astryx/astryx-swizzle.json': JSON.stringify({
+ packages: {'@astryxdesign/core': '0.0.0'},
+ }),
+ [SWIZZLED_FILE]: [
+ "import * as stylex from '@stylexjs/stylex';",
+ "export const styles = stylex.create({badge: {color: 'green'}});",
+ '',
+ ].join('\n'),
};
for (const [file, contents] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(appDir, file)), {recursive: true});
@@ -81,15 +91,20 @@ afterAll(() => {
fs.rmSync(appDir, {recursive: true, force: true});
});
+/** One instance of the documented config's StyleX plugin, as a dev server keeps. */
+function createCompile() {
+ const config = postcss(appDir);
+ const options = config.plugins[require.resolve('./index.js')];
+ const [compile] = require('./index.js')(options).plugins;
+ return compile;
+}
+
/**
* Run the documented config's StyleX plugin over the app the way `next build`
* does: from the app directory, on a stylesheet holding `@stylex;`. Returns the
* CSS that replaces the at-rule.
*/
-async function compileApp() {
- const config = postcss(appDir);
- const options = config.plugins[require.resolve('./index.js')];
- const [compile] = require('./index.js')(options).plugins;
+async function compileApp(compile = createCompile()) {
let css = null;
const atRule = {
name: 'stylex',
@@ -133,3 +148,55 @@ describe('the PostCSS plugin and the app Babel config', () => {
}
});
});
+
+describe('the PostCSS plugin and a swizzled copy', () => {
+ it('compiles a module under a swizzle marker into the library layer', async () => {
+ globalThis.appBabelConfigFiles = [];
+ try {
+ const css = await compileApp();
+ const library = css.match(/@layer astryx-base \{[^]*?\n\}/)?.[0] ?? '';
+ const product = css.match(/@layer product \{[^]*?\n\}/)?.[0] ?? '';
+ expect(library).toMatch(/color:\s*green/);
+ expect(product).not.toMatch(/color:\s*green/);
+ // The library pass compiles it, with the library class prefix.
+ expect(library).toMatch(/\.astryx[a-z0-9]{5,}[^{]*\{[^}]*color:\s*green/);
+ expect(globalThis.appBabelConfigFiles).not.toContain(
+ path.join(appDir, SWIZZLED_FILE),
+ );
+ } finally {
+ delete globalThis.appBabelConfigFiles;
+ }
+ });
+
+ it('moves an unchanged copy between layers when its marker appears or goes during a dev session', async () => {
+ const marker = path.join(
+ appDir,
+ 'src/components/astryx/astryx-swizzle.json',
+ );
+ const saved = fs.readFileSync(marker, 'utf-8');
+ globalThis.appBabelConfigFiles = [];
+ try {
+ const compile = createCompile();
+ const marked = await compileApp(compile);
+ expect(layer(marked, 'astryx-base')).toMatch(/color:\s*green/);
+
+ fs.rmSync(marker);
+ const unmarked = await compileApp(compile);
+ expect(layer(unmarked, 'product')).toMatch(/color:\s*green/);
+ expect(layer(unmarked, 'astryx-base')).not.toMatch(/color:\s*green/);
+
+ fs.writeFileSync(marker, saved);
+ const remarked = await compileApp(compile);
+ expect(layer(remarked, 'astryx-base')).toMatch(/color:\s*green/);
+ expect(layer(remarked, 'product')).not.toMatch(/color:\s*green/);
+ } finally {
+ fs.writeFileSync(marker, saved);
+ delete globalThis.appBabelConfigFiles;
+ }
+ });
+});
+
+/** The text of one `@layer` block in the emitted CSS. */
+function layer(css, name) {
+ return css.match(new RegExp(`@layer ${name} \\{[^]*?\\n\\}`))?.[0] ?? '';
+}
diff --git a/packages/build/src/swizzle-marker-loader.js b/packages/build/src/swizzle-marker-loader.js
new file mode 100644
index 0000000000..4cd86a0168
--- /dev/null
+++ b/packages/build/src/swizzle-marker-loader.js
@@ -0,0 +1,25 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use strict';
+
+/**
+ * @astryxdesign/build: a webpack pre-loader that `withAstryx()` installs for
+ * the app's own modules. It makes each module depend on every swizzle marker
+ * path that decides how the module compiles, so webpack rebuilds the module,
+ * and its cached class names, when a marker appears or disappears. It does
+ * not change the source.
+ */
+
+const fs = require('node:fs');
+const {markerPaths} = require('./swizzle-marker');
+
+module.exports = function astryxSwizzleMarkerLoader(source, map, meta) {
+ for (const marker of markerPaths(this.resourcePath, this.rootContext)) {
+ if (fs.existsSync(marker)) {
+ this.addDependency(marker);
+ break;
+ }
+ this.addMissingDependency(marker);
+ }
+ this.callback(null, source, map, meta);
+};
diff --git a/packages/build/src/swizzle-marker.d.ts b/packages/build/src/swizzle-marker.d.ts
new file mode 100644
index 0000000000..47bee3714c
--- /dev/null
+++ b/packages/build/src/swizzle-marker.d.ts
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** The marker file in a swizzle output folder. */
+export declare const SWIZZLE_MARKER: string;
+
+/**
+ * Whether a module is in a swizzled copy: a folder at or above it holds the
+ * marker. One `memo` per build pass looks each folder up once.
+ */
+/** The marker paths from a module's folder up to `stopDir` or the root. */
+export declare function markerPaths(
+ filePath: string,
+ stopDir?: string,
+): string[];
+
+export declare function isSwizzledSource(
+ filePath: string,
+ memo?: Map<string, boolean>,
+): boolean;
diff --git a/packages/build/src/swizzle-marker.js b/packages/build/src/swizzle-marker.js
new file mode 100644
index 0000000000..6e998c857c
--- /dev/null
+++ b/packages/build/src/swizzle-marker.js
@@ -0,0 +1,68 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use strict';
+
+/**
+ * @astryxdesign/build: swizzled copies. A swizzle output folder holds an
+ * `astryx-swizzle.json` marker. Every module under a folder that holds the
+ * marker is Astryx source: the library pass compiles it with
+ * the library class prefix into the library layer, below `astryx-theme`, so a
+ * theme's component overrides reach the copy as they reach the package.
+ */
+
+const fs = require('node:fs');
+const path = require('node:path');
+
+/** The marker file in a swizzle output folder. */
+const SWIZZLE_MARKER = 'astryx-swizzle.json';
+
+/**
+ * Whether a module is in a swizzled copy: a folder at or above it holds the
+ * marker. Pass one `memo` to the checks of one build pass, so each folder is
+ * looked up once; nothing is kept between passes, so a copy swizzled while a
+ * dev server runs counts from the next pass.
+ * @param {string} filePath an absolute module path
+ * @param {Map<string, boolean>} [memo] folder -> whether it or a folder
+ * above it holds the marker
+ * @returns {boolean}
+ */
+function isSwizzledSource(filePath, memo = new Map()) {
+ /** @type {string[]} */
+ const visited = [];
+ let dir = path.dirname(filePath);
+ let marked = false;
+ for (;;) {
+ const known = memo.get(dir);
+ if (known !== undefined) {
+ marked = known;
+ break;
+ }
+ visited.push(dir);
+ if (fs.existsSync(path.join(dir, SWIZZLE_MARKER))) {
+ marked = true;
+ break;
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ for (const folder of visited) memo.set(folder, marked);
+ return marked;
+}
+
+/**
+ * The marker paths that decide whether a module is in a swizzled copy, from
+ * its own folder up to `stopDir` (or the file system root).
+ * @param {string} filePath an absolute module path
+ * @param {string} [stopDir] the last folder to check, such as the project root
+ * @returns {string[]}
+ */
+function markerPaths(filePath, stopDir) {
+ const paths = [];
+ for (let dir = path.dirname(filePath); ; dir = path.dirname(dir)) {
+ paths.push(path.join(dir, SWIZZLE_MARKER));
+ if (dir === stopDir || path.dirname(dir) === dir) return paths;
+ }
+}
+
+module.exports = {SWIZZLE_MARKER, isSwizzledSource, markerPaths};
diff --git a/packages/build/src/swizzle-marker.webpack.test.mjs b/packages/build/src/swizzle-marker.webpack.test.mjs
new file mode 100644
index 0000000000..e50805e869
--- /dev/null
+++ b/packages/build/src/swizzle-marker.webpack.test.mjs
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file swizzle-marker.webpack.test.mjs
+ * @description A cached webpack build recompiles a swizzled copy when its
+ * marker appears. `withAstryx()` installs a pre-loader that makes each app
+ * module depend on the marker paths above it; without it, webpack's
+ * persistent cache keeps the copy's earlier compile, and its class names,
+ * after a marker is added.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+
+const require = createRequire(import.meta.url);
+const {withAstryx} = require('./next.js');
+
+/** Next's own webpack, the one `next build --webpack` runs. */
+function nextWebpack() {
+ return require('next/dist/compiled/webpack/bundle5')().webpack;
+}
+
+let dir;
+
+beforeEach(() => {
+ dir = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-marker-webpack-')),
+ );
+ const app = path.join(dir, 'app');
+ fs.mkdirSync(path.join(app, 'src/components/astryx/Badge'), {
+ recursive: true,
+ });
+ fs.writeFileSync(path.join(app, 'package.json'), '{"name":"app"}');
+ fs.writeFileSync(
+ path.join(app, 'src/components/astryx/Badge/Badge.js'),
+ 'export const badge = 1;\n',
+ );
+ fs.writeFileSync(
+ path.join(app, 'src/index.js'),
+ "export {badge, side} from './components/astryx/Badge/Badge.js';\n",
+ );
+ // Stands in for the StyleX transform: it compiles a module by its side.
+ fs.writeFileSync(
+ path.join(dir, 'side-loader.js'),
+ [
+ `const {isSwizzledSource} = require(${JSON.stringify(require.resolve('./swizzle-marker.js'))});`,
+ 'module.exports = function (source) {',
+ ' if (!this.resourcePath.endsWith("Badge.js")) return source;',
+ ' const side = isSwizzledSource(this.resourcePath) ? "library" : "product";',
+ ' return source + `export const side = ${JSON.stringify(side)};\\n`;',
+ '};',
+ '',
+ ].join('\n'),
+ );
+});
+
+afterEach(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+/** One cached build; returns the side the copy compiled as. */
+function build(rules) {
+ const webpack = nextWebpack();
+ const app = path.join(dir, 'app');
+ return new Promise((resolve, reject) => {
+ webpack(
+ {
+ mode: 'development',
+ devtool: false,
+ context: app,
+ entry: './src/index.js',
+ output: {path: path.join(dir, 'out'), library: {type: 'commonjs2'}},
+ cache: {type: 'filesystem', cacheDirectory: path.join(dir, 'cache')},
+ module: {
+ rules: [
+ ...rules,
+ {test: /\.js$/, use: [path.join(dir, 'side-loader.js')]},
+ ],
+ },
+ },
+ (error, stats) => {
+ if (error) return reject(error);
+ if (stats.hasErrors())
+ return reject(new Error(stats.toString('errors-only')));
+ stats.compilation.compiler.close(() => {
+ const out = fs.readFileSync(path.join(dir, 'out/main.js'), 'utf-8');
+ resolve(out.match(/side = \\?"(\w+)\\?"/)?.[1] ?? null);
+ });
+ },
+ );
+ });
+}
+
+describe('withAstryx and a swizzle marker under a cached webpack build', () => {
+ it('recompiles an unchanged copy when its marker appears', async () => {
+ const config = withAstryx({}).webpack(
+ {resolve: {}, module: {rules: []}},
+ {dir: path.join(dir, 'app')},
+ );
+ const markerRules = config.module.rules.filter(
+ rule => rule.enforce === 'pre',
+ );
+ expect(markerRules).toHaveLength(1);
+
+ expect(await build(markerRules)).toBe('product');
+ fs.writeFileSync(
+ path.join(dir, 'app/src/components/astryx/astryx-swizzle.json'),
+ '{}',
+ );
+ expect(await build(markerRules)).toBe('library');
+ }, 120_000);
+});
diff --git a/packages/build/src/vite.build.test.ts b/packages/build/src/vite.build.test.ts
index 65d9b2ac8f..d8e4ff3741 100644
--- a/packages/build/src/vite.build.test.ts
+++ b/packages/build/src/vite.build.test.ts
@@ -381,6 +381,30 @@ describe('a production build separates Astryx and product styles by layer', () =
// 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 compiles a swizzled copy in the library pass', () => {
+ let built: Built;
+ beforeAll(async () => {
+ built = await buildFixture('layer-split-swizzled', ['index.html'], {
+ zeroConfig: true,
+ });
+ }, 180_000);
+ afterAll(() => built && rmSync(built.outDir, {recursive: true, force: true}));
+
+ it('puts the copy under a swizzle marker in astryx-base, with the library prefix', () => {
+ const library = layerBlock(built.css, 'astryx-base');
+ expect(library).toContain('13px');
+ expect(library).toContain('#0a0b0c');
+ expect(library.match(PRODUCT_CLASS)).toBeNull();
+ expect(library.match(LIBRARY_CLASS)?.length ?? 0).toBeGreaterThan(0);
+ });
+
+ it("keeps the app's own rules in the product layer", () => {
+ const product = layerBlock(built.css, 'product');
+ expect(product).toContain('11px');
+ expect(product).not.toContain('13px');
+ });
+});
+
describe('a production build resolves defineConsts imported across files', () => {
/** A constant reference StyleX left unsubstituted. */
const PLACEHOLDER = /var\(--(?:astryx|x)[a-z0-9]{4,}\)/;
diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.ts
index 0c17469b35..8678092b42 100644
--- a/packages/build/src/vite.ts
+++ b/packages/build/src/vite.ts
@@ -11,6 +11,15 @@ import {createHash} from 'node:crypto';
import {undefinedGeneratedVariables} from './undefinedVariables';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
+// The CommonJS marker reader the Babel and PostCSS integrations share,
+// loaded on first use from beside babel.js, so every integration runs one copy.
+let markerReader: typeof import('./swizzle-marker.js') | undefined;
+function isSwizzledSource(filePath: string, memo: Map<string, boolean>) {
+ markerReader ??= createRequire(import.meta.url)(
+ path.resolve(__dirname, 'swizzle-marker.js'),
+ ) as typeof import('./swizzle-marker.js');
+ return markerReader.isSwizzledSource(filePath, memo);
+}
const LIBRARY_PATTERN = 'node_modules/@astryxdesign/';
const STYLEX_CSS_PATH = '/virtual:stylex.css';
@@ -356,10 +365,14 @@ function renderSplitLayers(
// their own, so repeating them adds nothing to the output.
const collectedConstants: unknown[] = [];
+ // A swizzled copy is Astryx source too: its rules go in the library layer.
+ const markerMemo = new Map<string, boolean>();
for (const [filePath, rules] of rulesById.entries()) {
- const own = filePath.includes(options.libraryPattern)
- ? libraryRules
- : productRules;
+ const own =
+ filePath.includes(options.libraryPattern) ||
+ isSwizzledSource(filePath, markerMemo)
+ ? libraryRules
+ : productRules;
for (const rule of rules) {
if (isConstantRule(rule)) {
collectedConstants.push(rule);