An open source design system that's fully customizable and agent ready
TypeScript
build(stylex): resolve workspace .stylex imports to their source, so cross-package markers match (#8324)
Christopher Chedeau84702fc4f008
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0c4430a133..af9a2f19ac 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -3794,6 +3794,14 @@ jobs:- name: Run Build CSS-layer cascade guardrun: node .github/scripts/theme-layer-cascade.js+ # A compile-time ancestor selector on another workspace package's marker+ # (lab's rule on core's indicatorScope) matches in a real browser: see+ # scripts/stylex-module-resolution.cjs.+ - name: Run cross-package StyleX marker browser check+ env:+ ASTRYX_STYLEX_BROWSER: '1'+ run: pnpm vitest run scripts/stylex-module-resolution.browser.test.mjs --project node --maxWorkers=1+# Guest token boundaries cross portals and the host light/dark cascade. This# requires a production browser render; source and jsdom checks cannot prove# which custom properties paint the portaled surfaces.diff --git a/apps/docsite/babel.config.js b/apps/docsite/babel.config.jsindex 40cc5da38d..4667c3ec0d 100644--- a/apps/docsite/babel.config.js+++ b/apps/docsite/babel.config.js@@ -3,6 +3,10 @@/* global module, require, process, __dirname */// eslint-disable-next-line @typescript-eslint/no-require-importsconst path = require('node:path');+// eslint-disable-next-line @typescript-eslint/no-require-imports+const {+ stylexModuleResolution,+} = require('../../scripts/stylex-module-resolution.cjs');const dev = process.env.NODE_ENV !== 'production';@@ -20,9 +24,7 @@ module.exports = {'@/*': [path.join(__dirname, '*')],},classNamePrefix: 'p',- unstable_moduleResolution: {- type: 'commonJS',- },+ unstable_moduleResolution: stylexModuleResolution,},],],diff --git a/apps/sandbox/vite.config.mts b/apps/sandbox/vite.config.mtsindex c7c39b619c..f91d6d4d02 100644--- a/apps/sandbox/vite.config.mts+++ b/apps/sandbox/vite.config.mts@@ -14,6 +14,7 @@ import fs from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';import {createRequire} from 'node:module';+import stylexResolution from '../../scripts/stylex-module-resolution.cjs';import {categories} from './src/app/sandboxPages';import {discoverRoutes,@@ -188,7 +189,7 @@ export default defineConfig({),],},- unstable_moduleResolution: {type: 'commonJS', rootDir: appDir},+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,},stylexPrefix: 'x',}),diff --git a/apps/storybook/.storybook/main.ts b/apps/storybook/.storybook/main.tsindex bb95c7bae1..243cb3468d 100644--- a/apps/storybook/.storybook/main.ts+++ b/apps/storybook/.storybook/main.ts@@ -15,6 +15,7 @@ import type {StorybookConfig} from '@storybook/react-vite';// tsconfig already resolves for typecheck.import {astryxStylex} from '../../../packages/build/src/vite.ts';import path from 'node:path';+import stylexResolution from '../../../scripts/stylex-module-resolution.cjs';import {fileURLToPath} from 'node:url';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -191,10 +192,7 @@ const config: StorybookConfig = {dev: false,styleResolution: 'application-order',aliases: stylexAliases,- unstable_moduleResolution: {- type: 'commonJS',- rootDir: rootDir,- },+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,lightningcssOptions: {targets: lightningcssTargets,},diff --git a/apps/storybook/vite.config.ts b/apps/storybook/vite.config.tsindex f1eea31b67..b78d2b23bd 100644--- a/apps/storybook/vite.config.ts+++ b/apps/storybook/vite.config.ts@@ -13,6 +13,7 @@ import {defineConfig} from 'vite';import react from '@vitejs/plugin-react';import stylex from '@stylexjs/unplugin';import path from 'node:path';+import stylexResolution from '../../scripts/stylex-module-resolution.cjs';const rootDir = path.resolve(__dirname, '../..');const coreRoot = path.resolve(__dirname, '../../packages/core/src');@@ -28,10 +29,7 @@ export default defineConfig({'@astryxdesign/core/*': [path.join(rootDir, 'packages/core/src/*')],'@astryxdesign/core': [path.join(rootDir, 'packages/core/src')],},- unstable_moduleResolution: {- type: 'commonJS',- rootDir: rootDir,- },+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,}),react(),],diff --git a/internal/vibe-tests/app/vite.config.preview.ts b/internal/vibe-tests/app/vite.config.preview.tsindex 65c6f810c9..d241ee3836 100644--- a/internal/vibe-tests/app/vite.config.preview.ts+++ b/internal/vibe-tests/app/vite.config.preview.ts@@ -2,6 +2,7 @@import path from 'node:path';import {fileURLToPath} from 'node:url';+import stylexResolution from '../../../scripts/stylex-module-resolution.cjs';import {defineConfig} from 'vite';import react from '@vitejs/plugin-react';import stylex from '@stylexjs/unplugin';@@ -44,10 +45,7 @@ export default defineConfig({dev: process.env.NODE_ENV === 'development',runtimeInjection: false,treeshakeCompensation: true,- unstable_moduleResolution: {- type: 'commonJS',- rootDir: repoRoot,- },+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,aliases: {'@astryxdesign/core/theme/tokens.stylex': path.resolve(repoRoot,diff --git a/internal/vibe-tests/app/vite.config.ts b/internal/vibe-tests/app/vite.config.tsindex 9f44d49c05..ba618bdb31 100644--- a/internal/vibe-tests/app/vite.config.ts+++ b/internal/vibe-tests/app/vite.config.ts@@ -2,6 +2,7 @@import path from 'node:path';import {fileURLToPath} from 'node:url';+import stylexResolution from '../../../scripts/stylex-module-resolution.cjs';import {defineConfig} from 'vite';import react from '@vitejs/plugin-react';import stylex from '@stylexjs/unplugin';@@ -36,10 +37,7 @@ export default defineConfig({dev: process.env.NODE_ENV === 'development',runtimeInjection: false,treeshakeCompensation: true,- unstable_moduleResolution: {- type: 'commonJS',- rootDir: repoRoot,- },+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,aliases: {'@astryxdesign/core/theme/tokens.stylex': path.resolve(repoRoot,diff --git a/packages/charts/babel.config.cjs b/packages/charts/babel.config.cjsnew file mode 100644index 0000000000..325709981b--- /dev/null+++ b/packages/charts/babel.config.cjs@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/* global module, require */++// StyleX resolves this package's imports of workspace `.stylex` files (core's+// tokens, markers) to their source files, as the workspace's other StyleX+// configs do: see scripts/stylex-module-resolution.cjs.+// eslint-disable-next-line @typescript-eslint/no-require-imports+const resolution = require('../../scripts/stylex-module-resolution.cjs');++module.exports = {+ presets: [+ ['@babel/preset-react', {runtime: 'automatic', development: false}],+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],+ ],+ plugins: [+ './babel-plugin-add-extensions.cjs',+ [+ '@stylexjs/babel-plugin',+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ unstable_moduleResolution: resolution.stylexModuleResolution,+ },+ ],+ ],+};diff --git a/packages/charts/babel.config.json b/packages/charts/babel.config.jsondeleted file mode 100644index 83f8a6a536..0000000000--- a/packages/charts/babel.config.json+++ /dev/null@@ -1,23 +0,0 @@-{- "presets": [- ["@babel/preset-react", {"runtime": "automatic", "development": false}],- ["@babel/preset-typescript", {"isTSX": true, "allExtensions": true}]- ],- "plugins": [- "./babel-plugin-add-extensions.cjs",- [- "@stylexjs/babel-plugin",- {- "dev": false,- "runtimeInjection": false,- "genConditionalClasses": true,- "treeshakeCompensation": true,- "aliases": {- "@astryxdesign/core/*": ["../../packages/core/src/*"],- "@astryxdesign/core": ["../../packages/core/src"]- },- "unstable_moduleResolution": {"type": "commonJS", "rootDir": "../.."}- }- ]- ]-}diff --git a/packages/charts/package.json b/packages/charts/package.jsonindex c749aee23e..ddb32dc3ae 100644--- a/packages/charts/package.json+++ b/packages/charts/package.json@@ -51,9 +51,9 @@"scripts": {"prepack": "pnpm build","build": "node ../../scripts/clean-dist.mjs && pnpm build:esm && tsc --project tsconfig.build.json && node ../../scripts/add-declaration-extensions.mjs && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs",- "build:esm": "babel src --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.json",+ "build:esm": "babel src --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.cjs","build:css": "node ../../scripts/build-css.mjs --package charts",- "dev": "babel src --watch --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.json",+ "dev": "babel src --watch --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.cjs","test": "vitest run --root ../..","test:watch": "vitest --root ../..","lint": "eslint src",diff --git a/packages/lab/babel.config.cjs b/packages/lab/babel.config.cjsnew file mode 100644index 0000000000..325709981b--- /dev/null+++ b/packages/lab/babel.config.cjs@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/* global module, require */++// StyleX resolves this package's imports of workspace `.stylex` files (core's+// tokens, markers) to their source files, as the workspace's other StyleX+// configs do: see scripts/stylex-module-resolution.cjs.+// eslint-disable-next-line @typescript-eslint/no-require-imports+const resolution = require('../../scripts/stylex-module-resolution.cjs');++module.exports = {+ presets: [+ ['@babel/preset-react', {runtime: 'automatic', development: false}],+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],+ ],+ plugins: [+ './babel-plugin-add-extensions.cjs',+ [+ '@stylexjs/babel-plugin',+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ unstable_moduleResolution: resolution.stylexModuleResolution,+ },+ ],+ ],+};diff --git a/packages/lab/babel.config.json b/packages/lab/babel.config.jsondeleted file mode 100644index 83f8a6a536..0000000000--- a/packages/lab/babel.config.json+++ /dev/null@@ -1,23 +0,0 @@-{- "presets": [- ["@babel/preset-react", {"runtime": "automatic", "development": false}],- ["@babel/preset-typescript", {"isTSX": true, "allExtensions": true}]- ],- "plugins": [- "./babel-plugin-add-extensions.cjs",- [- "@stylexjs/babel-plugin",- {- "dev": false,- "runtimeInjection": false,- "genConditionalClasses": true,- "treeshakeCompensation": true,- "aliases": {- "@astryxdesign/core/*": ["../../packages/core/src/*"],- "@astryxdesign/core": ["../../packages/core/src"]- },- "unstable_moduleResolution": {"type": "commonJS", "rootDir": "../.."}- }- ]- ]-}diff --git a/packages/lab/package.json b/packages/lab/package.jsonindex e8ed60b816..12be91f693 100644--- a/packages/lab/package.json+++ b/packages/lab/package.json@@ -51,9 +51,9 @@"scripts": {"prepack": "pnpm build","build": "node ../../scripts/clean-dist.mjs && pnpm build:esm && tsc --project tsconfig.build.json && node ../../scripts/add-declaration-extensions.mjs && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs",- "build:esm": "babel src --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.json",+ "build:esm": "babel src --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.cjs","build:css": "node ../../scripts/build-css.mjs --package lab",- "dev": "babel src --watch --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.json",+ "dev": "babel src --watch --out-dir dist --extensions .ts,.tsx --out-file-extension .js --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.cjs","test": "vitest run --root ../..","test:watch": "vitest --root ../..","lint": "eslint src",diff --git a/packages/richtext/babel.config.cjs b/packages/richtext/babel.config.cjsnew file mode 100644index 0000000000..325709981b--- /dev/null+++ b/packages/richtext/babel.config.cjs@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/* global module, require */++// StyleX resolves this package's imports of workspace `.stylex` files (core's+// tokens, markers) to their source files, as the workspace's other StyleX+// configs do: see scripts/stylex-module-resolution.cjs.+// eslint-disable-next-line @typescript-eslint/no-require-imports+const resolution = require('../../scripts/stylex-module-resolution.cjs');++module.exports = {+ presets: [+ ['@babel/preset-react', {runtime: 'automatic', development: false}],+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],+ ],+ plugins: [+ './babel-plugin-add-extensions.cjs',+ [+ '@stylexjs/babel-plugin',+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ unstable_moduleResolution: resolution.stylexModuleResolution,+ },+ ],+ ],+};diff --git a/packages/richtext/babel.config.json b/packages/richtext/babel.config.jsondeleted file mode 100644index 83f8a6a536..0000000000--- a/packages/richtext/babel.config.json+++ /dev/null@@ -1,23 +0,0 @@-{- "presets": [- ["@babel/preset-react", {"runtime": "automatic", "development": false}],- ["@babel/preset-typescript", {"isTSX": true, "allExtensions": true}]- ],- "plugins": [- "./babel-plugin-add-extensions.cjs",- [- "@stylexjs/babel-plugin",- {- "dev": false,- "runtimeInjection": false,- "genConditionalClasses": true,- "treeshakeCompensation": true,- "aliases": {- "@astryxdesign/core/*": ["../../packages/core/src/*"],- "@astryxdesign/core": ["../../packages/core/src"]- },- "unstable_moduleResolution": {"type": "commonJS", "rootDir": "../.."}- }- ]- ]-}diff --git a/packages/richtext/package.json b/packages/richtext/package.jsonindex d00e237611..16b45af5a8 100644--- a/packages/richtext/package.json+++ b/packages/richtext/package.json@@ -54,9 +54,9 @@"scripts": {"prepack": "pnpm build","build": "node ../../scripts/clean-dist.mjs && pnpm build:esm && tsc --project tsconfig.build.json && node ../../scripts/add-declaration-extensions.mjs && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs",- "build:esm": "babel src --out-dir dist --extensions \".ts,.tsx\" --out-file-extension \".js\" --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.json",+ "build:esm": "babel src --out-dir dist --extensions \".ts,.tsx\" --out-file-extension \".js\" --ignore \"**/*.test.ts,**/*.test.tsx,**/__tests__/**,**/*.perf.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css,**/*.css.d.ts\" --config-file ./babel.config.cjs","build:css": "node ../../scripts/build-css.mjs --package richtext",- "dev": "babel src --watch --out-dir dist --extensions \".ts,.tsx\" --out-file-extension \".js\" --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.json",+ "dev": "babel src --watch --out-dir dist --extensions \".ts,.tsx\" --out-file-extension \".js\" --ignore \"**/*.test.*,**/*.doc.mjs,**/*.d.ts,**/*.css*\" --config-file ./babel.config.cjs","test": "vitest run --root ../..","test:watch": "vitest --root ../..","lint": "eslint src",diff --git a/scripts/build-css.mjs b/scripts/build-css.mjsindex 5bc9fec867..237deed10e 100644--- a/scripts/build-css.mjs+++ b/scripts/build-css.mjs@@ -24,6 +24,7 @@import {transformAsync} from '@babel/core';import stylexBabelPlugin from '@stylexjs/babel-plugin';+import stylexResolution from './stylex-module-resolution.cjs';import fs from 'node:fs/promises';import path from 'node:path';import {fileURLToPath} from 'node:url';@@ -288,10 +289,8 @@ export async function collectStyleXCSS(target) {genConditionalClasses: true,treeshakeCompensation: true,aliases: target.aliases,- unstable_moduleResolution: {- type: 'commonJS',- rootDir: ROOT,- },+ unstable_moduleResolution:+ stylexResolution.stylexModuleResolution,},],],diff --git a/scripts/stylex-module-resolution.browser.test.mjs b/scripts/stylex-module-resolution.browser.test.mjsnew file mode 100644index 0000000000..27ac7a3c0d--- /dev/null+++ b/scripts/stylex-module-resolution.browser.test.mjs@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stylex-module-resolution.browser.test.mjs+ * @input Core's `indicatorScope` marker compiled by core's build, and a lab+ * rule on it compiled by lab's build; run with ASTRYX_STYLEX_BROWSER=1 after+ * installing Chromium (CI's test-build job does both)+ * @output Real-browser proof that a lab element styled with+ * `stylex.when.ancestor(':hover', indicatorScope)` changes when the core+ * element carrying the marker is hovered+ * @position The browser half of stylex-module-resolution.test.mjs: the names+ * agreeing is what makes the selector match, and this shows it does+ */++import fs from 'node:fs';+import path from 'node:path';++import {transformSync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import {chromium} from 'playwright';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';++const ROOT = path.resolve(import.meta.dirname, '..');+const CORE = path.join(ROOT, 'packages/core');+const LAB = path.join(ROOT, 'packages/lab');++const PROBE = `+import * as stylex from '@stylexjs/stylex';+import {indicatorScope} from '@astryxdesign/core/Indicator/indicator.markers.stylex';+export const styles = stylex.create({+ child: {+ color: {+ default: 'rgb(255, 0, 0)',+ [stylex.when.ancestor(':hover', indicatorScope)]: 'rgb(0, 0, 255)',+ },+ },+});+`;++describe.runIf(process.env.ASTRYX_STYLEX_BROWSER === '1')(+ "a lab rule on core's marker, in Chromium",+ () => {+ let browser;+ beforeAll(async () => {+ browser = await chromium.launch({args: ['--no-sandbox']});+ }, 60_000);+ afterAll(async () => {+ await browser?.close();+ });++ it('takes effect when the core owner is hovered', async () => {+ // The marker class core's own build gives indicatorScope.+ const markerFile = path.join(+ CORE,+ 'src/Indicator/indicator.markers.stylex.ts',+ );+ const marker = /\{\s*(\w+):\s*"\1"/.exec(+ transformSync(fs.readFileSync(markerFile, 'utf8'), {+ filename: markerFile,+ configFile: path.join(CORE, 'babel.config.json'),+ cwd: CORE,+ }).code,+ )[1];+ // The lab rule as lab's build compiles it, and its CSS.+ const lab = transformSync(PROBE, {+ filename: path.join(LAB, 'src/MarkerHoverProbe.tsx'),+ configFile: path.join(LAB, 'babel.config.cjs'),+ cwd: LAB,+ });+ const childClasses = /child:\s*\{([^}]*)\}/+ .exec(lab.code)[1]+ .match(/"(x\w+(?: x\w+)*)"/g)+ .map(value => value.slice(1, -1))+ .join(' ');+ const css = stylexBabelPlugin.processStylexRules(+ lab.metadata.stylex,+ false,+ );++ const page = await browser.newPage();+ try {+ await page.setContent(+ `<style>${css}</style>` ++ `<div id="owner" class="${marker}" style="padding: 40px">` ++ `<span id="child" class="${childClasses}">lab child</span></div>`,+ );+ const color = () =>+ page.$eval('#child', element => getComputedStyle(element).color);+ expect(await color()).toBe('rgb(255, 0, 0)');+ await page.hover('#owner');+ expect(await color()).toBe('rgb(0, 0, 255)');+ } finally {+ await page.close();+ }+ });+ },+);diff --git a/scripts/stylex-module-resolution.cjs b/scripts/stylex-module-resolution.cjsnew file mode 100644index 0000000000..49d993dba4--- /dev/null+++ b/scripts/stylex-module-resolution.cjs@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/**+ * @file stylex-module-resolution.cjs+ * @input An import specifier in a file StyleX compiles, and the importing file+ * @output StyleX's `unstable_moduleResolution` for this workspace: a `custom`+ * resolution whose `filePathResolver` maps a workspace package specifier to+ * that package's `exports` `source` target, and whose `getCanonicalFilePath`+ * is StyleX's own (`<package name>:<path inside the package>`).+ * @position Shared by every StyleX config that compiles source importing a+ * workspace package's `.stylex` files (the package builds, Vitest, Storybook,+ * Sandbox, the docsite, the vibe-test apps).+ *+ * StyleX names a `defineMarker`, `defineConsts` or hashed `defineVars` export+ * after the file that defines it, and an import site resolves its specifier to+ * compute the same name. Its built-in `commonJS` resolution tries a bare+ * specifier through Node resolution before any alias, so once core is built,+ * `@astryxdesign/core/Indicator/indicator.markers.stylex` resolves through+ * core's `exports` "default" to `dist/…stylex.js`, while core names the marker+ * after `src/…stylex.ts`. The two names differ, and a compile-time+ * `stylex.when.ancestor()` on a core marker never matches. Resolving workspace+ * specifiers to their `source` export names every export after the file the+ * package's own build compiles.+ */++const fs = require('node:fs');+const path = require('node:path');++const ROOT = path.resolve(__dirname, '..');+const WORKSPACE_ROOTS = ['packages', 'packages/themes', 'internal'];+const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];++const isFile = file => {+ try {+ return fs.statSync(file).isFile();+ } catch {+ return false;+ }+};+// As StyleX's own resolution: the path itself, then its base (without a code+// extension, which a build may have added: `tokens.stylex.js`) with each one.+const firstFile = file => {+ const extension = path.extname(file);+ const base = EXTENSIONS.includes(extension)+ ? file.slice(0, -extension.length)+ : file;+ return [file, ...EXTENSIONS.map(ext => base + ext)].find(isFile);+};++/** Workspace packages by name: their directory and `exports`. */+function readWorkspacePackages(root, workspaceRoots) {+ const packages = new Map();+ for (const workspaceRoot of workspaceRoots) {+ let entries = [];+ try {+ entries = fs.readdirSync(path.join(root, workspaceRoot), {+ withFileTypes: true,+ });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const dir = path.join(root, workspaceRoot, entry.name);+ try {+ const json = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ );+ if (json.name) packages.set(json.name, {dir, exports: json.exports});+ } catch {+ // Not a package.+ }+ }+ }+ return packages;+}++/** A workspace specifier's `source` export (or `src/<subpath>`), if any. */+function workspaceSource(packages, specifier) {+ const match = /^(@[^/]+\/[^/]+|[^./][^/]*)(?:\/(.+))?$/.exec(specifier);+ const pkg = match && packages.get(match[1]);+ if (!pkg) return undefined;+ const target = pkg.exports?.[match[2] ? `./${match[2]}` : '.'];+ if (+ target != null &&+ typeof target === 'object' &&+ typeof target.source === 'string'+ ) {+ return firstFile(path.join(pkg.dir, target.source));+ }+ return match[2] ? firstFile(path.join(pkg.dir, 'src', match[2])) : undefined;+}++/** Candidate paths for `specifier` from StyleX `aliases` (absolute targets). */+function aliasTargets(specifier, aliases) {+ const targets = [];+ for (const [alias, values] of Object.entries(aliases ?? {})) {+ const [before, after = ''] = alias.split('*');+ const matches = alias.includes('*')+ ? specifier.startsWith(before) && specifier.endsWith(after)+ : specifier === alias;+ if (!matches) continue;+ const rest = alias.includes('*')+ ? specifier.slice(before.length, specifier.length - after.length)+ : '';+ for (const value of values) {+ const target = value.split('*').join(rest);+ if (path.isAbsolute(target)) targets.push(target);+ }+ }+ return targets;+}++/** StyleX's `filePathResolver`: the file an import of a `.stylex` file names. */+function resolveFilePath(packages, importPath, sourceFilePath, aliases) {+ if (importPath.startsWith('.')) {+ return firstFile(path.resolve(path.dirname(sourceFilePath), importPath));+ }+ const source = workspaceSource(packages, importPath);+ if (source) return source;+ for (const target of aliasTargets(importPath, aliases)) {+ const file = firstFile(target);+ if (file) return file;+ }+ for (const candidate of [+ importPath,+ ...EXTENSIONS.map(ext => importPath + ext),+ ]) {+ try {+ return require.resolve(candidate, {+ paths: [path.dirname(sourceFilePath)],+ });+ } catch {+ // Try the next extension.+ }+ }+ return undefined;+}++/**+ * StyleX's own canonical name for a file: `<package name>:<path inside the+ * package>` from the nearest package.json (the name a package's own build gives+ * its exports), or the path from the repository root outside any package.+ */+function canonicalFilePath(root, filePath) {+ let dir = path.dirname(filePath);+ for (;;) {+ const manifest = path.join(dir, 'package.json');+ if (fs.existsSync(manifest)) {+ const {name} = JSON.parse(fs.readFileSync(manifest, 'utf8'));+ return `${name}:${path.relative(dir, filePath)}`;+ }+ const parent = path.dirname(dir);+ if (parent === dir) return path.relative(root, filePath);+ dir = parent;+ }+}++/**+ * The resolution for a workspace at `root` whose packages sit one level below+ * `workspaceRoots` (this repository's by default; a test passes a fixture).+ */+function createStylexModuleResolution({+ root = ROOT,+ workspaceRoots = WORKSPACE_ROOTS,+} = {}) {+ let packages = null;+ const workspace = () =>+ (packages ??= readWorkspacePackages(root, workspaceRoots));+ return {+ type: 'custom',+ filePathResolver: (importPath, sourceFilePath, aliases) =>+ resolveFilePath(workspace(), importPath, sourceFilePath, aliases),+ getCanonicalFilePath: filePath => canonicalFilePath(root, filePath),+ };+}++const stylexModuleResolution = createStylexModuleResolution();++module.exports = {stylexModuleResolution, createStylexModuleResolution};diff --git a/scripts/stylex-module-resolution.d.cts b/scripts/stylex-module-resolution.d.ctsnew file mode 100644index 0000000000..fe3fc33eba--- /dev/null+++ b/scripts/stylex-module-resolution.d.cts@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stylex-module-resolution.d.cts+ * @output Types for stylex-module-resolution.cjs, for the TypeScript configs+ * (Storybook, Sandbox, Vitest, the vibe-test apps) that import it+ */++/** StyleX's `unstable_moduleResolution` of type `custom`. */+interface StylexCustomModuleResolution {+ type: 'custom';+ filePathResolver: (+ importPath: string,+ sourceFilePath: string,+ aliases: null | undefined | Readonly<Record<string, ReadonlyArray<string>>>,+ ) => string | undefined;+ getCanonicalFilePath: (filePath: string) => string;+}++declare const resolution: {+ /** The resolution for this repository's workspace. */+ stylexModuleResolution: StylexCustomModuleResolution;+ /** The resolution for a workspace at `root` (a test passes a fixture). */+ createStylexModuleResolution(options?: {+ root?: string;+ workspaceRoots?: ReadonlyArray<string>;+ }): StylexCustomModuleResolution;+};++export = resolution;diff --git a/scripts/stylex-module-resolution.test.mjs b/scripts/stylex-module-resolution.test.mjsnew file mode 100644index 0000000000..2bbdaff667--- /dev/null+++ b/scripts/stylex-module-resolution.test.mjs@@ -0,0 +1,196 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stylex-module-resolution.test.mjs+ *+ * A compile-time `stylex.when.ancestor()` on another workspace package's+ * marker matches only if the importing compile names the marker exactly as+ * the defining package's own build does. StyleX's built-in `commonJS`+ * resolution resolves a built package's specifier to its `dist` file, whose+ * canonical name differs from the `src` file the package compiled; the shared+ * resolution resolves it to the `source` export.+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {createRequire} from 'node:module';++import yaml from 'yaml';++import {transformSync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import {afterAll, describe, expect, it} from 'vitest';++const require = createRequire(import.meta.url);+const {+ createStylexModuleResolution,+} = require('./stylex-module-resolution.cjs');++const ROOT = path.resolve(import.meta.dirname, '..');++const PROBE = `+import * as stylex from '@stylexjs/stylex';+import {scope} from '@probe/core/marker.stylex';+export const styles = stylex.create({+ child: {color: {default: 'red', [stylex.when.ancestor(':hover', scope)]: 'blue'}},+});+`;++/** The marker class a compile gives `defineMarker`, from its emitted object. */+const markerClass = code => /\{\s*(\w+):\s*"\1"/.exec(code)?.[1];+/** The marker class in a compile's `:where(.<marker>:hover *)` rule. */+const ancestorClass = rules =>+ rules+ .map(([, css]) => /:where\(\.(\w+):hover \*\)/.exec(css.ltr)?.[1])+ .find(Boolean);++function compile(code, filename, unstable_moduleResolution) {+ return transformSync(code, {+ babelrc: false,+ configFile: false,+ filename,+ presets: [['@babel/preset-typescript', {isTSX: true, allExtensions: true}]],+ plugins: [+ [+ stylexBabelPlugin,+ {dev: false, runtimeInjection: false, unstable_moduleResolution},+ ],+ ],+ });+}++describe('a marker from another workspace package', () => {+ // Two packages, the way core and lab sit: `@probe/core` exports its marker+ // with a `source` condition and a built `dist` file, and `@probe/lab`+ // reaches it through node_modules.+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'stylex-resolution-'));+ afterAll(() => fs.rmSync(root, {recursive: true, force: true}));+ const core = path.join(root, 'packages/core');+ const lab = path.join(root, 'packages/lab');+ const marker =+ "import * as stylex from '@stylexjs/stylex';\nexport const scope = stylex.defineMarker();\n";+ const write = (file, text) => {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, text);+ };+ write(+ path.join(core, 'package.json'),+ JSON.stringify({+ name: '@probe/core',+ exports: {+ './marker.stylex': {+ source: './src/marker.stylex.ts',+ default: './dist/marker.stylex.js',+ },+ },+ }),+ );+ write(path.join(core, 'src/marker.stylex.ts'), marker);+ write(path.join(core, 'dist/marker.stylex.js'), marker);+ write(path.join(lab, 'package.json'), JSON.stringify({name: '@probe/lab'}));+ fs.mkdirSync(path.join(lab, 'node_modules/@probe'), {recursive: true});+ fs.symlinkSync(core, path.join(lab, 'node_modules/@probe/core'), 'dir');+ const probe = path.join(lab, 'src/Probe.tsx');+ write(probe, PROBE);++ // The defining package's own build: StyleX's resolution, its own root.+ const coreClass = markerClass(+ compile(marker, path.join(core, 'src/marker.stylex.ts'), {+ type: 'commonJS',+ rootDir: core,+ }).code,+ );++ it('is named after its dist file by the built-in resolution', () => {+ const rules = compile(PROBE, probe, {type: 'commonJS', rootDir: root})+ .metadata.stylex;+ expect(coreClass).toMatch(/^x\w+$/);+ expect(ancestorClass(rules)).not.toBe(coreClass);+ });++ it('is named after its source file, as its package names it, by the shared resolution', () => {+ const resolution = createStylexModuleResolution({+ root,+ workspaceRoots: ['packages'],+ });+ const rules = compile(PROBE, probe, resolution).metadata.stylex;+ expect(ancestorClass(rules)).toBe(coreClass);+ });+});++describe("lab's build and core's build", () => {+ it("name core's indicatorScope alike", () => {+ const corePackage = path.join(ROOT, 'packages/core');+ const markerFile = path.join(+ corePackage,+ 'src/Indicator/indicator.markers.stylex.ts',+ );+ const coreClass = markerClass(+ transformSync(fs.readFileSync(markerFile, 'utf8'), {+ filename: markerFile,+ configFile: path.join(corePackage, 'babel.config.json'),+ cwd: corePackage,+ }).code,+ );+ const labPackage = path.join(ROOT, 'packages/lab');+ const source = `+import * as stylex from '@stylexjs/stylex';+import {indicatorScope} from '@astryxdesign/core/Indicator/indicator.markers.stylex';+export const styles = stylex.create({+ tint: {color: {default: 'red', [stylex.when.ancestor(':hover', indicatorScope)]: 'blue'}},+});+`;+ const rules = transformSync(source, {+ filename: path.join(labPackage, 'src/MarkerProbe.tsx'),+ configFile: path.join(labPackage, 'babel.config.cjs'),+ cwd: labPackage,+ }).metadata.stylex;+ expect(coreClass).toMatch(/^x\w+$/);+ expect(ancestorClass(rules)).toBe(coreClass);+ });+});++describe('StyleX configs', () => {+ // Every config that compiles workspace source against another package's+ // `.stylex` files uses the shared resolution, not StyleX's built-in one.+ it.each([+ 'packages/lab/babel.config.cjs',+ 'packages/charts/babel.config.cjs',+ 'packages/richtext/babel.config.cjs',+ 'scripts/build-css.mjs',+ 'vitest.config.ts',+ 'apps/storybook/.storybook/main.ts',+ 'apps/storybook/vite.config.ts',+ 'apps/sandbox/vite.config.mts',+ 'apps/docsite/babel.config.js',+ 'internal/vibe-tests/app/vite.config.ts',+ 'internal/vibe-tests/app/vite.config.preview.ts',+ ])('%s uses the shared resolution', file => {+ const text = fs.readFileSync(path.join(ROOT, file), 'utf8');+ expect(text).toContain('stylex-module-resolution.cjs');+ expect(text).not.toMatch(/type: ['"]commonJS['"]/);+ });+});++describe('the browser check', () => {+ it('runs in test-build after Chromium is installed', () => {+ const ci = yaml.parse(+ fs.readFileSync(path.join(ROOT, '.github/workflows/ci.yml'), 'utf8'),+ );+ const steps = ci.jobs['test-build'].steps;+ const install = steps.findIndex(+ step => step.run === 'npx playwright install chromium',+ );+ const check = steps.findIndex(+ step => step.name === 'Run cross-package StyleX marker browser check',+ );+ expect(install).toBeGreaterThanOrEqual(0);+ expect(check).toBeGreaterThan(install);+ expect(steps[check].env).toEqual({ASTRYX_STYLEX_BROWSER: '1'});+ expect(steps[check].run).toContain(+ 'scripts/stylex-module-resolution.browser.test.mjs',+ );+ expect(steps[check]['continue-on-error']).toBeUndefined();+ });+});diff --git a/vitest.config.ts b/vitest.config.tsindex c9f2cf8f9a..b8d51274f1 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -21,6 +21,7 @@import path from 'node:path';import {configDefaults, defineConfig} from 'vitest/config';import react from '@vitejs/plugin-react';+import stylexResolution from './scripts/stylex-module-resolution.cjs';const rootDir = path.resolve(__dirname, '.');const coreSrc = path.resolve(__dirname, 'packages/core/src');@@ -44,10 +45,8 @@ export default defineConfig({],'@astryxdesign/core': [path.join(rootDir, 'packages/core/src')],},- unstable_moduleResolution: {- type: 'commonJS',- rootDir: rootDir,- },+ unstable_moduleResolution:+ stylexResolution.stylexModuleResolution,},],],