An open source design system that's fully customizable and agent ready
TypeScript
fix(build): refuse a Turbopack config in withAstryx instead of building unstyled (#6109)
João Doria de Souza83a74f622901
diff --git a/.changeset/refuse-turbopack-in-with-astryx.md b/.changeset/refuse-turbopack-in-with-astryx.mdnew file mode 100644index 0000000000..5ae403cf5d--- /dev/null+++ b/.changeset/refuse-turbopack-in-with-astryx.md@@ -0,0 +1,6 @@+---+'@astryxdesign/build': patch+---++[fix] `withAstryx()` refuses a Turbopack config instead of building an unstyled app. Every alias the helper installs lives in `nextConfig.webpack`, which Turbopack never calls, so the app resolved `@astryxdesign/*` to dist while PostCSS compiled the library from source — disjoint class names, an exit code of 0, and an unstyled page. It now throws, naming both ways out: `--webpack`, or drop the helper and consume the pre-built package. Also warns when the merged alias map claims none of the packages, which reaches the same unstyled state by another route. (#6109)+@joaodotworkdiff --git a/apps/example-nextjs-source/README.md b/apps/example-nextjs-source/README.mdindex 0bf2ca52a6..7b2c4776f1 100644--- a/apps/example-nextjs-source/README.md+++ b/apps/example-nextjs-source/README.md@@ -2,6 +2,25 @@Reference application for compiling **@astryxdesign/core** from raw TypeScript + StyleX source alongside product code. Uses `@astryxdesign/build` for independent CSS layer separation.+> **Runs on webpack, not Turbopack.** The source build configures resolution through+> `nextConfig.webpack`, which Turbopack never calls — under Turbopack the app loads+> `dist` while PostCSS compiles the library from `source`, and the page renders unstyled+> without erroring.+>+> This example pins Next 15, where webpack is still the default, so its plain+> `next dev` / `next build` scripts are correct as they stand. **On Next 16 the default+> flips to Turbopack**, and a source build has to name the bundler:+>+> ```bash+> next dev --webpack+> next build --webpack+> ```+>+> (`--webpack` is a Next 16 flag; Next 15 does not accept it.) `withAstryx()` throws+> under Turbopack rather than producing the unstyled build. If you would rather not pin+> the bundler, take the pre-built approach in+> [example-nextjs](../example-nextjs/) instead.+## Why source build?| | Source build | Dist build |diff --git a/packages/build/README.md b/packages/build/README.mdindex e36203ce93..355f70fee8 100644--- a/packages/build/README.md+++ b/packages/build/README.md@@ -18,11 +18,11 @@ StyleX generates atomic CSS: same declaration = same class name. Without separat## Packages-| Export | Purpose | Platform |-| -------------------- | --------------------------------------------- | --------------------------- |-| `@astryxdesign/build/babel` | Babel plugin: splits class prefixes per file | Next.js, any babel pipeline |-| `@astryxdesign/build/postcss` | PostCSS plugin: compiles + splits CSS layers | Next.js |-| `@astryxdesign/build/vite` | Vite plugin: wraps unplugin + splits layers | Vite, Storybook |+| Export | Purpose | Platform |+| ----------------------------- | -------------------------------------------- | --------------------------- |+| `@astryxdesign/build/babel` | Babel plugin: splits class prefixes per file | Next.js, any babel pipeline |+| `@astryxdesign/build/postcss` | PostCSS plugin: compiles + splits CSS layers | Next.js |+| `@astryxdesign/build/vite` | Vite plugin: wraps unplugin + splits layers | Vite, Storybook |## Install@@ -40,6 +40,27 @@ npm install -D @stylexjs/unplugin## Next.js Setup+> **Requires the webpack bundler.** Every step below configures resolution through+> `nextConfig.webpack`, and Turbopack never calls that hook. Under Turbopack the app+> resolves `@astryxdesign/*` to `dist` while the PostCSS pass compiles the library from+> `source` — the two emit disjoint class names, so the build succeeds and the page+> renders unstyled with nothing logged.+>+> Next.js 16 selects Turbopack by default, so name the bundler explicitly:+>+> ```bash+> next dev --webpack+> next build --webpack+> ```+>+> `withAstryx()` throws when it sees `TURBOPACK` set rather than letting that through.+> Next 16 also rejects a `webpack` config with no `turbopack` config on its own when no+> bundler flag is given.+>+> If you would rather not pin the bundler, take the pre-built package instead: import+> `@astryxdesign/core/astryx.css` and skip the babel and PostCSS setup entirely. See+> [example-nextjs](../../apps/example-nextjs/).+### 1. babel.config.js```js@@ -56,8 +77,12 @@ module.exports = {treeshakeCompensation: true,enableInlinedConditionalMerge: true,aliases: {- '@astryxdesign/core/*': [path.join(__dirname, 'node_modules/@astryxdesign/core/*')],- '@astryxdesign/core': [path.join(__dirname, 'node_modules/@astryxdesign/core')],+ '@astryxdesign/core/*': [+ path.join(__dirname, 'node_modules/@astryxdesign/core/*'),+ ],+ '@astryxdesign/core': [+ path.join(__dirname, 'node_modules/@astryxdesign/core'),+ ],},unstable_moduleResolution: {type: 'commonJS'},},@@ -84,8 +109,12 @@ module.exports = {treeshakeCompensation: true,enableInlinedConditionalMerge: true,aliases: {- '@astryxdesign/core/*': [path.join(__dirname, 'node_modules/@astryxdesign/core/*')],- '@astryxdesign/core': [path.join(__dirname, 'node_modules/@astryxdesign/core')],+ '@astryxdesign/core/*': [+ path.join(__dirname, 'node_modules/@astryxdesign/core/*'),+ ],+ '@astryxdesign/core': [+ path.join(__dirname, 'node_modules/@astryxdesign/core'),+ ],},unstable_moduleResolution: {type: 'commonJS'},},@@ -98,6 +127,10 @@ module.exports = {### 3. next.config.mjs+Or `withAstryx()` from `@astryxdesign/build/next`, which sets both of these for you.+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.+```jsconst nextConfig = {transpilePackages: ['@astryxdesign/core', '@astryxdesign/theme-neutral'],@@ -164,7 +197,10 @@ export default defineConfig({],resolve: {alias: {- '@astryxdesign/core': path.resolve(__dirname, 'node_modules/@astryxdesign/core/src'),+ '@astryxdesign/core': path.resolve(+ __dirname,+ 'node_modules/@astryxdesign/core/src',+ ),},},optimizeDeps: {diff --git a/packages/build/src/next.js b/packages/build/src/next.jsindex 7f8915c425..27578e59ea 100644--- a/packages/build/src/next.js+++ b/packages/build/src/next.js@@ -19,6 +19,35 @@ const path = require('path');const ASTRYX_MODULE = /[\\/]node_modules[\\/]@astryxdesign[\\/]/;+/**+ * Every alias this helper installs lives in `nextConfig.webpack`, and Turbopack+ * never calls that hook. So `withAstryx()` under Turbopack reinstates exactly+ * the failure the aliases exist to prevent: the app resolves the library+ * through `default` to dist, whose runtime class names are disjoint from the+ * CSS the PostCSS pass compiles out of source, and the build succeeds with an+ * unstyled page and nothing logged.+ *+ * There is no configuration in which the combination does what the author+ * intended, so this refuses rather than warning — an unstyled production deploy+ * costs more than a failed build. Next sets `TURBOPACK` for both+ * `next dev --turbopack` and `next build --turbopack`, in the parent process+ * and in each build worker.+ */+function assertWebpack() {+ if (!process.env.TURBOPACK) {+ return;+ }+ throw new Error(+ 'withAstryx() requires the webpack bundler: it configures resolution ' ++ 'through nextConfig.webpack, which Turbopack does not call, so the app ' ++ 'would resolve @astryxdesign/* to dist while the CSS is compiled from ' ++ 'source and render unstyled.\n' ++ 'Run the source build with `next build --webpack` / `next dev --webpack`, ' ++ 'or drop withAstryx() and consume the pre-built package instead — import ' ++ "'@astryxdesign/core/astryx.css' and skip the babel and PostCSS setup.",+ );+}+/*** Locate an installed package's directory by walking `node_modules` up from* the app, the way Node resolves a bare specifier. Returns null when the@@ -158,12 +187,65 @@ function sourceEntryAliases(packages, context) {return aliases;}+/**+ * Whether the resolved alias map routes any astryx request at all.+ *+ * The test is webpack's own matching rule rather than a list of shapes. A+ * non-exact alias `key` intercepts a request `R` when `R === key` or `R` starts+ * with `${key}/`, so an entry covers the packages when one of them sits at or+ * below its key: `'@astryxdesign'` claims `@astryxdesign/core`. A key *under* a+ * package counts too, because that is the shape of the entries this helper+ * generates, and a `*` key claims by pattern, using the same matcher+ * `withoutCallerOverrides` applies.+ *+ * Exactness — a trailing `$` on an object key, `onlyModule: true` on an array+ * entry — restricts an entry to the literal request, which removes the+ * ancestor case and only that one. `'@astryxdesign/core$'` still routes a real+ * request; `'@astryxdesign$'` routes only the bare scope specifier, which+ * nothing imports, so it covers nothing.+ *+ * Where a caller points its alias is its business; the only thing worth saying+ * is that no entry routes the packages at all. A false positive tells someone+ * their working build is broken, so an ambiguous config stays quiet — but an+ * exact-scope key is not ambiguous, it is determinately ineffective.+ */+function aliasCoversAstryx(alias, packages) {+ const covers = (key, exact) => {+ const bare = key.endsWith('$') ? key.slice(0, -1) : key;+ const isExact = exact || key.endsWith('$');+ if (bare.includes('*')) {+ const pattern = wildcardPattern(bare);+ return packages.some(name => pattern.test(name));+ }+ return packages.some(+ name =>+ name === bare ||+ bare.startsWith(`${name}/`) ||+ (!isExact && name.startsWith(`${bare}/`)),+ );+ };+ if (Array.isArray(alias)) {+ return alias.some(+ entry =>+ entry &&+ typeof entry.name === 'string' &&+ covers(entry.name, entry.onlyModule === true),+ );+ }+ if (alias == null || typeof alias !== 'object') {+ return false;+ }+ return Object.keys(alias).some(key => covers(key, false));+}+/*** Wraps a Next.js config to enable Astryx source builds.* - Adds transpilePackages for @astryxdesign/* packages* - Sets conditionNames to resolve source exports*/function withAstryx(nextConfig = {}) {+ assertWebpack();+const astryxPackages = ['@astryxdesign/core','@astryxdesign/theme-neutral',@@ -231,6 +313,29 @@ function withAstryx(nextConfig = {}) {sourceEntryAliases(astryxPackages, context),merged.resolve.alias,);++ // Generating no entries is not itself a fault: a package may simply not be+ // installed, and a caller alias that already routes the packages is a+ // working config this helper has nothing to add to. What is a fault is+ // ending up with an alias map that claims none of them — that is the+ // pre-0.5.3 config, where the app resolves dist while PostCSS compiles the+ // library from source and the page renders unstyled with nothing logged.+ // So the check is on the merged result, not on what we generated, and it+ // warns rather than throws: an install layout this helper cannot walk is+ // not proof the build is wrong.+ if (!aliasCoversAstryx(merged.resolve.alias, astryxPackages)) {+ console.warn(+ '[@astryxdesign/build] withAstryx(): no alias routes ' ++ `${astryxPackages.join(', ')} to their \`source\` entries. Either they ` ++ 'are not installed where the app can see them, their export maps ' ++ 'ship no `source` condition, or a configured alias does not match ' ++ 'the requests — an exact key such as `@astryxdesign$` matches only ' ++ 'the bare specifier. Source resolution is not in effect, so the app ' ++ 'will load dist while the PostCSS pass compiles the library from ' ++ 'source.',+ );+ }+return merged;},};diff --git a/packages/build/src/next.test.mjs b/packages/build/src/next.test.mjsindex c280879100..5dcdd11f6a 100644--- a/packages/build/src/next.test.mjs+++ b/packages/build/src/next.test.mjs@@ -14,7 +14,7 @@* `config.resolve.alias` cannot tell a winning entry from a shadowed one.*/-import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import {describe, it, expect, beforeAll, afterAll, afterEach, vi} from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -124,6 +124,19 @@ function corePath(...segments) {}describe('withAstryx', () => {+ // Every case in this block is a config that resolves successfully, so none of+ // them may warn. Asserting it here rather than per-test means a future+ // coverage check that misreads a working alias — as one did for wildcards —+ // fails the suite instead of quietly logging into it.+ let warned;+ beforeEach(() => {+ warned = vi.spyOn(console, 'warn').mockImplementation(() => {});+ });+ afterEach(() => {+ expect(warned).not.toHaveBeenCalled();+ vi.restoreAllMocks();+ });+it('resolves the package root to its source entry', () => {expect(resolveFromApp('@astryxdesign/core')).toBe(corePath('src/index.ts'));});@@ -364,3 +377,261 @@ describe('withAstryx', () => {expect(config.resolve.alias['@astryxdesign/core$']).toBeDefined();});});++describe('withAstryx bundler guard', () => {+ afterEach(() => {+ delete process.env.TURBOPACK;+ vi.restoreAllMocks();+ });++ it('refuses to build a config under Turbopack', () => {+ process.env.TURBOPACK = '1';+ expect(() => withAstryx()).toThrow(/requires the webpack bundler/);+ });++ it('names both ways out in the message', () => {+ process.env.TURBOPACK = '1';+ // The two supported routes: keep the source build and pick webpack, or drop+ // the source build entirely and consume the pre-built package.+ expect(() => withAstryx()).toThrow(/--webpack/);+ expect(() => withAstryx()).toThrow(/astryx\.css/);+ });++ it('refuses before touching the caller config', () => {+ process.env.TURBOPACK = '1';+ const webpack = vi.fn();+ expect(() => withAstryx({webpack})).toThrow();+ expect(webpack).not.toHaveBeenCalled();+ });++ it('builds normally when Turbopack is not in play', () => {+ expect(() => withAstryx()).not.toThrow();+ });+});++describe('withAstryx alias coverage', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('warns when nothing routes the packages at all', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ // Nothing installed and no caller alias, so the merged map claims none of+ // the packages — the pre-0.5.3 config, rather than a partial one.+ const empty = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-none-')),+ );+ try {+ withAstryx().webpack({resolve: {}}, {dir: empty});+ expect(warn).toHaveBeenCalledOnce();+ expect(warn.mock.calls[0][0]).toMatch(/no alias routes/);+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ }+ });++ it('stays quiet when at least one package resolves', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ // Only @astryxdesign/core is installed in the fixture; theme-neutral and+ // lab are absent and skipped. A partial map is the normal case, not a fault.+ resolveConfig();+ expect(warn).not.toHaveBeenCalled();+ });++ it('stays quiet when a caller alias already routes the packages', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ // Nothing installed, so this helper generates nothing — but the caller has+ // routed the packages itself, which is a working config with nothing to+ // warn about. The check is on the merged alias map, not on what we+ // generated.+ const empty = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-caller-')),+ );+ try {+ withAstryx().webpack(+ {+ resolve: {+ alias: {'@astryxdesign/core': path.join(empty, 'vendored')},+ },+ },+ {dir: empty},+ );+ expect(warn).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ }+ });++ it('stays quiet for an array-shaped caller alias too', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const empty = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-caller-arr-')),+ );+ try {+ withAstryx().webpack(+ {+ resolve: {+ alias: [+ {+ name: '@astryxdesign/core',+ onlyModule: false,+ alias: path.join(empty, 'vendored'),+ },+ ],+ },+ },+ {dir: empty},+ );+ expect(warn).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ }+ });++ // A scope-level key matches no package name as a string, but webpack resolves+ // `@astryxdesign/core` through it — the key is an ancestor of the request.+ // An exact key restricted to the bare scope matches only `@astryxdesign`,+ // which nothing imports, so it routes no package and must not buy silence.+ // These need an app with nothing installed: with a package present the+ // generated entries route it and there is correctly nothing to report.+ const ineffective = (label, build) =>+ it(`warns for an exact scope-only alias ${label}`, () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const dir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-exact-')),+ );+ try {+ build(dir, path.join(dir, 'customRoot'));+ expect(warn).toHaveBeenCalledOnce();+ expect(warn.mock.calls[0][0]).toMatch(/no alias routes/);+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });++ ineffective('in the config', (dir, target) =>+ withAstryx().webpack({resolve: {alias: {'@astryxdesign$': target}}}, {dir}),+ );++ ineffective('in array form', (dir, target) =>+ withAstryx().webpack(+ {+ resolve: {+ alias: [{name: '@astryxdesign', onlyModule: true, alias: target}],+ },+ },+ {dir},+ ),+ );++ ineffective('from the caller webpack hook', (dir, target) =>+ withAstryx({+ webpack: cfg => {+ cfg.resolve.alias['@astryxdesign$'] = target;+ return cfg;+ },+ }).webpack({resolve: {alias: {}}}, {dir}),+ );++ // The boundary: exactness removes the ancestor case and only that one, so an+ // exact key at or below a package still routes a real request.+ const effectiveExact = (label, build) =>+ it(`stays quiet for an exact alias ${label}`, () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const dir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-exact-ok-')),+ );+ try {+ build(dir, path.join(dir, 'customRoot'));+ expect(warn).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });++ effectiveExact('on the package itself', (dir, target) =>+ withAstryx().webpack(+ {resolve: {alias: {'@astryxdesign/core$': target}}},+ {dir},+ ),+ );++ effectiveExact('on the package, array form', (dir, target) =>+ withAstryx().webpack(+ {+ resolve: {+ alias: [+ {name: '@astryxdesign/core', onlyModule: true, alias: target},+ ],+ },+ },+ {dir},+ ),+ );++ effectiveExact('on a subpath under the package', (dir, target) =>+ withAstryx().webpack(+ {resolve: {alias: {'@astryxdesign/core/Badge$': target}}},+ {dir},+ ),+ );++ const scoped = (label, build) =>+ it(`stays quiet for a scope-prefix alias ${label}`, () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const dir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-scope-')),+ );+ try {+ build(dir, path.join(dir, 'customRoot'));+ expect(warn).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });++ scoped('in the config', (dir, target) =>+ withAstryx().webpack({resolve: {alias: {'@astryxdesign': target}}}, {dir}),+ );++ scoped('in array form', (dir, target) =>+ withAstryx().webpack(+ {+ resolve: {+ alias: [{name: '@astryxdesign', onlyModule: false, alias: target}],+ },+ },+ {dir},+ ),+ );++ scoped('from the caller webpack hook', (dir, target) =>+ withAstryx({+ webpack: cfg => {+ cfg.resolve.alias['@astryxdesign'] = target;+ return cfg;+ },+ }).webpack({resolve: {alias: {}}}, {dir}),+ );++ it('stays quiet when the caller routes them from its webpack hook', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const empty = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-caller-hook-')),+ );+ try {+ withAstryx({+ webpack: cfg => {+ cfg.resolve.alias['@astryxdesign/core'] = path.join(+ empty,+ 'vendored',+ );+ return cfg;+ },+ }).webpack({resolve: {alias: {}}}, {dir: empty});+ expect(warn).not.toHaveBeenCalled();+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ }+ });+});