An open source design system that's fully customizable and agent ready
TypeScript
fix(build): own packed consumer dependencies (#6605)
Cindy Zhang09846f097bf3
diff --git a/.changeset/build-packed-consumer-dependencies.md b/.changeset/build-packed-consumer-dependencies.mdnew file mode 100644index 0000000000..9138a79ee1--- /dev/null+++ b/.changeset/build-packed-consumer-dependencies.md@@ -0,0 +1,9 @@+---+'@astryxdesign/build': patch+---++[fix] Keep PostCSS and Vite processing inside `@astryxdesign/build`'s declared dependency boundary++Packed consumers no longer depend on workspace hoisting to find PostCSS helpers or CSS compatibility processors. The package now owns Autoprefixer, Browserslist, and Lightning CSS, and a clean isolated-install test exercises the published tarball's PostCSS helper and Vite output.++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex de4afd4ccd..a68b0597d8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1053,6 +1053,9 @@ jobs:- uses: ./.github/actions/setup+ - name: Verify packed consumer dependency contract+ run: pnpm vitest run packages/build/src/packed-consumer.test.mjs --project node --maxWorkers=1+- name: Install Playwrightrun: npx playwright install chromiumdiff --git a/packages/build/package.json b/packages/build/package.jsonindex 748918fd07..e21eed7b4d 100644--- a/packages/build/package.json+++ b/packages/build/package.json@@ -40,15 +40,18 @@"prepack": "pnpm build"},"peerDependencies": {- "@stylexjs/babel-plugin": ">=0.18.0","@babel/core": ">=7.0.0",+ "@stylexjs/babel-plugin": ">=0.18.0","@stylexjs/unplugin": ">=0.18.0","vite": "catalog:"},"dependencies": {+ "autoprefixer": "^10.5.2",+ "browserslist": "^4.28.4","fast-glob": "^3.3.0","glob-parent": "^6.0.0",- "is-glob": "^4.0.0"+ "is-glob": "^4.0.0",+ "lightningcss": "^1.32.0"},"devDependencies": {"esbuild": "catalog:"diff --git a/packages/build/src/config.js b/packages/build/src/config.jsindex e47e2ecf8b..71e4d3af41 100644--- a/packages/build/src/config.js+++ b/packages/build/src/config.js@@ -1,17 +1,19 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-"use strict";+'use strict';/*** @astryxdesign/build*- * Unified build configuration for Astryx source builds.- *+ * Unified build configuration for Astryx source builds. The complete PostCSS+ * helper resolves its bundled Autoprefixer from this package rather than from+ * the consuming project's dependency graph.+ ** Usage:* // babel.config.js* const {babel} = require('@astryxdesign/build');* module.exports = babel(__dirname);- *+ ** // postcss.config.js* const {postcss} = require('@astryxdesign/build');* module.exports = postcss(__dirname);@@ -51,7 +53,7 @@ function stylexOptions(rootDir, overrides = {}) {/*** Generate a complete babel.config.js for Astryx source builds.- *+ ** @param {string} rootDir — __dirname of the project root* @param {object} [overrides] — extra StyleX options to merge* @returns {object} babel config object@@ -79,7 +81,7 @@ function babel(rootDir, overrides = {}) {/*** Generate a complete postcss.config.js for Astryx source builds.- *+ ** @param {string} rootDir — __dirname of the project root* @param {object} [overrides] — extra options (appDir, extraInclude, etc.)* @returns {object} postcss config object@@ -96,7 +98,7 @@ function postcss(rootDir, overrides = {}) {],extraInclude,},- autoprefixer: {},+ [require.resolve('autoprefixer')]: {},},};}diff --git a/packages/build/src/index.js b/packages/build/src/index.jsindex a34605356b..94dca89405 100644--- a/packages/build/src/index.js+++ b/packages/build/src/index.js@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-"use strict";+'use strict';/*** @astryxdesign/postcss-plugin@@ -12,12 +12,12 @@* reset < astryx-base (library, prefix: 'astryx') < astryx-theme < product (prefix: 'x')** The separate prefixes ensure atomic classes don't collide between- * layers, which would break theme overrides.+ * layers, which would break theme overrides. Generated replacement CSS is+ * parsed by the host PostCSS instance so consumers do not load a second copy.*/const path = require('node:path');const fs = require('node:fs');-const postcss = require('postcss');const babel = require('@babel/core');const stylexBabelPlugin = require('@stylexjs/babel-plugin');const {globSync} = require('fast-glob');@@ -27,7 +27,11 @@ const globParent = require('glob-parent');const PLUGIN_NAME = '@astryxdesign/postcss-plugin';const LIBRARY_GLOB = 'node_modules/@astryxdesign/**/*.{ts,tsx}';-const LIBRARY_PATTERNS = ['node_modules/@astryxdesign/', 'packages/core/', 'packages/themes/'];+const LIBRARY_PATTERNS = [+ 'node_modules/@astryxdesign/',+ 'packages/core/',+ 'packages/themes/',+];const STYLEX_IMPORT_SOURCE = '@stylexjs/stylex';function parseDependency(fileOrGlob, cwd) {@@ -117,7 +121,7 @@ function createPlugin() {const fileName = result.opts.from;let styleXAtRule = null;- root.walkAtRules((atRule) => {+ root.walkAtRules(atRule => {if (atRule.name === 'stylex' && !atRule.params) {styleXAtRule = atRule;}@@ -193,7 +197,7 @@ function createPlugin() {rulesMap.set(filePath, stylex);}})- .catch((error) => {+ .catch(error => {if (shouldSkipTransformError) {console.warn(`[${PLUGIN_NAME}] Failed to transform "${filePath}": ${error.message}`,@@ -231,9 +235,9 @@ function createPlugin() {parts.push(`@layer ${layers.product} {\n${productCss}\n}`);}- const finalCss = parts.join('\n\n');- const parsed = await postcss.parse(finalCss, {from: fileName});- styleXAtRule.replaceWith(parsed);+ // Let the host PostCSS instance parse the replacement so this plugin+ // does not need or load a second copy of PostCSS.+ styleXAtRule.replaceWith(parts.join('\n\n'));result.root = root;if (!shouldSkipTransformError) {diff --git a/packages/build/src/packed-consumer.test.mjs b/packages/build/src/packed-consumer.test.mjsnew file mode 100644index 0000000000..3248fe353c--- /dev/null+++ b/packages/build/src/packed-consumer.test.mjs@@ -0,0 +1,186 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file packed-consumer.test.mjs+ * @input Packs @astryxdesign/build, reconstructs only the dependencies declared+ * by its tarball, and exercises the public PostCSS helper and Vite plugin+ * @output Proves shipped build integrations need no ambient workspace packages+ * and preserve generated browser compatibility CSS+ * @position Consumer-package regression for @astryxdesign/build+ */++import {execFileSync} from 'node:child_process';+import {+ mkdtempSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import {tmpdir} from 'node:os';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const packageDir = path.resolve(__dirname, '..');+const repoRoot = path.resolve(packageDir, '../..');++function run(command, args, cwd) {+ try {+ return execFileSync(command, args, {+ cwd,+ encoding: 'utf8',+ env: {...process.env, NODE_PATH: undefined},+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ } catch (error) {+ const stdout = error.stdout?.toString() || '';+ const stderr = error.stderr?.toString() || '';+ throw new Error(+ `${command} ${args.join(' ')} failed in ${cwd}\n${stdout}${stderr}`,+ {cause: error},+ );+ }+}++function linkPackage(sourceRoot, name, targetRoot) {+ const source = realpathSync(path.join(sourceRoot, 'node_modules', name));+ const target = path.join(targetRoot, 'node_modules', name);+ mkdirSync(path.dirname(target), {recursive: true});+ symlinkSync(source, target, 'junction');+}++describe('the packed @astryxdesign/build consumer contract', () => {+ let root;+ let appDir;+ let packedPackageDir;++ beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'astryx-build-consumer-'));+ const packDir = path.join(root, 'pack');+ appDir = path.join(root, 'app');+ packedPackageDir = path.join(root, 'packed-build');+ mkdirSync(packDir);+ mkdirSync(path.join(appDir, 'node_modules/@astryxdesign'), {+ recursive: true,+ });+ mkdirSync(path.join(appDir, 'src'), {recursive: true});+ mkdirSync(packedPackageDir);++ run('pnpm', ['pack', '--pack-destination', packDir], packageDir);+ const tarball = path.join(+ packDir,+ readdirSync(packDir).find(name => name.endsWith('.tgz')),+ );+ run(+ 'tar',+ ['-xzf', tarball, '-C', packedPackageDir, '--strip-components=1'],+ root,+ );++ const manifest = JSON.parse(+ readFileSync(path.join(packedPackageDir, 'package.json'), 'utf8'),+ );+ // Recreate strict dependency visibility from the packed manifest rather+ // than letting the monorepo's hoisted packages satisfy missing entries.+ for (const dependency of Object.keys(manifest.dependencies || {})) {+ linkPackage(packageDir, dependency, packedPackageDir);+ }+ for (const peer of Object.keys(manifest.peerDependencies || {})) {+ linkPackage(packageDir, peer, packedPackageDir);+ linkPackage(packageDir, peer, appDir);+ }++ symlinkSync(+ packedPackageDir,+ path.join(appDir, 'node_modules/@astryxdesign/build'),+ 'junction',+ );+ const virtualStoreRoot = path.join(repoRoot, 'node_modules/.pnpm');+ linkPackage(virtualStoreRoot, 'postcss', appDir);+ linkPackage(virtualStoreRoot, '@stylexjs/stylex', appDir);++ writeFileSync(+ path.join(appDir, 'package.json'),+ JSON.stringify({+ name: 'astryx-build-consumer-contract',+ private: true,+ type: 'module',+ }),+ );+ writeFileSync(+ path.join(appDir, 'index.html'),+ '<!doctype html><html><body><script type="module" src="/src/main.js"></script></body></html>\n',+ );+ writeFileSync(+ path.join(appDir, 'src/main.js'),+ [+ "import * as stylex from '@stylexjs/stylex';",+ "const styles = stylex.create({item: {userSelect: 'none'}});",+ 'document.body.className = stylex.props(styles.item).className;',+ '',+ ].join('\n'),+ );+ writeFileSync(+ path.join(appDir, 'vite.config.mjs'),+ [+ "import {astryxStylex} from '@astryxdesign/build/vite';",+ 'export default {plugins: [...astryxStylex({rootDir: process.cwd()})]};',+ '',+ ].join('\n'),+ );+ writeFileSync(+ path.join(appDir, 'check-postcss.cjs'),+ [+ "const path = require('node:path');",+ "const postcss = require('postcss');",+ "const {postcss: buildPostcss} = require('@astryxdesign/build');",+ "for (const dependency of ['autoprefixer', 'browserslist', 'lightningcss']) {",+ ' try {',+ ' require.resolve(dependency);',+ ' throw new Error(`${dependency} leaked into the consumer root`);',+ ' } catch (error) {',+ " if (error.code !== 'MODULE_NOT_FOUND') throw error;",+ ' }',+ '}',+ 'const config = buildPostcss(__dirname);',+ 'const plugins = Object.entries(config.plugins).map(([id, options]) => {',+ ' if (!path.isAbsolute(id)) throw new Error(`unowned PostCSS plugin: ${id}`);',+ ' return require(id)(options);',+ '});',+ "postcss(plugins).process('@stylex;', {from: 'input.css'}).then(() => {",+ " process.stdout.write('postcss-ok\\n');",+ '});',+ '',+ ].join('\n'),+ );+ }, 120_000);++ afterAll(() => {+ if (root) rmSync(root, {recursive: true, force: true});+ });++ it('loads the public PostCSS helper without undeclared consumer packages', () => {+ expect(run(process.execPath, ['check-postcss.cjs'], appDir)).toBe(+ 'postcss-ok\n',+ );+ });++ it('keeps the Vite compatibility pass inside the package boundary', () => {+ const viteCli = path.join(+ packedPackageDir,+ 'node_modules/vite/bin/vite.js',+ );+ run(process.execPath, [viteCli, 'build'], appDir);+ const assetsDir = path.join(appDir, 'dist/assets');+ const cssFile = readdirSync(assetsDir).find(name => name.endsWith('.css'));+ expect(cssFile).toBeDefined();+ expect(readFileSync(path.join(assetsDir, cssFile), 'utf8')).toContain(+ '-webkit-user-select',+ );+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ed96dec930..5d03fc0357 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -674,6 +674,12 @@ importers:'@stylexjs/unplugin':specifier: '>=0.18.0'version: 0.19.0([email protected]([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])))+ autoprefixer:+ specifier: ^10.5.2+ version: 10.5.2([email protected])+ browserslist:+ specifier: ^4.28.4+ version: 4.28.4fast-glob:specifier: ^3.3.0version: 3.3.3@@ -683,6 +689,9 @@ importers:is-glob:specifier: ^4.0.0version: 4.0.3+ lightningcss:+ specifier: ^1.32.0+ version: 1.32.0vite:specifier: 'catalog:'version: 8.1.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])