An open source design system that's fully customizable and agent ready
TypeScript
chore: remove per-component CSS splitting from dist build (#1469)
Cindy Zhangf9437e67d9cc
diff --git a/packages/core/package.json b/packages/core/package.jsonindex ff1a2f0592..5aa2122656 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -523,8 +523,7 @@"lint": "eslint src","typecheck:docs": "tsc --project tsconfig.docs.json","build:css": "node ../../scripts/build-css.mjs",- "inject:css": "node ../../scripts/inject-css-imports.mjs",- "postbuild": "yarn build:css && yarn inject:css && node ../../scripts/fix-use-client-dist.mjs"+ "postbuild": "yarn build:css && node ../../scripts/fix-use-client-dist.mjs"},"peerDependencies": {"react": ">=19.0.0",diff --git a/scripts/build-css.mjs b/scripts/build-css.mjsindex 0efb32198e..2be05d81cf 100644--- a/scripts/build-css.mjs+++ b/scripts/build-css.mjs@@ -1,24 +1,16 @@/*** @file build-css.mjs* Post-build script that extracts StyleX CSS from compiled source files- * and outputs per-component CSS files, a shared common.css, and a combined xds.css,- * all wrapped in @layer xds-base.+ * and outputs a combined xds.css wrapped in @layer xds-base.** Usage: node scripts/build-css.mjs** This script:* 1. Runs Babel with the StyleX plugin over all source files- * 2. Groups CSS rules by component directory- * 3. Identifies shared rules (used by 2+ components) → common.css- * 4. Outputs per-component CSS files with only unique rules- * 5. Outputs a combined xds.css with all rules- * 6. All CSS is wrapped in @layer xds-base { ... }+ * 2. Collects all StyleX rules+ * 3. Outputs a combined xds.css with all rules in @layer xds-base*- * Per-component CSS enables tree-shaking for dist consumers:- * import { Button } from '@xds/core/Button';- * // bundler auto-includes common.css + dist/Button/styles.css- *- * All-in-one CSS for consumers who prefer a single import:+ * Dist consumers import the full stylesheet:* import '@xds/core/xds.css';*/@@ -34,25 +26,6 @@ const ROOT = path.resolve(__dirname, '..');const CORE_SRC = path.resolve(ROOT, 'packages/core/src');const CORE_DIST = path.resolve(ROOT, 'packages/core/dist');-/**- * Determine which component a source file belongs to.- * Returns the component directory name (e.g. "Button") or "_shared"- * for files not in a component directory.- */-function getComponentName(filePath) {- const rel = path.relative(CORE_SRC, filePath);- const parts = rel.split(path.sep);-- if (parts.length === 1) return '_shared';-- const dir = parts[0];- if (dir[0] === dir[0].toUpperCase() && dir[0] !== '_') {- return dir;- }-- return '_shared';-}-async function collectStyleXCSS() {const files = await glob('**/*.{ts,tsx}', {cwd: CORE_SRC,@@ -62,8 +35,6 @@ async function collectStyleXCSS() {console.log(`Processing ${files.length} source files...`);- // Map: componentName -> StyleX rules[]- const componentRules = new Map();const allRules = [];for (const file of files) {@@ -99,14 +70,7 @@ async function collectStyleXCSS() {});if (result?.metadata?.stylex?.length) {- const rules = result.metadata.stylex;- const component = getComponentName(file);-- if (!componentRules.has(component)) {- componentRules.set(component, []);- }- componentRules.get(component).push(...rules);- allRules.push(...rules);+ allRules.push(...result.metadata.stylex);}} catch (err) {console.warn(@@ -115,119 +79,13 @@ async function collectStyleXCSS() {}}- console.log(`Collected ${allRules.length} StyleX rules across ${componentRules.size} groups`);-- return {componentRules, allRules};-}--/**- * Given a list of StyleX rules, produce CSS via the official processor- * and parse it into individual rule entries: { className, rule (full text) }- *- * Handles @media and other at-rule wrappers by preserving them around the- * inner rule. For example:- * @media (prefers-reduced-motion: reduce){.x1{transition-duration:0s}}- * is parsed as a single entry with the full @media wrapper intact.- */-function parseRulesFromCSS(css) {- const entries = [];- let i = 0;-- while (i < css.length) {- // Skip whitespace and newlines- while (i < css.length && /\s/.test(css[i])) i++;- if (i >= css.length) break;-- // Detect at-rules (@media, @keyframes, etc.)- if (css[i] === '@') {- // Find the opening brace of the at-rule- const atStart = i;- const braceIdx = css.indexOf('{', i);- if (braceIdx === -1) break;-- const atPrelude = css.slice(atStart, braceIdx).trim();-- // Skip @keyframes entirely — they aren't component-splittable rules- if (atPrelude.startsWith('@keyframes')) {- // Jump past the balanced braces- i = findClosingBrace(css, braceIdx);- continue;- }-- // For @media and other conditional at-rules, extract inner rules- // and wrap each one with the at-rule prelude- const closeIdx = findClosingBrace(css, braceIdx);- const innerCSS = css.slice(braceIdx + 1, closeIdx - 1);- const innerEntries = parseRulesFromCSS(innerCSS);-- for (const entry of innerEntries) {- entries.push({- className: entry.className,- fullRule: `${atPrelude}{${entry.fullRule}}`,- });- }-- i = closeIdx;- continue;- }-- // Regular rule: .className...{ declarations }- if (css[i] === '.') {- const ruleStart = i;- const braceIdx = css.indexOf('{', i);- if (braceIdx === -1) break;-- const closeIdx = findClosingBrace(css, braceIdx);- const fullRule = css.slice(ruleStart, closeIdx).trim();- const selector = css.slice(ruleStart, braceIdx).trim();- const className = selector.match(/^(\.[a-z][a-z0-9_-]+)/)?.[1];-- if (className) {- entries.push({className, fullRule});- }-- i = closeIdx;- continue;- }-- // Skip anything else (comments, etc.)- i++;- }-- return entries;-}--/**- * Find the index just past the closing brace that matches the opening brace- * at `openIdx`. Handles nested braces.- */-function findClosingBrace(css, openIdx) {- let depth = 1;- let i = openIdx + 1;- while (i < css.length && depth > 0) {- if (css[i] === '{') depth++;- else if (css[i] === '}') depth--;- i++;- }- return i;-}--function wrapInLayer(css, comment) {- if (!css.trim()) return '';- return `/* ${comment} */-/* Auto-generated. Do not edit manually. */+ console.log(`Collected ${allRules.length} StyleX rules`);-@layer xds-base {-${css- .split('\n')- .map(line => ' ' + line)- .join('\n')}-}-`;+ return allRules;}async function main() {- const {componentRules, allRules} = await collectStyleXCSS();+ const allRules = await collectStyleXCSS();if (allRules.length === 0) {console.error('No StyleX rules found!');@@ -236,125 +94,18 @@ async function main() {await fs.mkdir(CORE_DIST, {recursive: true});- // --- Step 1: Process each component's rules to get CSS ---- // We need to identify which CSS classes are shared across components.- // Process each component independently, then compare.- const componentCSS = new Map(); // component -> parsed CSS entries- const classToComponents = new Map(); // className -> Set<component>- const classToRule = new Map(); // className -> full rule text (first seen)-- for (const [component, rules] of componentRules) {- if (component === '_shared' || rules.length === 0) continue;-- const css = stylexBabelPlugin.processStylexRules(rules, false);- if (!css.trim()) continue;-- const entries = parseRulesFromCSS(css);- componentCSS.set(component, entries);-- for (const {className, fullRule} of entries) {- if (!classToComponents.has(className)) {- classToComponents.set(className, new Set());- }- classToComponents.get(className).add(component);-- if (!classToRule.has(className)) {- classToRule.set(className, fullRule);- }- }- }-- // --- Step 2: Identify shared classes (2+ components) ---- const sharedClasses = new Set();- for (const [className, components] of classToComponents) {- if (components.size >= 2) {- sharedClasses.add(className);- }- }-- console.log(`\nShared classes (2+ components): ${sharedClasses.size}`);- console.log(`Unique classes: ${classToComponents.size - sharedClasses.size}`);-- // --- Step 3: Write common.css with shared rules ---- // Use the combined allRules processed output to get correct orderingconst combinedCSS = stylexBabelPlugin.processStylexRules(allRules, false);- const combinedEntries = parseRulesFromCSS(combinedCSS);- const commonRules = combinedEntries- .filter(e => sharedClasses.has(e.className))- .map(e => e.fullRule);-- // Dedupe (same className can appear in multiple @media contexts)- const seenCommon = new Set();- const dedupedCommonRules = commonRules.filter(rule => {- if (seenCommon.has(rule)) return false;- seenCommon.add(rule);- return true;- });-- const commonCSSContent = dedupedCommonRules.join('\n');- const commonPath = path.resolve(CORE_DIST, 'common.css');- await fs.writeFile(- commonPath,- wrapInLayer(commonCSSContent, 'XDS shared styles — auto-imported by components'),- 'utf8',- );- console.log(`Common CSS: ${(commonCSSContent.length / 1024).toFixed(1)} KB (${dedupedCommonRules.length} rules)`);-- // --- Step 4: Write per-component CSS (unique rules only) ---- let componentCount = 0;- const manifest = {};-- for (const [component, entries] of componentCSS) {- // Filter to only rules unique to this component- const uniqueRules = entries- .filter(e => !sharedClasses.has(e.className))- .map(e => e.fullRule);-- const componentDir = path.resolve(CORE_DIST, component);- await fs.mkdir(componentDir, {recursive: true});-- const outPath = path.resolve(componentDir, 'styles.css');-- if (uniqueRules.length === 0) {- // Component only uses shared classes — still write an empty-ish file- // so the import doesn't break- await fs.writeFile(- outPath,- `/* XDS ${component} styles */\n/* All rules for this component are in common.css */\n`,- 'utf8',- );- } else {- // Dedupe within component- const seen = new Set();- const deduped = uniqueRules.filter(rule => {- if (seen.has(rule)) return false;- seen.add(rule);- return true;- });- await fs.writeFile(outPath, wrapInLayer(deduped.join('\n'), `XDS ${component} styles`), 'utf8');- }-- manifest[component] = {total: entries.length, unique: uniqueRules.length};- componentCount++;- }-- console.log(`\nWrote ${componentCount} per-component CSS files`);-- // --- Step 5: Write combined xds.css ---const combinedPath = path.resolve(CORE_DIST, 'xds.css');await fs.writeFile(combinedPath,- wrapInLayer(combinedCSS, 'XDS Pre-compiled StyleX CSS — all components'),+ `/* XDS Pre-compiled StyleX CSS — all components */\n/* Auto-generated. Do not edit manually. */\n\n@layer xds-base {\n${combinedCSS+ .split('\n')+ .map(line => ' ' + line)+ .join('\n')}\n}\n`,'utf8',);- console.log(`Combined: ${(combinedCSS.length / 1024).toFixed(1)} KB`);-- // --- Manifest ---- const manifestLines = Object.entries(manifest)- .sort(([a], [b]) => a.localeCompare(b))- .map(([name, {total, unique}]) => ` ${name}: ${unique} unique / ${total} total`);- console.log(`\nPer-component breakdown:\n${manifestLines.join('\n')}`);+ console.log(`xds.css: ${(combinedCSS.length / 1024).toFixed(1)} KB`);}main().catch(err => {diff --git a/scripts/build-css.test.mjs b/scripts/build-css.test.mjsindex 9a2ed362ac..870feecb50 100644--- a/scripts/build-css.test.mjs+++ b/scripts/build-css.test.mjs@@ -2,14 +2,8 @@* @file build-css.test.mjs* Integration test for build-css.mjs*- * Validates that the CSS splitting pipeline (common.css + per-component styles.css)- * preserves all @media wrappers from the combined xds.css output.- *- * The combined xds.css writes directly from processStylexRules and is always correct.- * common.css and per-component styles.css go through parseRulesFromCSS, which is the- * code under test — a regression in that parser silently stripped @media wrappers,- * causing conditional rules (prefers-reduced-motion, hover, prefers-contrast) to apply- * unconditionally. See #952, #957.+ * Validates that xds.css contains expected @media wrappers and+ * prefers-reduced-motion rules.*/import {describe, it, expect, beforeAll} from 'vitest';@@ -24,21 +18,17 @@ const CORE_DIST = path.resolve(ROOT, 'packages/core/dist');/*** Extract all @media blocks from a CSS string.- * Returns an array of the full @media rule strings.*/function extractMediaRules(css) {const rules = [];let i = 0;while (i < css.length) {- // Find @mediaconst idx = css.indexOf('@media', i);if (idx === -1) break;- // Find the opening braceconst braceStart = css.indexOf('{', idx);if (braceStart === -1) break;- // Balance braces to find the endlet depth = 1;let j = braceStart + 1;while (j < css.length && depth > 0) {@@ -53,90 +43,42 @@ function extractMediaRules(css) {return rules;}-describe('build-css @media preservation', () => {+describe('build-css xds.css', () => {let xdsCss;- let commonCss;- let componentCssFiles;beforeAll(async () => {- // Build core first (build-css needs compiled source)console.log('Running yarn build...');execSync('yarn build', {cwd: ROOT, stdio: 'pipe', timeout: 120_000});-- // Read the outputsxdsCss = await fs.readFile(path.join(CORE_DIST, 'xds.css'), 'utf8');- commonCss = await fs.readFile(path.join(CORE_DIST, 'common.css'), 'utf8');-- // Collect all per-component styles.css files- componentCssFiles = {};- const entries = await fs.readdir(CORE_DIST, {withFileTypes: true});- for (const entry of entries) {- if (entry.isDirectory()) {- const stylesPath = path.join(CORE_DIST, entry.name, 'styles.css');- try {- componentCssFiles[entry.name] = await fs.readFile(stylesPath, 'utf8');- } catch {- // No styles.css for this component — that's fine- }- }- }}, 180_000);- it('xds.css contains @media rules', () => {+ it('contains @media rules', () => {const mediaRules = extractMediaRules(xdsCss);expect(mediaRules.length).toBeGreaterThan(0);console.log(`xds.css has ${mediaRules.length} @media rules`);});- it('combined split CSS has the same @media count as xds.css', () => {- const xdsMedia = extractMediaRules(xdsCss);-- // Collect @media rules from common.css + all per-component files- let splitMedia = extractMediaRules(commonCss);- for (const [name, css] of Object.entries(componentCssFiles)) {- splitMedia = splitMedia.concat(extractMediaRules(css));- }-- console.log(`xds.css @media rules: ${xdsMedia.length}`);- console.log(- `Split CSS @media rules: ${splitMedia.length} (common: ${extractMediaRules(commonCss).length})`,- );-- expect(splitMedia.length).toBe(xdsMedia.length);- });-- it('common.css contains prefers-reduced-motion rules', () => {- const mediaRules = extractMediaRules(commonCss);+ it('contains prefers-reduced-motion rules', () => {+ const mediaRules = extractMediaRules(xdsCss);const motionRules = mediaRules.filter(r =>r.includes('prefers-reduced-motion'),);expect(motionRules.length).toBeGreaterThan(0);- console.log(- `common.css has ${motionRules.length} prefers-reduced-motion rules`,- );+ console.log(`xds.css has ${motionRules.length} prefers-reduced-motion rules`);});it('no transition-duration:0s rules appear outside @media blocks', () => {- // The bug caused rules like .x12w9bfk.x12w9bfk{transition-duration:0s}- // to appear WITHOUT their @media wrapper. Check that any rule with- // transition-duration:0s is inside an @media block.- const allSplitCss =- commonCss + '\n' + Object.values(componentCssFiles).join('\n');-- // Find all transition-duration:0s rulesconst zeroTransitionRegex =/\.[a-z][a-z0-9_-]+[^{}]*\{[^}]*transition-duration:\s*0s[^}]*\}/g;- const matches = [...allSplitCss.matchAll(zeroTransitionRegex)];+ const matches = [...xdsCss.matchAll(zeroTransitionRegex)];for (const match of matches) {const position = match.index;-- // Check if this rule is inside an @media block by looking backwards- const before = allSplitCss.slice(0, position);+ const before = xdsCss.slice(0, position);const mediaStarts = [...before.matchAll(/@media[^{]*\{/g)];const isWrapped = mediaStarts.some(m => {const mediaStart = m.index;- const afterMedia = allSplitCss.slice(mediaStart);+ const afterMedia = xdsCss.slice(mediaStart);let depth = 0;for (let i = 0; i < afterMedia.length; i++) {if (afterMedia[i] === '{') depth++;@@ -160,25 +102,10 @@ describe('build-css @media preservation', () => {}});- it('every @media variant from xds.css exists in split CSS', () => {- const preludeRegex = /@media\s*\([^)]+\)/g;-- const xdsVariants = new Set(- [...xdsCss.matchAll(preludeRegex)].map(m => m[0]),- );- const splitCss =- commonCss + '\n' + Object.values(componentCssFiles).join('\n');- const splitVariants = new Set(- [...splitCss.matchAll(preludeRegex)].map(m => m[0]),- );-- console.log(`xds.css @media variants: ${[...xdsVariants].join(', ')}`);- console.log(- `Split CSS @media variants: ${[...splitVariants].join(', ')}`,- );-- for (const variant of xdsVariants) {- expect(splitVariants.has(variant)).toBe(true);- }+ it('does not produce per-component CSS files', () => {+ // Verify the cleanup — no common.css or per-component styles.css+ expect(+ fs.access(path.join(CORE_DIST, 'common.css')).then(() => true, () => false),+ ).resolves.toBe(false);});});diff --git a/scripts/bundle-analysis.mjs b/scripts/bundle-analysis.mjsindex 01364afed7..69b36c7b95 100644--- a/scripts/bundle-analysis.mjs+++ b/scripts/bundle-analysis.mjs@@ -57,21 +57,20 @@ function buildMap() {for (const n of readdirSync(DIST)) {const e = join(DIST, n, 'index.mjs');if (!existsSync(e)) continue;- const ch = allChunks(e), css = join(DIST, n, 'styles.css');- comps[n] = {entry: gzSize(e), css: existsSync(css) ? gzSize(css) : {raw:0,gzip:0}, chunks: ch};+ const ch = allChunks(e);+ comps[n] = {entry: gzSize(e), chunks: ch};for (const c of ch) { if (!cu[c]) cu[c] = new Set(); cu[c].add(n); }}return {comps, cu};}function measure(names, comps, cu) {- const ac = new Set(); let eG=0,eR=0,cG=0,cR=0; const found=[];+ const ac = new Set(); let eG=0,eR=0; const found=[];for (const n of names) {const comp = comps[n];if (!comp) { console.warn(` \u26a0 "${n}" not found`); continue; }found.push(n);eG += comp.entry.gzip; eR += comp.entry.raw;- cG += comp.css.gzip; cR += comp.css.raw;for (const ch of comp.chunks) ac.add(ch);}const ts = new Set(found), excl = new Set(), shr = new Set();@@ -82,14 +81,14 @@ function measure(names, comps, cu) {let xG=0,xR=0,sG=0,sR=0;for (const c of excl) { const s = gzSize(join(DIST,c)); xG+=s.gzip; xR+=s.raw; }for (const c of shr) { const s = gzSize(join(DIST,c)); sG+=s.gzip; sR+=s.raw; }- const cc = gzSize(join(DIST, 'common.css'));+ const xdsCss = existsSync(join(DIST, 'xds.css')) ? gzSize(join(DIST, 'xds.css')) : {raw:0,gzip:0};return {count: found.length, found,entries: {gzip:eG, raw:eR}, exclusive: {gzip:xG, raw:xR, count:excl.size},- shared: {gzip:sG, raw:sR, count:shr.size}, css: {gzip:cG, raw:cR}, commonCss: cc,- foundation: {gzip:sG+cc.gzip, raw:sR+cc.raw},- incremental: {gzip:eG+xG+cG, raw:eR+xR+cR},- total: {gzip:sG+cc.gzip+eG+xG+cG, raw:sR+cc.raw+eR+xR+cR},+ shared: {gzip:sG, raw:sR, count:shr.size}, xdsCss,+ foundation: {gzip:sG+xdsCss.gzip, raw:sR+xdsCss.raw},+ incremental: {gzip:eG+xG, raw:eR+xR},+ total: {gzip:sG+xdsCss.gzip+eG+xG, raw:sR+xdsCss.raw+eR+xR},};}@@ -106,10 +105,9 @@ function printSet(label, r) {console.log(` Entries: ${pad(fmt(r.entries.gzip),10,'right')} (${r.count} files)`);console.log(` Exclusive chunks: ${pad(fmt(r.exclusive.gzip),10,'right')} (${r.exclusive.count} chunks)`);console.log(` Shared chunks: ${pad(fmt(r.shared.gzip),10,'right')} (${r.shared.count} chunks)`);- console.log(` Component CSS: ${pad(fmt(r.css.gzip),10,'right')}`);- console.log(` common.css: ${pad(fmt(r.commonCss.gzip),10,'right')}`);+ console.log(` xds.css: ${pad(fmt(r.xdsCss.gzip),10,'right')}`);console.log();- console.log(` Foundation: ${pad(fmt(r.foundation.gzip),10,'right')} (shared chunks + common.css)`);+ console.log(` Foundation: ${pad(fmt(r.foundation.gzip),10,'right')} (shared chunks + xds.css)`);console.log(` Incremental: ${pad(fmt(r.incremental.gzip),10,'right')} (entries + exclusive + CSS)`);console.log(` ${'\u2500'.repeat(16)}`);console.log(` Total shipped: ${pad(fmt(r.total.gzip),10,'right')}`);@@ -137,7 +135,7 @@ async function printCompare(mappings, comps, cu) {for (const r of results) {if (!r.xds) continue;const comp = comps[r.xds]; if (!comp) continue;- const x = comp.entry.gzip + comp.css.gzip; xt += x;+ const x = comp.entry.gzip; xt += x;console.log(`${pad(r.xds,20)} ${pad(fmt(x),14,'right')} ${pad(fmt(r.bp.gzip),14,'right')} ${r.bp.name}@${r.bp.version}`);}console.log('-'.repeat(75));@@ -160,15 +158,15 @@ async function printCompare(mappings, comps, cu) {function printFull(comps, cu) {const an = Object.keys(comps).sort();console.log(`${'='.repeat(75)}\nXDS BUNDLE SIZE ANALYSIS\n${'='.repeat(75)}\n`);- console.log(`${pad('Component',22)} ${pad('Entry',8,'right')} ${pad('CSS',8,'right')} ${pad('Chunks',8,'right')} ${pad('Solo',10,'right')} ${pad('#ch',5,'right')}`);- console.log('-'.repeat(75));+ console.log(`${pad('Component',22)} ${pad('Entry',8,'right')} ${pad('Chunks',8,'right')} ${pad('Solo',10,'right')} ${pad('#ch',5,'right')}`);+ console.log('-'.repeat(65));const sorted = an.map(n => {const comp = comps[n]; let cg = 0;for (const ch of comp.chunks) cg += gzSize(join(DIST, ch)).gzip;- return {n, e: comp.entry.gzip, c: comp.css.gzip, cg, solo: comp.entry.gzip + comp.css.gzip + cg, ch: comp.chunks.size};+ return {n, e: comp.entry.gzip, cg, solo: comp.entry.gzip + cg, ch: comp.chunks.size};}).sort((a, b) => b.solo - a.solo);for (const c of sorted)- console.log(`${pad(c.n,22)} ${pad(fmt(c.e),8,'right')} ${pad(fmt(c.c),8,'right')} ${pad(fmt(c.cg),8,'right')} ${pad(fmt(c.solo),10,'right')} ${pad(String(c.ch),5,'right')}`);+ console.log(`${pad(c.n,22)} ${pad(fmt(c.e),8,'right')} ${pad(fmt(c.cg),8,'right')} ${pad(fmt(c.solo),10,'right')} ${pad(String(c.ch),5,'right')}`);const scenarios = [['Small app (5)', ['Button','Text','Dialog','TextInput','Stack']],['Medium app (15)', ['Button','Text','Dialog','TextInput','Stack','Table','DropdownMenu','Selector','TabList','Card','Badge','Avatar','Tooltip','Banner','Spinner']],diff --git a/scripts/inject-css-imports.mjs b/scripts/inject-css-imports.mjsdeleted file mode 100644index ee5331b8d8..0000000000--- a/scripts/inject-css-imports.mjs+++ /dev/null@@ -1,72 +0,0 @@-/**- * @file inject-css-imports.mjs- * Post-build script that adds CSS imports to each component's dist JS- * entry point, enabling automatic CSS tree-shaking.- *- * Injects:- * import '../common.css'; // shared atomic classes- * import './styles.css'; // component-specific classes- *- * Usage: node scripts/inject-css-imports.mjs- *- * Runs after build-css.mjs. The common.css import is deduplicated by- * bundlers — even though every component imports it, the bundler only- * includes it once in the output.- */--import fs from 'fs/promises';-import path from 'path';-import {fileURLToPath} from 'url';--const __dirname = path.dirname(fileURLToPath(import.meta.url));-const ROOT = path.resolve(__dirname, '..');-const CORE_DIST = path.resolve(ROOT, 'packages/core/dist');--async function main() {- const entries = await fs.readdir(CORE_DIST, {withFileTypes: true});- let injected = 0;- let skipped = 0;-- // Verify common.css exists- try {- await fs.access(path.join(CORE_DIST, 'common.css'));- } catch {- console.error('common.css not found in dist — run build-css.mjs first');- process.exit(1);- }-- for (const entry of entries) {- if (!entry.isDirectory()) continue;-- const cssPath = path.join(CORE_DIST, entry.name, 'styles.css');- const mjsPath = path.join(CORE_DIST, entry.name, 'index.mjs');-- // Only inject if both styles.css and index.mjs exist- try {- await fs.access(cssPath);- await fs.access(mjsPath);- } catch {- skipped++;- continue;- }-- const content = await fs.readFile(mjsPath, 'utf8');-- // Don't double-inject- if (content.includes("import '../common.css'")) {- skipped++;- continue;- }-- const imports = `import '../common.css';\nimport './styles.css';\n`;- await fs.writeFile(mjsPath, `${imports}${content}`, 'utf8');- injected++;- }-- console.log(`Injected CSS imports into ${injected} component entry points (${skipped} skipped)`);-}--main().catch(err => {- console.error(err);- process.exit(1);-});