An open source design system that's fully customizable and agent ready
TypeScript
fix(build): resolve app imports of astryx to source in withAstryx (#5932)
PRIEYAN MNbea53b23fa40
diff --git a/.changeset/withastryx-app-source-resolution.md b/.changeset/withastryx-app-source-resolution.mdnew file mode 100644index 0000000000..d47ae90a7b--- /dev/null+++ b/.changeset/withastryx-app-source-resolution.md@@ -0,0 +1,7 @@+---+'@astryxdesign/build': patch+---++[fix] `withAstryx()` now resolves an app's own `@astryxdesign/*` imports to the packages' `source` entries. The scoped webpack rule only governs requests issued from inside `node_modules`, so app code resolved the library through `default` to `dist` while PostCSS compiled it from source — the two emit disjoint class names and the app rendered unstyled without erroring. (#5932)++@PRIEYANdiff --git a/packages/build/src/next.js b/packages/build/src/next.jsindex 9a6d24ced0..7f8915c425 100644--- a/packages/build/src/next.js+++ b/packages/build/src/next.js@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-"use strict";+'use strict';/*** @astryxdesign/build/next@@ -14,6 +14,150 @@* });*/+const fs = require('fs');+const path = require('path');++const ASTRYX_MODULE = /[\\/]node_modules[\\/]@astryxdesign[\\/]/;++/**+ * 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+ * package is not installed.+ */+function findPackageDir(name, from) {+ let dir = path.resolve(from);+ for (;;) {+ const candidate = path.join(dir, 'node_modules', name);+ if (fs.existsSync(path.join(candidate, 'package.json'))) {+ return candidate;+ }+ const parent = path.dirname(dir);+ if (parent === dir) {+ return null;+ }+ dir = parent;+ }+}++/**+ * Match a wildcard alias key such as `@astryxdesign/*` against a request. The+ * resolver treats `*` as the variable part of the specifier, so a caller can+ * claim a whole scope with one entry.+ */+function wildcardPattern(name) {+ const source = name+ .split('*')+ .map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))+ .join('.*');+ return new RegExp(`^${source}$`);+}++/**+ * Drop the generated aliases a caller has already spoken for. A caller entry+ * is authoritative for the request it names: `'@astryxdesign/core'` is a prefix+ * alias covering the package and every subpath under it,+ * `'@astryxdesign/core$'` covers only the bare specifier, and+ * `'@astryxdesign/*'` claims everything the pattern matches. Without this the+ * generated entries sit earlier in the alias list and win, so a composed config+ * silently loads astryx source instead of the caller's implementation.+ */+function withoutCallerOverrides(generated, callerAlias) {+ const exact = new Set();+ const prefixes = [];+ const patterns = [];+ for (const key of Object.keys(callerAlias)) {+ const onlyModule = key.endsWith('$');+ const name = onlyModule ? key.slice(0, -1) : key;+ if (name.includes('*')) {+ patterns.push(wildcardPattern(name));+ } else if (onlyModule) {+ exact.add(name);+ } else {+ prefixes.push(name);+ }+ }+ const kept = {};+ for (const [key, target] of Object.entries(generated)) {+ const request = key.slice(0, -1);+ const overridden =+ exact.has(request) ||+ prefixes.some(+ prefix => request === prefix || request.startsWith(`${prefix}/`),+ ) ||+ patterns.some(pattern => pattern.test(request));+ if (!overridden) {+ kept[key] = target;+ }+ }+ return kept;+}++/**+ * Merge the generated aliases under whatever the caller already configured.+ * `resolve.alias` accepts an object or an array of entries; both are ordered,+ * first match wins, so the caller's entries stay ahead of ours either way.+ */+function mergeAliases(generated, existing) {+ if (Array.isArray(existing)) {+ const named = {};+ for (const entry of existing) {+ if (entry && typeof entry.name === 'string') {+ named[entry.onlyModule ? `${entry.name}$` : entry.name] = entry.alias;+ }+ }+ const kept = withoutCallerOverrides(generated, named);+ return [+ ...existing,+ ...Object.entries(kept).map(([key, alias]) => ({+ name: key.slice(0, -1),+ onlyModule: true,+ alias,+ })),+ ];+ }+ const callerAlias = existing || {};+ return {...withoutCallerOverrides(generated, callerAlias), ...callerAlias};+}++/**+ * Map each installed astryx package to the `source` targets in its export map,+ * so an app's imports reach raw TS the way an in-repo build does. Subpaths get+ * an entry each — `@astryxdesign/core/AlertDialog` is as much a documented+ * entry point as the package root. Packages that are absent, and export keys+ * that ship no `source` condition, are skipped and keep normal resolution.+ */+function sourceEntryAliases(packages, context) {+ const from = (context && context.dir) || process.cwd();+ const aliases = {};+ for (const name of packages) {+ // Not `require.resolve(`${name}/package.json`)`: packages that define+ // `exports` without a `./package.json` key — astryx's own among them —+ // make that request throw ERR_PACKAGE_PATH_NOT_EXPORTED.+ const packageDir = findPackageDir(name, from);+ if (packageDir == null) {+ continue;+ }+ let exports;+ try {+ exports = require(path.join(packageDir, 'package.json')).exports;+ } catch {+ continue;+ }+ if (exports == null || typeof exports !== 'object') {+ continue;+ }+ for (const [key, value] of Object.entries(exports)) {+ const entry = value && typeof value === 'object' ? value.source : null;+ if (typeof entry !== 'string' || key.includes('*')) {+ continue;+ }+ const request = key === '.' ? name : `${name}/${key.slice(2)}`;+ aliases[`${request}$`] = path.resolve(packageDir, entry);+ }+ }+ return aliases;+}+/*** Wraps a Next.js config to enable Astryx source builds.* - Adds transpilePackages for @astryxdesign/* packages@@ -46,12 +190,24 @@ function withAstryx(nextConfig = {}) {config.module = config.module || {};config.module.rules = config.module.rules || [];config.module.rules.unshift({- test: /[\\/]node_modules[\\/]@astryxdesign[\\/]/,+ test: ASTRYX_MODULE,resolve: {conditionNames: ['source', '...'],},});+ // The rule above only covers astryx-to-astryx imports: `Rule.test`+ // matches the module being processed and `Rule.resolve` governs the+ // requests that module makes, so an app's own `@astryxdesign/*` imports —+ // issued from its sources, outside node_modules — never match it. Those+ // resolve through `default` to dist, whose runtime class names are+ // disjoint from the CSS the PostCSS pass compiles out of source, and the+ // app renders unstyled without erroring. Rules cannot key on the request+ // string, so point the packages at their `source` entry directly; the+ // global conditions stay as Next's defaults for React and for+ // third-party `source` shippers such as `lexical`.+ config.resolve = config.resolve || {};+// Preserve the symlinked node_modules path so Next.js's// transpilePackages matcher recognizes @astryxdesign/* packages under// pnpm's symlinked layout. Without this, webpack dereferences@@ -61,10 +217,21 @@ function withAstryx(nextConfig = {}) {config.resolve.symlinks = false;// Call user's webpack config if provided- if (existingWebpack) {- return existingWebpack(config, context);- }- return config;+ const merged = existingWebpack+ ? existingWebpack(config, context) || config+ : config;++ // Merge after the caller's hook, not before: aliases the hook adds are+ // as authoritative as the ones already on the config, and merging first+ // would leave the generated entries ahead of them in the alias list —+ // where the resolver, taking the first match, loads astryx source+ // instead. Only a byte-identical `$` key would have replaced ours.+ merged.resolve = merged.resolve || {};+ merged.resolve.alias = mergeAliases(+ sourceEntryAliases(astryxPackages, context),+ merged.resolve.alias,+ );+ return merged;},};}diff --git a/packages/build/src/next.test.mjs b/packages/build/src/next.test.mjsnew file mode 100644index 0000000000..c280879100--- /dev/null+++ b/packages/build/src/next.test.mjs@@ -0,0 +1,366 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file next.test.mjs+ * @description Verifies that `withAstryx()` routes an app's own+ * `@astryxdesign/*` imports to the packages' `source` entries. The scoped+ * module rule only governs requests issued from inside node_modules, so+ * without the aliases an app resolves the library through `default` to dist+ * and renders unstyled against source-compiled CSS.+ *+ * Resolution is asserted through `enhanced-resolve` — the resolver webpack+ * itself runs — because alias precedence is an ordering property of the+ * resolver, not of the config object. Reading keys back out of+ * `config.resolve.alias` cannot tell a winning entry from a shadowed one.+ */++import {describe, it, expect, beforeAll, afterAll} 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');+const {ResolverFactory, CachedInputFileSystem} = require('enhanced-resolve');++let appDir;++/** Files the fixture package needs on disk for the resolver to accept them. */+const CORE_FILES = [+ 'src/index.ts',+ 'src/AlertDialog/index.ts',+ 'dist/index.js',+ 'dist/AlertDialog/index.js',+];++/**+ * A consumer app with `@astryxdesign/core` installed the way npm lays it out,+ * so the helper resolves real manifests rather than the workspace it lives in.+ */+beforeAll(() => {+ // Canonical, not the `mkdtemp` path: on macOS `os.tmpdir()` is under `/var`,+ // a symlink to `/private/var`, and the resolver reports the real path.+ appDir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-next-')),+ );+ const coreDir = path.join(appDir, 'node_modules/@astryxdesign/core');+ for (const file of CORE_FILES) {+ const target = path.join(coreDir, file);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, '');+ }+ fs.writeFileSync(+ path.join(coreDir, 'package.json'),+ JSON.stringify({+ name: '@astryxdesign/core',+ exports: {+ '.': {+ source: './src/index.ts',+ default: './dist/index.js',+ },+ './AlertDialog': {+ source: './src/AlertDialog/index.ts',+ default: './dist/AlertDialog/index.js',+ },+ './reset.css': {default: './src/reset.css'},+ './generated/*': {source: './src/generated/*'},+ },+ }),+ );+ fs.mkdirSync(path.join(appDir, 'src'), {recursive: true});+ fs.writeFileSync(path.join(appDir, 'src/page.tsx'), '');+});++afterAll(() => {+ fs.rmSync(appDir, {recursive: true, force: true});+});++/** Run the helper's webpack hook the way Next.js does. */+function resolveConfig(nextConfig = {}, config = {resolve: {}}) {+ return withAstryx(nextConfig).webpack(config, {dir: appDir});+}++/**+ * Resolve a request from the app's own source, through the resolver webpack+ * uses, under the config `withAstryx()` produced.+ */+function resolveFromApp(request, callerResolve = {}) {+ const {resolve} = resolveConfig({}, {resolve: callerResolve});+ const resolver = ResolverFactory.createResolver({+ fileSystem: new CachedInputFileSystem(fs, 4000),+ extensions: ['.ts', '.tsx', '.js'],+ conditionNames: ['import', 'default'],+ alias: resolve.alias,+ useSyncFileSystemCalls: true,+ });+ return resolver.resolveSync({}, path.join(appDir, 'src'), request);+}++/**+ * The same, for an alias the caller contributes from its own `webpack` hook —+ * the composition path a Next config takes when it wraps `withAstryx()`.+ */+function resolveFromAppWithHook(request, hookAlias) {+ const {resolve} = withAstryx({+ webpack: cfg => {+ Object.assign(cfg.resolve.alias, hookAlias);+ return cfg;+ },+ }).webpack({resolve: {alias: {}}}, {dir: appDir});+ const resolver = ResolverFactory.createResolver({+ fileSystem: new CachedInputFileSystem(fs, 4000),+ extensions: ['.ts', '.tsx', '.js'],+ conditionNames: ['import', 'default'],+ alias: resolve.alias,+ useSyncFileSystemCalls: true,+ });+ return resolver.resolveSync({}, path.join(appDir, 'src'), request);+}++/** The installed fixture's absolute path for one of its files. */+function corePath(...segments) {+ return path.join(appDir, 'node_modules/@astryxdesign/core', ...segments);+}++describe('withAstryx', () => {+ it('resolves the package root to its source entry', () => {+ expect(resolveFromApp('@astryxdesign/core')).toBe(corePath('src/index.ts'));+ });++ it('resolves documented subpath entry points, not just the root', () => {+ expect(resolveFromApp('@astryxdesign/core/AlertDialog')).toBe(+ corePath('src/AlertDialog/index.ts'),+ );+ });++ it('lets a caller prefix alias win over the generated entries', () => {+ const custom = path.join(appDir, 'custom');+ fs.mkdirSync(custom, {recursive: true});+ fs.writeFileSync(path.join(custom, 'index.js'), '');++ expect(+ resolveFromApp('@astryxdesign/core', {+ alias: {'@astryxdesign/core': custom},+ }),+ ).toBe(path.join(custom, 'index.js'));+ });++ it('lets a caller prefix alias win for subpaths too', () => {+ const custom = path.join(appDir, 'custom');+ fs.mkdirSync(path.join(custom, 'AlertDialog'), {recursive: true});+ fs.writeFileSync(path.join(custom, 'AlertDialog/index.js'), '');++ expect(+ resolveFromApp('@astryxdesign/core/AlertDialog', {+ alias: {'@astryxdesign/core': custom},+ }),+ ).toBe(path.join(custom, 'AlertDialog/index.js'));+ });++ it('lets a caller wildcard alias win over the generated entries', () => {+ const custom = path.join(appDir, 'custom');+ fs.mkdirSync(custom, {recursive: true});+ fs.writeFileSync(path.join(custom, 'index.js'), '');++ expect(+ resolveFromApp('@astryxdesign/core', {+ alias: {'@astryxdesign/*': custom},+ }),+ ).toBe(path.join(custom, 'index.js'));+ });++ it('lets a caller wildcard alias win for subpaths too', () => {+ const custom = path.join(appDir, 'custom');+ fs.mkdirSync(path.join(custom, 'core/AlertDialog'), {recursive: true});+ fs.writeFileSync(path.join(custom, 'core/AlertDialog/index.js'), '');++ // A wildcard target substitutes the matched part, so the subpath survives;+ // a plain target collapses every request onto the one directory.+ expect(+ resolveFromApp('@astryxdesign/core/AlertDialog', {+ alias: {'@astryxdesign/*': path.join(custom, '*')},+ }),+ ).toBe(path.join(custom, 'core/AlertDialog/index.js'));+ });++ it('resolves through a symlinked app root', () => {+ const link = path.join(+ path.dirname(appDir),+ `${path.basename(appDir)}-link`,+ );+ try {+ fs.symlinkSync(appDir, link, 'dir');+ } catch {+ return;+ }+ const {resolve} = withAstryx({}).webpack({resolve: {}}, {dir: link});+ const resolver = ResolverFactory.createResolver({+ fileSystem: new CachedInputFileSystem(fs, 4000),+ extensions: ['.ts', '.tsx', '.js'],+ conditionNames: ['import', 'default'],+ alias: resolve.alias,+ useSyncFileSystemCalls: true,+ });++ expect(+ resolver.resolveSync({}, path.join(link, 'src'), '@astryxdesign/core'),+ ).toBe(corePath('src/index.ts'));++ fs.unlinkSync(link);+ });++ it('lets a caller exact alias win for the bare specifier', () => {+ const pinned = corePath('dist/index.js');++ expect(+ resolveFromApp('@astryxdesign/core', {+ alias: {'@astryxdesign/core$': pinned},+ }),+ ).toBe(pinned);+ });++ it('keeps the generated subpaths when the caller pins only the root', () => {+ expect(+ resolveFromApp('@astryxdesign/core/AlertDialog', {+ alias: {'@astryxdesign/core$': corePath('dist/index.js')},+ }),+ ).toBe(corePath('src/AlertDialog/index.ts'));+ });++ it('preserves an array-shaped caller alias', () => {+ const pinned = corePath('dist/index.js');+ const {resolve} = resolveConfig(+ {},+ {resolve: {alias: [{name: '@astryxdesign/core', alias: pinned}]}},+ );++ expect(Array.isArray(resolve.alias)).toBe(true);+ expect(resolve.alias[0]).toEqual({+ name: '@astryxdesign/core',+ alias: pinned,+ });+ expect(+ resolve.alias.some(+ entry => entry.name === '@astryxdesign/core/AlertDialog',+ ),+ ).toBe(false);+ });++ it('skips export keys that ship no source condition', () => {+ const {resolve} = resolveConfig();++ expect(resolve.alias).not.toHaveProperty('@astryxdesign/core/reset.css$');+ });++ it('skips wildcard subpaths, which an exact alias cannot express', () => {+ const {resolve} = resolveConfig();++ const wildcards = Object.keys(resolve.alias).filter(request =>+ request.includes('*'),+ );+ expect(wildcards).toEqual([]);+ });++ it('leaves non-astryx requests to their normal resolution', () => {+ const {resolve} = resolveConfig();++ const foreign = Object.keys(resolve.alias).filter(+ request => !request.startsWith('@astryxdesign/'),+ );+ expect(foreign).toEqual([]);+ });++ it('keeps the global conditions as Next resolved them', () => {+ const {resolve} = resolveConfig(+ {},+ {resolve: {conditionNames: ['import']}},+ );++ expect(resolve.conditionNames).toEqual(['import']);+ });++ it('still scopes the source condition to astryx modules', () => {+ const {module: mod} = resolveConfig();++ expect(mod.rules[0].resolve.conditionNames).toEqual(['source', '...']);+ expect('@astryxdesign/core'.match(mod.rules[0].test)).toBeNull();+ expect(+ '/app/node_modules/@astryxdesign/core/src/index.ts'.match(+ mod.rules[0].test,+ ),+ ).not.toBeNull();+ });++ it('lets a prefix alias from the caller webpack hook win', () => {+ const custom = path.join(appDir, 'custom');+ fs.mkdirSync(path.join(custom, 'AlertDialog'), {recursive: true});+ fs.writeFileSync(path.join(custom, 'index.js'), '');+ fs.writeFileSync(path.join(custom, 'AlertDialog/index.js'), '');++ expect(+ resolveFromAppWithHook('@astryxdesign/core', {+ '@astryxdesign/core': custom,+ }),+ ).toBe(path.join(custom, 'index.js'));+ expect(+ resolveFromAppWithHook('@astryxdesign/core/AlertDialog', {+ '@astryxdesign/core': custom,+ }),+ ).toBe(path.join(custom, 'AlertDialog/index.js'));+ });++ it('lets a wildcard alias from the caller webpack hook win', () => {+ const custom = path.join(appDir, 'custom');+ fs.mkdirSync(path.join(custom, 'core/AlertDialog'), {recursive: true});+ fs.writeFileSync(path.join(custom, 'core/index.js'), '');+ fs.writeFileSync(path.join(custom, 'core/AlertDialog/index.js'), '');++ expect(+ resolveFromAppWithHook('@astryxdesign/core', {+ '@astryxdesign/*': path.join(custom, '*'),+ }),+ ).toBe(path.join(custom, 'core/index.js'));+ expect(+ resolveFromAppWithHook('@astryxdesign/core/AlertDialog', {+ '@astryxdesign/*': path.join(custom, '*'),+ }),+ ).toBe(path.join(custom, 'core/AlertDialog/index.js'));+ });++ it('lets an exact alias from the caller webpack hook win', () => {+ const pinned = corePath('dist/index.js');++ expect(+ resolveFromAppWithHook('@astryxdesign/core', {+ '@astryxdesign/core$': pinned,+ }),+ ).toBe(pinned);+ });++ it('still applies the generated entries the hook did not claim', () => {+ expect(+ resolveFromAppWithHook('@astryxdesign/core', {'other-pkg': '/elsewhere'}),+ ).toBe(corePath('src/index.ts'));+ });++ it('tolerates a caller webpack hook that returns nothing', () => {+ const config = withAstryx({webpack: () => {}}).webpack(+ {resolve: {alias: {}}},+ {dir: appDir},+ );++ expect(config.resolve.alias['@astryxdesign/core$']).toBe(+ corePath('src/index.ts'),+ );+ });++ it('runs the caller webpack hook last', () => {+ const config = resolveConfig({+ webpack: cfg => ({...cfg, marker: true}),+ });++ expect(config.marker).toBe(true);+ expect(config.resolve.alias['@astryxdesign/core$']).toBeDefined();+ });+});