Skip to content

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

TypeScript

refactor(build): build the prebuilt stylesheets through the source build's walk (#9673)

Christopher Chedeau5f44b1c14082
diff --git a/.changeset/the-prebuilt-stylesheet-build-and-the-turbopack--cfev.md b/.changeset/the-prebuilt-stylesheet-build-and-the-turbopack--cfev.md
new file mode 100644
index 0000000000..b722f8cf54
--- /dev/null
+++ b/.changeset/the-prebuilt-stylesheet-build-and-the-turbopack--cfev.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/build': patch
+---
+
+[chore] The prebuilt stylesheet build and the Turbopack source build share one module walk, compile and layer block, so a source build prints the prebuilt rules by construction. Every prebuilt stylesheet keeps its bytes.
+@vjeux
diff --git a/packages/build/src/source-stylesheet.js b/packages/build/src/source-stylesheet.js
index ce765fd705..73c99fe954 100644
--- a/packages/build/src/source-stylesheet.js
+++ b/packages/build/src/source-stylesheet.js
@@ -5,11 +5,10 @@
/**
* @astryxdesign/build: source stylesheets. A source build of a package's
* modules prints its prebuilt stylesheet's rules, selectors and order. It
- * prints them in one `@layer astryx-base` after the layer order.
- * `stylexOptions()` holds the options the prebuilt stylesheets use
- * (scripts/build-css.mjs), `packageModules()` the module set, and
- * `renderPackage()` prints it. The bundler compiles the same modules with the
- * same options (turbopack-loader.js), so rendered class names match the rules.
+ * prints them in one `@layer astryx-base` after the layer order. The walk,
+ * the compile options and the layer block here also build the prebuilt
+ * stylesheets (scripts/build-css.mjs). The bundler compiles the same modules
+ * with the same options (turbopack-loader.js), so class names match the rules.
*/
const fs = require('node:fs');
@@ -54,10 +53,9 @@ const PREBUILT_STYLESHEETS = {
/**
* Variable modules a prebuilt stylesheet compiles though none of the package's
- * modules imports them: scripts/build-css.mjs's `stylexEntries`. Core's public
- * `dataVars` entry is one, since an app reads its defaults as plain `var()`
- * references. The parity test, whose reference comes from that script's own
- * targets, fails if this list drifts from it.
+ * modules imports them. Core's public `dataVars` entry is one, since an app
+ * reads its defaults as plain `var()` references. The targets of
+ * scripts/build-css.mjs take their `stylexEntries` from this list.
*/
const STYLEX_ENTRIES = {[CORE]: ['theme/dataTokens.stylex.ts']};
@@ -128,25 +126,35 @@ function prebuiltStylesheet(pkg) {
}
/**
- * The StyleX options the prebuilt stylesheets are compiled with: the default
+ * The StyleX options every prebuilt stylesheet is compiled with: the default
* `x` class-name prefix, no development class names and StyleX's default
- * property validation. Plain JSON, since Turbopack passes only serializable
- * loader options: `pluginOptions()` adds the resolution's functions.
+ * property validation.
+ */
+const PREBUILT_OPTIONS = {
+ dev: false,
+ runtimeInjection: false,
+ genConditionalClasses: true,
+ treeshakeCompensation: true,
+};
+
+/** The aliases that point another package's imports of Core at Core's source. */
+function coreAliases(srcDir) {
+ return {
+ '@astryxdesign/core/*': [path.join(srcDir, '*')],
+ '@astryxdesign/core': [srcDir],
+ };
+}
+
+/**
+ * An installed package's StyleX options. They are plain JSON, since Turbopack
+ * passes only serializable loader options. `pluginOptions()` adds the
+ * resolution's functions.
*/
function stylexOptions(pkg, packages) {
const core = packages.find(candidate => candidate.name === CORE);
return {
- dev: false,
- runtimeInjection: false,
- genConditionalClasses: true,
- treeshakeCompensation: true,
- aliases:
- pkg.name === CORE || core == null
- ? {}
- : {
- '@astryxdesign/core/*': [path.join(core.srcDir, '*')],
- '@astryxdesign/core': [core.srcDir],
- },
+ ...PREBUILT_OPTIONS,
+ aliases: pkg.name === CORE || core == null ? {} : coreAliases(core.srcDir),
unstable_moduleResolution: {type: 'custom', rootDir: pkg.dir},
};
}
@@ -166,6 +174,13 @@ const UNRESOLVED = new Set([
* `<package name>:<path inside it>`, so Core's names do not change.
*/
function pluginOptions(options) {
+ // The prebuilt build passes the resolver the packages' JavaScript builds use.
+ // Keep it, so CSS and JavaScript name each variable the same way.
+ if (
+ typeof options.unstable_moduleResolution.filePathResolver === 'function'
+ ) {
+ return options;
+ }
const {rootDir} = options.unstable_moduleResolution;
let packages;
const owner = request =>
@@ -265,33 +280,26 @@ function resolveStyleXImport(specifier, importer, aliases) {
}
/**
- * The modules a package's prebuilt stylesheet is compiled from, walked as
- * scripts/build-css.mjs walks them. That is every source file except tests and
- * `.stylex` modules, plus the package's `STYLEX_ENTRIES`. The walk adds the
- * variable modules they import, minus those a provider's stylesheet already
- * emits. It adds the provided modules the package imports to `imported`. The
- * parity test in source-stylesheet.test.mjs fails if this drifts from
- * scripts/build-css.mjs.
+ * The modules a stylesheet is compiled from. The walk starts at every source
+ * file under `srcDir` except tests and `.stylex` modules, plus `entries`. It
+ * follows static `.stylex` imports, through `aliases`. A module in `provided`
+ * belongs to another stylesheet. The walk adds each one it reaches to
+ * `imported`.
*/
-function packageModules(
- pkg,
- packages,
+function reachableModules(
+ {srcDir, aliases, entries = []},
provided = new Set(),
imported = new Set(),
) {
- const {aliases} = stylexOptions(pkg, packages);
const queue = [
...globSync('**/*.{ts,tsx}', {
- cwd: pkg.srcDir,
+ cwd: srcDir,
absolute: true,
ignore: ['**/*.test.*', '**/*.d.ts', '**/node_modules/**'],
})
.map(file => path.normalize(file))
.filter(file => !STYLEX_MODULE.test(file)),
- // A version older than an entry has none of it to print.
- ...(STYLEX_ENTRIES[pkg.name] ?? [])
- .map(entry => path.join(pkg.srcDir, entry))
- .filter(file => fs.existsSync(file)),
+ ...entries,
].filter(file => !provided.has(file));
const modules = new Set();
while (queue.length > 0) {
@@ -314,20 +322,32 @@ function packageModules(
return modules;
}
+function packageWalk(pkg, packages) {
+ return {
+ srcDir: pkg.srcDir,
+ aliases: stylexOptions(pkg, packages).aliases,
+ // A version older than an entry has none of it to print.
+ entries: (STYLEX_ENTRIES[pkg.name] ?? [])
+ .map(entry => path.join(pkg.srcDir, entry))
+ .filter(file => fs.existsSync(file)),
+ };
+}
+
+function packageModules(pkg, packages, provided, imported) {
+ return reachableModules(packageWalk(pkg, packages), provided, imported);
+}
+
/** A `defineConsts` value, as StyleX collects it: no CSS of its own. */
const isConstant = rule =>
rule[1]?.constKey != null && rule[1]?.constVal != null;
/**
- * Every rule of a package's prebuilt stylesheet, collected as
- * scripts/build-css.mjs collects them. That is its modules' rules, plus the
- * constants it reads from a provider's modules. Those constants resolve where
- * they are read.
+ * Every rule of a stylesheet: its modules' rules, plus the constants it reads
+ * from provided modules. Those constants resolve where they are read.
*/
-async function packageRules(pkg, packages, provided) {
- const options = stylexOptions(pkg, packages);
+async function collectRules(walk, provided, options) {
const imported = new Set();
- const modules = packageModules(pkg, packages, provided, imported);
+ const modules = reachableModules(walk, provided, imported);
const rules = [];
for (const file of modules) {
rules.push(...(await compileRules(file, options)));
@@ -338,6 +358,14 @@ async function packageRules(pkg, packages, provided) {
return {modules, rules};
}
+function packageRules(pkg, packages, provided) {
+ return collectRules(
+ packageWalk(pkg, packages),
+ provided,
+ stylexOptions(pkg, packages),
+ );
+}
+
const compiled = new Map();
function stamp(file) {
@@ -345,9 +373,22 @@ function stamp(file) {
return `${stat.mtimeMs}:${stat.size}`;
}
+// `JSON.stringify` drops a resolver's functions, so each resolver object a
+// caller sets gets an id in the cache key.
+const resolverIds = new WeakMap();
+let nextResolverId = 0;
+
+function resolverKey({unstable_moduleResolution: resolution}) {
+ if (typeof resolution?.filePathResolver !== 'function') return '';
+ if (!resolverIds.has(resolution)) {
+ resolverIds.set(resolution, nextResolverId++);
+ }
+ return `:${resolverIds.get(resolution)}`;
+}
+
/** One module's StyleX rules, cached on its modification stamp. */
async function compileRules(file, options) {
- const key = `${stamp(file)}:${JSON.stringify(options)}`;
+ const key = `${stamp(file)}:${JSON.stringify(options)}${resolverKey(options)}`;
if (compiled.get(file)?.key === key) {
return compiled.get(file).rules;
}
@@ -368,23 +409,31 @@ async function compileRules(file, options) {
return rules;
}
-/**
- * The cascade-layer order every Astryx stylesheet registers before its rules,
- * the line scripts/build-css.mjs writes into each prebuilt stylesheet.
- */
+/** The cascade-layer order every Astryx stylesheet registers before its rules. */
const LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';
+/** A stylesheet's block: the layer order, then `css` inside `@layer astryx-base`. */
+function layerBlock(css) {
+ const body = css
+ .split('\n')
+ .map(line => ` ${line}`)
+ .join('\n');
+ return `${LAYER_ORDER}\n\n@layer astryx-base {\n${body}\n}\n`;
+}
+
+/** StyleX's CSS for `rules`, from the copy of StyleX that compiled them. */
+function processRules(rules) {
+ return stylexBabelPlugin().processStylexRules(rules, false);
+}
+
/**
- * Print a package's rules as its prebuilt stylesheet prints them. Print the
- * layer order, then StyleX's output inside one `@layer astryx-base`. Print
- * nothing when there are no rules. Each block carries the order, so the order
- * holds whichever block or chunk loads first. The product needs no line of its
- * own.
+ * Print a package's rules as its prebuilt stylesheet prints them, or nothing
+ * when there are no rules. Each block carries the order, so the order holds
+ * whichever block or chunk loads first. The product needs no line of its own.
*/
function renderPackage(rules) {
- const css = stylexBabelPlugin().processStylexRules(rules, false);
- if (!css.trim()) return '';
- return `${LAYER_ORDER}\n\n@layer astryx-base {\n${css.replace(/^/gm, ' ')}\n}\n`;
+ const css = processRules(rules);
+ return css.trim() ? layerBlock(css) : '';
}
/**
@@ -411,13 +460,22 @@ module.exports = {
ASTRYX_PACKAGES,
SOURCE_PACKAGES,
PREBUILT_STYLESHEETS,
+ PREBUILT_OPTIONS,
+ STYLEX_ENTRIES,
+ STYLEX_MODULE,
+ LAYER_ORDER,
prebuiltStylesheet,
findPackageDir,
sourcePackages,
+ coreAliases,
stylexOptions,
pluginOptions,
+ reachableModules,
packageModules,
+ collectRules,
compileRules,
+ processRules,
+ layerBlock,
renderPackage,
resolveStyleXImport,
sourceStylesheet,
diff --git a/packages/build/src/source-stylesheet.test.mjs b/packages/build/src/source-stylesheet.test.mjs
index d93a33d0ac..491e8df206 100644
--- a/packages/build/src/source-stylesheet.test.mjs
+++ b/packages/build/src/source-stylesheet.test.mjs
@@ -19,6 +19,7 @@ import {fileURLToPath, pathToFileURL} from 'node:url';
const require = createRequire(import.meta.url);
const {
+ PREBUILT_OPTIONS,
compileRules,
pluginOptions,
resolveStyleXImport,
@@ -139,6 +140,43 @@ describe('a source build against the prebuilt stylesheets', () => {
});
describe('reading packages and resolving imports', () => {
+ it('compiles a module again for another resolver the caller sets', async () => {
+ const dir = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-resolver-')),
+ );
+ try {
+ fs.writeFileSync(
+ path.join(dir, 'tokens.stylex.ts'),
+ "import * as stylex from '@stylexjs/stylex';\nexport const tokens = stylex.defineVars({gap: '4px'});\n",
+ );
+ const file = path.join(dir, 'Box.ts');
+ fs.writeFileSync(
+ file,
+ "import * as stylex from '@stylexjs/stylex';\nimport {tokens} from './tokens.stylex';\nexport const styles = stylex.create({box: {gap: tokens.gap}});\n",
+ );
+ const calls = [];
+ const options = name => ({
+ ...PREBUILT_OPTIONS,
+ aliases: {},
+ unstable_moduleResolution: {
+ type: 'custom',
+ filePathResolver: (request, importer) => {
+ calls.push(name);
+ return path.resolve(path.dirname(importer), `${request}.ts`);
+ },
+ getCanonicalFilePath: target => path.relative(dir, target),
+ },
+ });
+ await compileRules(file, options('first'));
+ await compileRules(file, options('second'));
+ // Present first: the first resolver ran.
+ expect(calls).toContain('first');
+ expect(calls).toContain('second');
+ } finally {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+ });
+
it('matches an alias key without a wildcard only exactly', () => {
const dir = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-alias-')),
diff --git a/scripts/api-report/cli.mjs b/scripts/api-report/cli.mjs
index ef1982deab..a41ce11aea 100644
--- a/scripts/api-report/cli.mjs
+++ b/scripts/api-report/cli.mjs
@@ -158,6 +158,7 @@ export const SHARED_INPUTS = [
'tsconfig.json',
'pnpm-lock.yaml',
'scripts/build-css.mjs',
+ 'packages/build/src/source-stylesheet.js',
'scripts/stylex-module-resolution.cjs',
'scripts/add-declaration-extensions.mjs',
];
diff --git a/scripts/build-css.mjs b/scripts/build-css.mjs
index 45102dc824..0b49f7b68c 100644
--- a/scripts/build-css.mjs
+++ b/scripts/build-css.mjs
@@ -22,24 +22,39 @@
* import '@astryxdesign/lab/lab.css';
*/
-import {transformAsync} from '@babel/core';
-import stylexBabelPlugin from '@stylexjs/babel-plugin';
import stylexResolution from './stylex-module-resolution.cjs';
import {STYLEX_GENERATED_VARIABLE} from './lib/stylex-generated-variable.mjs';
import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
-import {glob} from 'glob';
+
+// The walk, the compile options and the layer block come from the source build
+// of @astryxdesign/build. So both builds print the same stylesheet.
+const {
+ PREBUILT_OPTIONS,
+ STYLEX_ENTRIES,
+ STYLEX_MODULE,
+ LAYER_ORDER,
+ coreAliases,
+ reachableModules,
+ collectRules,
+ processRules,
+ layerBlock,
+} = createRequire(import.meta.url)(
+ '../packages/build/src/source-stylesheet.js',
+);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
+const CORE_SRC = path.resolve(ROOT, 'packages/core/src');
// Per-package build targets. Each entry defines where source lives, where the
// stylesheet is written, and any StyleX module-resolution aliases needed for
// cross-package theme-token imports (lab consumes @astryxdesign/core tokens).
export const TARGETS = {
core: {
- src: path.resolve(ROOT, 'packages/core/src'),
+ src: CORE_SRC,
dist: path.resolve(ROOT, 'packages/core/dist'),
outFile: 'astryx.css',
banner: 'Astryx Pre-compiled StyleX CSS — all components',
@@ -47,7 +62,7 @@ export const TARGETS = {
// The public dist dataVars entry is already compiled to var() references.
// Dist consumers cannot retain its defineVars call, so astryx.css provides
// this group even without a Core component import (spec:AST-066 FR3).
- stylexEntries: ['theme/dataTokens.stylex.ts'],
+ stylexEntries: STYLEX_ENTRIES['@astryxdesign/core'],
},
lab: {
src: path.resolve(ROOT, 'packages/lab/src'),
@@ -56,10 +71,7 @@ export const TARGETS = {
banner: 'Astryx Lab Pre-compiled StyleX CSS — experimental components',
// lab imports @astryxdesign/core/theme/tokens.stylex; point the resolver at
// core's source so the cross-package token reference resolves.
- aliases: {
- '@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],
- '@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],
- },
+ aliases: coreAliases(CORE_SRC),
// astryx.css always loads with this stylesheet, so a Core variable group
// it already declares is not repeated here.
provider: 'core',
@@ -72,10 +84,7 @@ export const TARGETS = {
'Astryx Charts Pre-compiled StyleX CSS — data visualization components',
// charts imports @astryxdesign/core/theme/tokens.stylex; point the resolver
// at core's source so the cross-package token reference resolves.
- aliases: {
- '@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],
- '@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],
- },
+ aliases: coreAliases(CORE_SRC),
// astryx.css always loads with this stylesheet, so a Core variable group
// it already declares is not repeated here.
provider: 'core',
@@ -88,10 +97,7 @@ export const TARGETS = {
'Astryx Rich Text Pre-compiled StyleX CSS — Lexical editor and viewer',
// richtext imports @astryxdesign/core/theme/tokens.stylex; point the
// resolver at core's source so the cross-package token reference resolves.
- aliases: {
- '@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],
- '@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],
- },
+ aliases: coreAliases(CORE_SRC),
// astryx.css always loads with this stylesheet, so a Core variable group
// it already declares is not repeated here.
provider: 'core',
@@ -115,237 +121,38 @@ function parseTarget() {
};
}
-function staticStyleXImports(source) {
- const specifiers = [];
- const pattern =
- /\b(?:import|export)\s+([^'";]*?\sfrom\s*)?['"]([^'"]+\.stylex)['"]/g;
- for (const match of source.matchAll(pattern)) {
- const clause = (match[1] ?? '').replace(/\s+from\s*$/, '').trim();
- if (/^type(?:\s|\*|\{)/.test(clause)) {
- continue;
- }
-
- // TypeScript also permits `import {type Foo}` and
- // `export {type Foo}`. Keep a mixed list when any runtime binding remains,
- // but do not make an all-type list retain a variable module.
- const named = /^\{([^}]*)\}$/.exec(clause);
- if (
- named &&
- named[1]
- .split(',')
- .map(specifier => specifier.trim())
- .filter(Boolean)
- .every(specifier => /^type\b/.test(specifier))
- ) {
- continue;
- }
-
- specifiers.push(match[2]);
- }
- return specifiers;
-}
-
-async function firstExistingModule(basePath) {
- const candidates = [
- basePath,
- `${basePath}.ts`,
- `${basePath}.tsx`,
- `${basePath}.js`,
- `${basePath}.mjs`,
- path.join(basePath, 'index.ts'),
- path.join(basePath, 'index.tsx'),
- ];
- for (const candidate of candidates) {
- try {
- const stat = await fs.stat(candidate);
- if (stat.isFile()) {
- return candidate;
- }
- } catch {
- // Try the next supported source spelling.
- }
- }
- return null;
-}
-
-async function resolveStyleXImport(specifier, importer, aliases) {
- if (specifier.startsWith('.')) {
- return firstExistingModule(path.resolve(path.dirname(importer), specifier));
- }
-
- for (const [pattern, replacements] of Object.entries(aliases)) {
- const wildcard = pattern.indexOf('*');
- const prefix = wildcard === -1 ? pattern : pattern.slice(0, wildcard);
- const suffix = wildcard === -1 ? '' : pattern.slice(wildcard + 1);
- if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
- continue;
- }
- const matched = specifier.slice(
- prefix.length,
- suffix ? -suffix.length : undefined,
- );
- for (const replacement of replacements) {
- const candidate = replacement.replace('*', matched);
- const resolved = await firstExistingModule(candidate);
- if (resolved) {
- return resolved;
- }
- }
- }
- return null;
-}
-
-const STYLEX_MODULE = /\.stylex\.[cm]?[jt]sx?$/;
-
-/**
- * Walks a package from its all-component entry set through static `.stylex`
- * imports. Non-StyleX source files and explicitly retained distribution modules
- * are the entries; other variable modules join only through reachable imports.
- * This keeps source-like graphs selective without omitting Core's public dist
- * defaults. Modules in `provided` are left to the stylesheet that emits them;
- * the ones this package imports are added to `providedImports`.
- */
-async function reachableSourceFiles(
- target,
- provided = new Set(),
- providedImports = new Set(),
-) {
- const files = await glob('**/*.{ts,tsx}', {
- cwd: target.src,
- absolute: true,
- ignore: ['**/*.test.*', '**/*.d.ts', '**/node_modules/**'],
- });
-
- const queue = [
- ...files.filter(file => !STYLEX_MODULE.test(file)),
- ...(target.stylexEntries ?? []).map(entry =>
+/** A target's walk: its source, aliases and explicit distribution modules. */
+function walkOf(target) {
+ return {
+ srcDir: target.src,
+ aliases: target.aliases,
+ entries: (target.stylexEntries ?? []).map(entry =>
path.resolve(target.src, entry),
),
- ].filter(file => !provided.has(file));
- const reachable = new Map();
-
- while (queue.length > 0) {
- const file = queue.shift();
- if (reachable.has(file)) {
- continue;
- }
-
- const code = await fs.readFile(file, 'utf8');
- reachable.set(file, code);
- for (const specifier of staticStyleXImports(code)) {
- const dependency = await resolveStyleXImport(
- specifier,
- file,
- target.aliases,
- );
- if (!dependency) {
- throw new Error(
- `Could not resolve StyleX dependency "${specifier}" from ${path.relative(ROOT, file)}`,
- );
- }
- if (!provided.has(dependency)) {
- queue.push(dependency);
- } else {
- providedImports.add(dependency);
- }
- }
- }
- return reachable;
-}
-
-/**
- * The variable modules a provider package's own stylesheet emits. A satellite
- * package that imports one of them relies on that stylesheet instead of
- * declaring the same group a second time.
- */
-async function providedStyleXModules(provider) {
- if (!provider) {
- return new Set();
- }
- const reachable = await reachableSourceFiles(provider);
- return new Set(
- [...reachable.keys()].filter(file => STYLEX_MODULE.test(file)),
- );
-}
-
-/** A `defineConsts` value as StyleX collects it: a rule with `constKey`/`constVal`. */
-function isConstantRule(rule) {
- const body = Array.isArray(rule) ? rule[1] : undefined;
- return body?.constKey != null && body?.constVal != null;
+ };
}
export async function collectStyleXCSS(target) {
- const provided = await providedStyleXModules(target.provider);
- const providedImports = new Set();
- const reachable = await reachableSourceFiles(
- target,
- provided,
- providedImports,
- );
- const allRules = [];
-
- console.log(`Processing ${reachable.size} reachable source files...`);
-
- for (const [file, code] of reachable) {
- if (!code.includes('@stylexjs/stylex')) {
- continue;
- }
- allRules.push(...(await compileStyleX(file, code, target)));
- }
-
- // A constant read from a provider's module as a value (lab reading a core
- // motion duration) compiles to a placeholder that only the constant's own
- // rule resolves, and a constant is inlined where it is read; at-rule keys
- // stay literal. So the constants of
- // every provided module this package imports join its rules (they emit no
- // CSS); the module's variables stay in the provider's stylesheet.
- for (const file of providedImports) {
- const rules = await compileStyleX(
- file,
- await fs.readFile(file, 'utf8'),
- target,
- );
- allRules.push(...rules.filter(isConstantRule));
- }
-
+ // A satellite leaves the variable modules its provider emits to the
+ // provider's stylesheet.
+ const provided = target.provider
+ ? new Set(
+ [...reachableModules(walkOf(target.provider))].filter(file =>
+ STYLEX_MODULE.test(file),
+ ),
+ )
+ : new Set();
+ const {modules, rules} = await collectRules(walkOf(target), provided, {
+ ...PREBUILT_OPTIONS,
+ aliases: target.aliases,
+ // The packages' JavaScript builds name StyleX variables with this
+ // resolution too.
+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,
+ });
console.log(
- `Collected ${allRules.length} StyleX rules from ${reachable.size} reachable files`,
+ `Collected ${rules.length} StyleX rules from ${modules.size} reachable files`,
);
- return allRules;
-}
-
-/** One file's StyleX rules, compiled as every package stylesheet compiles them. */
-async function compileStyleX(file, code, target) {
- try {
- const result = await transformAsync(code, {
- babelrc: false,
- filename: file,
- presets: [
- ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],
- ['@babel/preset-react', {runtime: 'automatic'}],
- ],
- plugins: [
- [
- stylexBabelPlugin,
- {
- dev: false,
- runtimeInjection: false,
- genConditionalClasses: true,
- treeshakeCompensation: true,
- aliases: target.aliases,
- unstable_moduleResolution: stylexResolution.stylexModuleResolution,
- },
- ],
- ],
- });
-
- return result?.metadata?.stylex ?? [];
- } catch (err) {
- throw new Error(
- `Could not process ${path.relative(ROOT, file)}: ${err.message}`,
- {cause: err},
- );
- }
+ return rules;
}
/**
@@ -354,18 +161,14 @@ async function compileStyleX(file, code, target) {
* (spec:AST-066 FR7). Registering it in each file keeps
* `reset < astryx-base < astryx-theme` whichever Astryx stylesheet loads first.
*/
-export const ASTRYX_LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';
+export const ASTRYX_LAYER_ORDER = LAYER_ORDER;
/**
* Wrap a package's compiled StyleX rules as its prebuilt stylesheet: a banner,
* the layer-order registration, then every rule inside `@layer astryx-base`.
*/
export function composePackageStylesheet(banner, css) {
- const body = css
- .split('\n')
- .map(line => ' ' + line)
- .join('\n');
- return `/* ${banner} */\n/* Auto-generated. Do not edit manually. */\n\n${ASTRYX_LAYER_ORDER}\n\n@layer astryx-base {\n${body}\n}\n`;
+ return `/* ${banner} */\n/* Auto-generated. Do not edit manually. */\n\n${layerBlock(css)}`;
}
/**
@@ -435,7 +238,7 @@ async function main() {
await fs.mkdir(target.dist, {recursive: true});
- const combinedCSS = stylexBabelPlugin.processStylexRules(allRules, false);
+ const combinedCSS = processRules(allRules);
const providerCss = target.provider
? await readProviderCss(target.provider)