An open source design system that's fully customizable and agent ready
TypeScript
fix(build): add mandatory ESM extensions to dynamic import() specifiers in dist (#4571)
AK68966d2fa6c4
diff --git a/.changeset/fix-esm-dynamic-import-extensions.md b/.changeset/fix-esm-dynamic-import-extensions.mdnew file mode 100644index 0000000000..958e5de1db--- /dev/null+++ b/.changeset/fix-esm-dynamic-import-extensions.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Dynamic `import()` specifiers now get their mandatory `.js` extension in the published ESM dist — `babel-plugin-add-extensions` only rewrote static import/export declarations, so the lazy Tooltip specifier in `Text`, `Heading` and `Timestamp` shipped extensionless and strict-ESM consumers (Rspack, webpack `fullySpecified`, Node ESM) failed to resolve any component importing them. A new post-build gate (`scripts/check-fully-specified.mjs`) now fails any build whose dist ships an extensionless relative specifier. (#4569)+@AKnassadiff --git a/.github/scripts/accessibility-audit.js b/.github/scripts/accessibility-audit.jsindex 2ab65324be..dcb74a45b4 100644--- a/.github/scripts/accessibility-audit.js+++ b/.github/scripts/accessibility-audit.js@@ -34,8 +34,13 @@ const hasFlag = (name) => args.includes(`--${name}`);const storybookDir = getArg('storybook-dir') || 'apps/storybook/dist';const outputFile = getArg('output') || 'a11y-report.json';-const componentsArg = getArg('components') || '';-const components = componentsArg.split(',').filter(Boolean);+const componentsArg = getArg('components');+const components = (componentsArg || '').split(',').filter(Boolean);+// --components present but EMPTY means the caller derived an explicit empty+// audit set (pr-a11y on a PR whose core/src changes map to no component —+// e.g. a shared test file). Audit nothing and pass. Only an ABSENT flag+// means "all stories" (the a11y-weekly contract).+const emptyComponentSet = componentsArg !== null && components.length === 0;const baselineFile = getArg('baseline');const failOnNew = hasFlag('fail-on-new');const updateBaseline = hasFlag('update-baseline');@@ -108,6 +113,17 @@ async function getStories(storybookPath) {async function runAccessibilityAudit() {console.log('Starting accessibility audit...');++ if (emptyComponentSet) {+ console.log('No components to audit (--components is empty) — skipping.');+ const report = {+ components: {},+ summary: { componentsAudited: 0, totalViolations: 0 },+ };+ fs.writeFileSync(outputFile, JSON.stringify(report, null, 2));+ return report;+ }+console.log(`Components to audit: ${components.length > 0 ? components.join(', ') : 'all affected'}`);const storybookPath = path.resolve(process.cwd(), storybookDir);diff --git a/.github/scripts/accessibility-audit.test.mjs b/.github/scripts/accessibility-audit.test.mjsnew file mode 100644index 0000000000..fecbb8e6f0--- /dev/null+++ b/.github/scripts/accessibility-audit.test.mjs@@ -0,0 +1,75 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file accessibility-audit.test.mjs+ * Pins the --components contract of the a11y audit CLI. The pr-a11y job+ * derives its component list from the PR analysis and passes it as+ * `--components "$COMPONENTS"`; when a core/src change maps to no component+ * (a shared test file, docs-types.ts, …) that list is EMPTY, and the audit+ * must skip and pass rather than fan out into a full-repo audit that fails+ * on violations the PR never touched. An ABSENT --components flag keeps the+ * a11y-weekly contract: audit all stories.+ */++import {execFileSync} from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, it, expect} from 'vitest';++const SCRIPTS_DIR = path.dirname(fileURLToPath(import.meta.url));+const SCRIPT = path.join(SCRIPTS_DIR, 'accessibility-audit.js');+const BASELINE = path.resolve(SCRIPTS_DIR, '..', 'a11y-baseline.json');++/** Run the audit CLI in an empty temp cwd; return {stdout, report}. */+function runAudit(args) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'a11y-audit-'));+ try {+ const stdout = execFileSync(+ process.execPath,+ [SCRIPT, '--output', 'report.json', ...args],+ {cwd: dir, encoding: 'utf8'},+ );+ const report = JSON.parse(+ fs.readFileSync(path.join(dir, 'report.json'), 'utf8'),+ );+ return {stdout, report};+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+}++describe('accessibility-audit --components contract', () => {+ it('audits nothing and passes when --components is explicitly empty', () => {+ // The exact pr-a11y invocation shape for a PR whose analysis found no+ // new or modified components. execFileSync throws on a non-zero exit,+ // so reaching the assertions proves the gate passed.+ const {stdout, report} = runAudit([+ '--components',+ '',+ '--baseline',+ BASELINE,+ '--fail-on-new',+ ]);+ expect(stdout).toContain('No components to audit');+ expect(report.components).toEqual({});+ expect(report.summary.totalViolations).toBe(0);+ });++ it('still audits all stories when the flag is absent (a11y-weekly)', () => {+ // No storybook build exists in the temp cwd, so the all-stories path+ // reports the missing build instead of skipping — absent ≠ empty.+ const {stdout, report} = runAudit([]);+ expect(stdout).not.toContain('No components to audit');+ expect(stdout).toContain('all affected');+ expect(report.error).toBe('Storybook not built');+ });++ it('proceeds to audit when --components names components', () => {+ const {stdout, report} = runAudit(['--components', 'Text,Heading']);+ expect(stdout).not.toContain('No components to audit');+ expect(stdout).toContain('Text, Heading');+ expect(report.error).toBe('Storybook not built');+ });+});diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e12f86f925..ff45c55997 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -101,7 +101,7 @@ jobs:echo "has_components=true" >> $GITHUB_OUTPUTexit 0fi- CHANGED=$(git diff --name-only origin/${{ github.base_ref }}...HEAD -- packages/core/src/ | grep -v -E '(hooks|theme|utils)/' | head -1)+ CHANGED=$(git diff --name-only origin/${{ github.base_ref }}...HEAD -- packages/core/src/ | grep -v -E '(hooks|theme|utils|__tests__)/' | head -1)echo "has_components=$( [ -n "$CHANGED" ] && echo true || echo false )" >> $GITHUB_OUTPUT# Run tests (parallel with build)diff --git a/packages/charts/babel-plugin-add-extensions.cjs b/packages/charts/babel-plugin-add-extensions.cjsindex 3c6f15956a..6139ec4a68 100644--- a/packages/charts/babel-plugin-add-extensions.cjs+++ b/packages/charts/babel-plugin-add-extensions.cjs@@ -9,7 +9,11 @@* This plugin rewrites them during compilation so no postbuild step is needed.** Handles both file imports ('./XDSButton' → './XDSButton.js') and- * directory imports ('./domainTokens' → './domainTokens/index.js').+ * directory imports ('./domainTokens' → './domainTokens/index.js'), for+ * static import/export declarations and dynamic `import()` calls alike.+ * Dynamic specifiers otherwise reach dist verbatim and break strict-ESM+ * consumers (#4569). Babel 7 parses `import()` as a CallExpression with an+ * `Import` callee; Babel 8 emits an `ImportExpression` node — both handled.*/const fs = require('node:fs');const nodePath = require('node:path');@@ -17,6 +21,43 @@ const nodePath = require('node:path');module.exports = function addExtensions() {const SKIP = /\.(?:js|mjs|cjs|json|css)$/;+ /**+ * Rewrite one StringLiteral specifier node in place. `state` is the babel+ * plugin pass (state.filename = the importing source file).+ */+ function rewriteSpecifier(source, state) {+ const value = source.value;++ // Compat alias barrels self-re-export from `'.'` in source. Node ESM+ // does not support directory imports in built output, so make the self+ // reference explicit (`./index.js`) during compilation.+ if (value === '.') {+ source.value = './index.js';+ return;+ }+ if (value === '..') {+ source.value = '../index.js';+ return;+ }++ if (!value.startsWith('./') && !value.startsWith('../')) return;+ if (SKIP.test(value)) return;++ const dir = nodePath.dirname(state.filename);+ const asFile = nodePath.join(dir, value + '.ts');+ const asTsx = nodePath.join(dir, value + '.tsx');+ const asIndex = nodePath.join(dir, value, 'index.ts');+ const asIndexTsx = nodePath.join(dir, value, 'index.tsx');++ if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {+ source.value = value + '.js';+ } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {+ source.value = value + '/index.js';+ } else {+ source.value = value + '.js';+ }+ }+return {visitor: {'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(@@ -25,36 +66,21 @@ module.exports = function addExtensions() {) {const source = path.node.source;if (!source) return;- const value = source.value;-- // Compat alias barrels self-re-export from `'.'` in source. Node ESM- // does not support directory imports in built output, so make the self- // reference explicit (`./index.js`) during compilation.- if (value === '.') {- source.value = './index.js';- return;- }- if (value === '..') {- source.value = '../index.js';- return;- }-- if (!value.startsWith('./') && !value.startsWith('../')) return;- if (SKIP.test(value)) return;-- const dir = nodePath.dirname(state.filename);- const asFile = nodePath.join(dir, value + '.ts');- const asTsx = nodePath.join(dir, value + '.tsx');- const asIndex = nodePath.join(dir, value, 'index.ts');- const asIndexTsx = nodePath.join(dir, value, 'index.tsx');-- if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {- source.value = value + '.js';- } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {- source.value = value + '/index.js';- } else {- source.value = value + '.js';- }+ rewriteSpecifier(source, state);+ },+ // Dynamic import() under Babel 7. Only literal specifiers are+ // rewritten; computed ones cannot be resolved at build time.+ CallExpression(path, state) {+ if (path.node.callee.type !== 'Import') return;+ const [specifier] = path.node.arguments;+ if (!specifier || specifier.type !== 'StringLiteral') return;+ rewriteSpecifier(specifier, state);+ },+ // Dynamic import() under Babel 8 (or createImportExpressions parsing).+ ImportExpression(path, state) {+ const source = path.node.source;+ if (!source || source.type !== 'StringLiteral') return;+ rewriteSpecifier(source, state);},},};diff --git a/packages/charts/package.json b/packages/charts/package.jsonindex f53da82a07..a3b45a2511 100644--- a/packages/charts/package.json+++ b/packages/charts/package.json@@ -46,7 +46,7 @@},"scripts": {"prepack": "pnpm build",- "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs",+ "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && 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.js","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.js",diff --git a/packages/core/babel-plugin-add-extensions.cjs b/packages/core/babel-plugin-add-extensions.cjsindex 3c6f15956a..6139ec4a68 100644--- a/packages/core/babel-plugin-add-extensions.cjs+++ b/packages/core/babel-plugin-add-extensions.cjs@@ -9,7 +9,11 @@* This plugin rewrites them during compilation so no postbuild step is needed.** Handles both file imports ('./XDSButton' → './XDSButton.js') and- * directory imports ('./domainTokens' → './domainTokens/index.js').+ * directory imports ('./domainTokens' → './domainTokens/index.js'), for+ * static import/export declarations and dynamic `import()` calls alike.+ * Dynamic specifiers otherwise reach dist verbatim and break strict-ESM+ * consumers (#4569). Babel 7 parses `import()` as a CallExpression with an+ * `Import` callee; Babel 8 emits an `ImportExpression` node — both handled.*/const fs = require('node:fs');const nodePath = require('node:path');@@ -17,6 +21,43 @@ const nodePath = require('node:path');module.exports = function addExtensions() {const SKIP = /\.(?:js|mjs|cjs|json|css)$/;+ /**+ * Rewrite one StringLiteral specifier node in place. `state` is the babel+ * plugin pass (state.filename = the importing source file).+ */+ function rewriteSpecifier(source, state) {+ const value = source.value;++ // Compat alias barrels self-re-export from `'.'` in source. Node ESM+ // does not support directory imports in built output, so make the self+ // reference explicit (`./index.js`) during compilation.+ if (value === '.') {+ source.value = './index.js';+ return;+ }+ if (value === '..') {+ source.value = '../index.js';+ return;+ }++ if (!value.startsWith('./') && !value.startsWith('../')) return;+ if (SKIP.test(value)) return;++ const dir = nodePath.dirname(state.filename);+ const asFile = nodePath.join(dir, value + '.ts');+ const asTsx = nodePath.join(dir, value + '.tsx');+ const asIndex = nodePath.join(dir, value, 'index.ts');+ const asIndexTsx = nodePath.join(dir, value, 'index.tsx');++ if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {+ source.value = value + '.js';+ } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {+ source.value = value + '/index.js';+ } else {+ source.value = value + '.js';+ }+ }+return {visitor: {'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(@@ -25,36 +66,21 @@ module.exports = function addExtensions() {) {const source = path.node.source;if (!source) return;- const value = source.value;-- // Compat alias barrels self-re-export from `'.'` in source. Node ESM- // does not support directory imports in built output, so make the self- // reference explicit (`./index.js`) during compilation.- if (value === '.') {- source.value = './index.js';- return;- }- if (value === '..') {- source.value = '../index.js';- return;- }-- if (!value.startsWith('./') && !value.startsWith('../')) return;- if (SKIP.test(value)) return;-- const dir = nodePath.dirname(state.filename);- const asFile = nodePath.join(dir, value + '.ts');- const asTsx = nodePath.join(dir, value + '.tsx');- const asIndex = nodePath.join(dir, value, 'index.ts');- const asIndexTsx = nodePath.join(dir, value, 'index.tsx');-- if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {- source.value = value + '.js';- } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {- source.value = value + '/index.js';- } else {- source.value = value + '.js';- }+ rewriteSpecifier(source, state);+ },+ // Dynamic import() under Babel 7. Only literal specifiers are+ // rewritten; computed ones cannot be resolved at build time.+ CallExpression(path, state) {+ if (path.node.callee.type !== 'Import') return;+ const [specifier] = path.node.arguments;+ if (!specifier || specifier.type !== 'StringLiteral') return;+ rewriteSpecifier(specifier, state);+ },+ // Dynamic import() under Babel 8 (or createImportExpressions parsing).+ ImportExpression(path, state) {+ const source = path.node.source;+ if (!source || source.type !== 'StringLiteral') return;+ rewriteSpecifier(source, state);},},};diff --git a/packages/core/package.json b/packages/core/package.jsonindex d948fd7e08..6c2aa24cb9 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -651,7 +651,7 @@"scripts": {"prepack": "pnpm build","postinstall": "node scripts/postinstall.mjs",- "build": "rimraf dist && pnpm build:i18n && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css && pnpm build:umd && node ../../scripts/check-no-dev-jsx.mjs",+ "build": "rimraf dist && pnpm build:i18n && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css && pnpm build:umd && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs","build:i18n": "node scripts/build-pseudo-locale.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:css": "node ../../scripts/build-css.mjs",diff --git a/packages/core/src/__tests__/babelPluginAddExtensions.test.ts b/packages/core/src/__tests__/babelPluginAddExtensions.test.tsnew file mode 100644index 0000000000..441b38328b--- /dev/null+++ b/packages/core/src/__tests__/babelPluginAddExtensions.test.ts@@ -0,0 +1,190 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Guards the build-time babel plugin that rewrites extensionless relative+ * specifiers to fully-specified ESM paths in dist (issue #4569: dynamic+ * `import()` specifiers were passed through untouched, so the published+ * "type": "module" dist broke strict-ESM consumers like Rspack and Node).+ *+ * The plugin resolves specifiers against the importing file's real directory+ * (fs.existsSync on .ts/.tsx/index siblings), so the file/directory cases run+ * against a temp fixture tree, and one case pins the exact in-repo bug site+ * (Text.tsx lazily importing ../Tooltip/Tooltip).+ */+import fs from 'node:fs';+import os from 'node:os';+import {createRequire} from 'node:module';+import path from 'node:path';+import {describe, it, expect, beforeAll, afterAll} from 'vitest';++const require = createRequire(__filename);+const babel = require('@babel/core');+const addExtensions = require('../../babel-plugin-add-extensions.cjs');++/** Transform a snippet exactly as build:esm does for `filename`. */+function transform(+ code: string,+ filename: string,+ parserOpts?: Record<string, unknown>,+): string {+ const result = babel.transformSync(code, {+ filename,+ configFile: false,+ babelrc: false,+ plugins: [addExtensions],+ ...(parserOpts ? {parserOpts} : {}),+ });+ return result?.code ?? '';+}++const textTsx = path.resolve(__dirname, '../Text/Text.tsx');++let fixtureDir: string;+let entry: string;++beforeAll(() => {+ fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'add-extensions-'));+ fs.writeFileSync(path.join(fixtureDir, 'mod.ts'), 'export const x = 1;\n');+ fs.mkdirSync(path.join(fixtureDir, 'dir'));+ fs.writeFileSync(+ path.join(fixtureDir, 'dir', 'index.ts'),+ 'export const y = 2;\n',+ );+ // `both` exists as a file AND a directory-with-index — the file must win.+ fs.writeFileSync(path.join(fixtureDir, 'both.ts'), 'export const b = 3;\n');+ fs.mkdirSync(path.join(fixtureDir, 'both'));+ fs.writeFileSync(+ path.join(fixtureDir, 'both', 'index.ts'),+ 'export const bi = 4;\n',+ );+ // The importing file itself never needs to exist — the plugin only uses+ // its dirname as the resolution base.+ entry = path.join(fixtureDir, 'entry.ts');+});++afterAll(() => {+ fs.rmSync(fixtureDir, {recursive: true, force: true});+});++describe('babel-plugin-add-extensions', () => {+ describe('dynamic import()', () => {+ it('appends .js to a dynamic import() of a relative file', () => {+ // The exact shape of the LazyXDSTooltip sites in Text/Heading/Timestamp.+ const code = transform(+ "const LazyXDSTooltip = lazy(async () => import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})));",+ textTsx,+ );+ expect(code).toMatch(/import\(['"]\.\.\/Tooltip\/Tooltip\.js['"]\)/);+ });++ it('rewrites a dynamic import() of a directory to its index.js', () => {+ const code = transform("const p = import('./dir');", entry);+ expect(code).toMatch(/import\(['"]\.\/dir\/index\.js['"]\)/);+ });++ it('leaves a dynamic import() that already has an extension alone', () => {+ const code = transform("const p = import('./mod.js');", entry);+ expect(code).toMatch(/import\(['"]\.\/mod\.js['"]\)/);+ });++ it('leaves a dynamic import() of a bare specifier alone', () => {+ const code = transform("const p = import('react');", entry);+ expect(code).toMatch(/import\(['"]react['"]\)/);+ });++ it('leaves a dynamic import() of a non-literal specifier alone', () => {+ const code = transform('const p = (s) => import(s);', entry);+ expect(code).toContain('import(s)');+ });++ it('leaves a dynamic import() of a template literal alone', () => {+ const code = transform(+ 'const p = (n) => import(`./locales/${n}`);',+ entry,+ );+ expect(code).toContain('import(`./locales/${n}`)');+ });++ it('rewrites ImportExpression nodes (Babel 8 / createImportExpressions parse)', () => {+ const code = transform("const p = import('./mod');", entry, {+ createImportExpressions: true,+ });+ expect(code).toMatch(/import\(['"]\.\/mod\.js['"]\)/);+ });++ it('prefers the file over a same-named directory index', () => {+ const code = transform("const p = import('./both');", entry);+ expect(code).toMatch(/import\(['"]\.\/both\.js['"]\)/);+ });++ it("rewrites a dynamic import of '.' to './index.js'", () => {+ const code = transform("const p = import('.');", entry);+ expect(code).toMatch(/import\(['"]\.\/index\.js['"]\)/);+ });++ it('rewrites every dynamic import in a file', () => {+ const code = transform(+ "const a = import('./mod');\nconst b = import('./dir');",+ entry,+ );+ expect(code).toMatch(/import\(['"]\.\/mod\.js['"]\)/);+ expect(code).toMatch(/import\(['"]\.\/dir\/index\.js['"]\)/);+ });++ it('leaves a dynamic import() of a skipped extension alone', () => {+ const code = transform("const p = import('./data.json');", entry);+ expect(code).toMatch(/import\(['"]\.\/data\.json['"]\)/);+ });++ it('does not touch call expressions that are not import()', () => {+ const code = transform(+ "myImport('./mod');\nregistry.import('./mod');",+ entry,+ );+ expect(code).toContain("myImport('./mod')");+ expect(code).toContain("registry.import('./mod')");+ });+ });++ describe('static declarations (pre-existing behavior)', () => {+ it('appends .js to a static import of a relative file', () => {+ const code = transform("import {x} from './mod';", entry);+ expect(code).toMatch(/from ['"]\.\/mod\.js['"]/);+ });++ it('rewrites a static import of a directory to its index.js', () => {+ const code = transform("import {y} from './dir';", entry);+ expect(code).toMatch(/from ['"]\.\/dir\/index\.js['"]/);+ });++ it('appends .js to a re-export specifier', () => {+ const code = transform("export {x} from './mod';", entry);+ expect(code).toMatch(/from ['"]\.\/mod\.js['"]/);+ });++ it('appends .js to an export * specifier', () => {+ const code = transform("export * from './mod';", entry);+ expect(code).toMatch(/from ['"]\.\/mod\.js['"]/);+ });++ it("rewrites the '.' self-reference to './index.js'", () => {+ const code = transform("export * from '.';", entry);+ expect(code).toMatch(/from ['"]\.\/index\.js['"]/);+ });++ it('leaves bare specifiers alone', () => {+ const code = transform("import {lazy} from 'react';", entry);+ expect(code).toMatch(/from ['"]react['"]/);+ });++ it('appends .js even when no source sibling exists (fallback branch)', () => {+ const code = transform("import {z} from './does-not-exist';", entry);+ expect(code).toMatch(/from ['"]\.\/does-not-exist\.js['"]/);+ });++ it('leaves declarations without a source untouched', () => {+ const code = transform('export const a = 1;', entry);+ expect(code).toContain('export const a = 1;');+ });+ });+});diff --git a/packages/lab/babel-plugin-add-extensions.cjs b/packages/lab/babel-plugin-add-extensions.cjsindex 3c6f15956a..6139ec4a68 100644--- a/packages/lab/babel-plugin-add-extensions.cjs+++ b/packages/lab/babel-plugin-add-extensions.cjs@@ -9,7 +9,11 @@* This plugin rewrites them during compilation so no postbuild step is needed.** Handles both file imports ('./XDSButton' → './XDSButton.js') and- * directory imports ('./domainTokens' → './domainTokens/index.js').+ * directory imports ('./domainTokens' → './domainTokens/index.js'), for+ * static import/export declarations and dynamic `import()` calls alike.+ * Dynamic specifiers otherwise reach dist verbatim and break strict-ESM+ * consumers (#4569). Babel 7 parses `import()` as a CallExpression with an+ * `Import` callee; Babel 8 emits an `ImportExpression` node — both handled.*/const fs = require('node:fs');const nodePath = require('node:path');@@ -17,6 +21,43 @@ const nodePath = require('node:path');module.exports = function addExtensions() {const SKIP = /\.(?:js|mjs|cjs|json|css)$/;+ /**+ * Rewrite one StringLiteral specifier node in place. `state` is the babel+ * plugin pass (state.filename = the importing source file).+ */+ function rewriteSpecifier(source, state) {+ const value = source.value;++ // Compat alias barrels self-re-export from `'.'` in source. Node ESM+ // does not support directory imports in built output, so make the self+ // reference explicit (`./index.js`) during compilation.+ if (value === '.') {+ source.value = './index.js';+ return;+ }+ if (value === '..') {+ source.value = '../index.js';+ return;+ }++ if (!value.startsWith('./') && !value.startsWith('../')) return;+ if (SKIP.test(value)) return;++ const dir = nodePath.dirname(state.filename);+ const asFile = nodePath.join(dir, value + '.ts');+ const asTsx = nodePath.join(dir, value + '.tsx');+ const asIndex = nodePath.join(dir, value, 'index.ts');+ const asIndexTsx = nodePath.join(dir, value, 'index.tsx');++ if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {+ source.value = value + '.js';+ } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {+ source.value = value + '/index.js';+ } else {+ source.value = value + '.js';+ }+ }+return {visitor: {'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(@@ -25,36 +66,21 @@ module.exports = function addExtensions() {) {const source = path.node.source;if (!source) return;- const value = source.value;-- // Compat alias barrels self-re-export from `'.'` in source. Node ESM- // does not support directory imports in built output, so make the self- // reference explicit (`./index.js`) during compilation.- if (value === '.') {- source.value = './index.js';- return;- }- if (value === '..') {- source.value = '../index.js';- return;- }-- if (!value.startsWith('./') && !value.startsWith('../')) return;- if (SKIP.test(value)) return;-- const dir = nodePath.dirname(state.filename);- const asFile = nodePath.join(dir, value + '.ts');- const asTsx = nodePath.join(dir, value + '.tsx');- const asIndex = nodePath.join(dir, value, 'index.ts');- const asIndexTsx = nodePath.join(dir, value, 'index.tsx');-- if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {- source.value = value + '.js';- } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {- source.value = value + '/index.js';- } else {- source.value = value + '.js';- }+ rewriteSpecifier(source, state);+ },+ // Dynamic import() under Babel 7. Only literal specifiers are+ // rewritten; computed ones cannot be resolved at build time.+ CallExpression(path, state) {+ if (path.node.callee.type !== 'Import') return;+ const [specifier] = path.node.arguments;+ if (!specifier || specifier.type !== 'StringLiteral') return;+ rewriteSpecifier(specifier, state);+ },+ // Dynamic import() under Babel 8 (or createImportExpressions parsing).+ ImportExpression(path, state) {+ const source = path.node.source;+ if (!source || source.type !== 'StringLiteral') return;+ rewriteSpecifier(source, state);},},};diff --git a/packages/lab/package.json b/packages/lab/package.jsonindex 8b0f7a4500..04c222742d 100644--- a/packages/lab/package.json+++ b/packages/lab/package.json@@ -46,7 +46,7 @@},"scripts": {"prepack": "pnpm build",- "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs",+ "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && 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.js","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.js",diff --git a/packages/richtext/babel-plugin-add-extensions.cjs b/packages/richtext/babel-plugin-add-extensions.cjsindex 3c6f15956a..6139ec4a68 100644--- a/packages/richtext/babel-plugin-add-extensions.cjs+++ b/packages/richtext/babel-plugin-add-extensions.cjs@@ -9,7 +9,11 @@* This plugin rewrites them during compilation so no postbuild step is needed.** Handles both file imports ('./XDSButton' → './XDSButton.js') and- * directory imports ('./domainTokens' → './domainTokens/index.js').+ * directory imports ('./domainTokens' → './domainTokens/index.js'), for+ * static import/export declarations and dynamic `import()` calls alike.+ * Dynamic specifiers otherwise reach dist verbatim and break strict-ESM+ * consumers (#4569). Babel 7 parses `import()` as a CallExpression with an+ * `Import` callee; Babel 8 emits an `ImportExpression` node — both handled.*/const fs = require('node:fs');const nodePath = require('node:path');@@ -17,6 +21,43 @@ const nodePath = require('node:path');module.exports = function addExtensions() {const SKIP = /\.(?:js|mjs|cjs|json|css)$/;+ /**+ * Rewrite one StringLiteral specifier node in place. `state` is the babel+ * plugin pass (state.filename = the importing source file).+ */+ function rewriteSpecifier(source, state) {+ const value = source.value;++ // Compat alias barrels self-re-export from `'.'` in source. Node ESM+ // does not support directory imports in built output, so make the self+ // reference explicit (`./index.js`) during compilation.+ if (value === '.') {+ source.value = './index.js';+ return;+ }+ if (value === '..') {+ source.value = '../index.js';+ return;+ }++ if (!value.startsWith('./') && !value.startsWith('../')) return;+ if (SKIP.test(value)) return;++ const dir = nodePath.dirname(state.filename);+ const asFile = nodePath.join(dir, value + '.ts');+ const asTsx = nodePath.join(dir, value + '.tsx');+ const asIndex = nodePath.join(dir, value, 'index.ts');+ const asIndexTsx = nodePath.join(dir, value, 'index.tsx');++ if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {+ source.value = value + '.js';+ } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {+ source.value = value + '/index.js';+ } else {+ source.value = value + '.js';+ }+ }+return {visitor: {'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(@@ -25,36 +66,21 @@ module.exports = function addExtensions() {) {const source = path.node.source;if (!source) return;- const value = source.value;-- // Compat alias barrels self-re-export from `'.'` in source. Node ESM- // does not support directory imports in built output, so make the self- // reference explicit (`./index.js`) during compilation.- if (value === '.') {- source.value = './index.js';- return;- }- if (value === '..') {- source.value = '../index.js';- return;- }-- if (!value.startsWith('./') && !value.startsWith('../')) return;- if (SKIP.test(value)) return;-- const dir = nodePath.dirname(state.filename);- const asFile = nodePath.join(dir, value + '.ts');- const asTsx = nodePath.join(dir, value + '.tsx');- const asIndex = nodePath.join(dir, value, 'index.ts');- const asIndexTsx = nodePath.join(dir, value, 'index.tsx');-- if (fs.existsSync(asFile) || fs.existsSync(asTsx)) {- source.value = value + '.js';- } else if (fs.existsSync(asIndex) || fs.existsSync(asIndexTsx)) {- source.value = value + '/index.js';- } else {- source.value = value + '.js';- }+ rewriteSpecifier(source, state);+ },+ // Dynamic import() under Babel 7. Only literal specifiers are+ // rewritten; computed ones cannot be resolved at build time.+ CallExpression(path, state) {+ if (path.node.callee.type !== 'Import') return;+ const [specifier] = path.node.arguments;+ if (!specifier || specifier.type !== 'StringLiteral') return;+ rewriteSpecifier(specifier, state);+ },+ // Dynamic import() under Babel 8 (or createImportExpressions parsing).+ ImportExpression(path, state) {+ const source = path.node.source;+ if (!source || source.type !== 'StringLiteral') return;+ rewriteSpecifier(source, state);},},};diff --git a/packages/richtext/package.json b/packages/richtext/package.jsonindex ebb1e80ffa..2a0a8be17a 100644--- a/packages/richtext/package.json+++ b/packages/richtext/package.json@@ -45,7 +45,7 @@},"scripts": {"prepack": "pnpm build",- "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && node ../../scripts/check-no-dev-jsx.mjs",+ "build": "rm -rf dist && pnpm build:esm && tsc --project tsconfig.build.json && 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.js","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.js","test": "vitest run --root ../..",diff --git a/scripts/check-fully-specified.mjs b/scripts/check-fully-specified.mjsnew file mode 100644index 0000000000..96f4a629e2--- /dev/null+++ b/scripts/check-fully-specified.mjs@@ -0,0 +1,130 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Build-output check: verify every relative specifier in the compiled dist+ * is fully specified (carries an explicit file extension).+ *+ * The packages publish "type": "module" dist, where Node ESM makes+ * extensions mandatory for relative specifiers — strict-ESM consumers (Node+ * itself, Rspack, webpack's `fullySpecified`) refuse to resolve+ * './XDSButton' where './XDSButton.js' is required.+ * babel-plugin-add-extensions rewrites specifiers during compilation; this+ * guard makes sure nothing slips past it into the artifact again (#4569:+ * dynamic `import()` specifiers did exactly that).+ *+ * Like check-no-dev-jsx.mjs this is a textual scan, not a parse. Comment+ * lines are skipped: dist keeps some JSDoc comments whose usage examples+ * legitimately mention extensionless specifiers. Only runtime files are+ * scanned — the .d.ts surface resolves through TypeScript, not Node.+ *+ * Usage: node ../../scripts/check-fully-specified.mjs (run from a package+ * root, after the package's dist has been built)+ */+import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';++// A relative specifier is fine once it ends in an explicit extension.+const FULLY_SPECIFIED = /\.(?:js|mjs|cjs|json|css)$/;++// The syntactic homes of a specifier in emitted ESM:+// import/export ... from './x'+// import './x' (side-effect import)+// import('./x') (dynamic import)+// import(`./x`) (no-substitution template — a static specifier in+// disguise; templates with `${` stay computed and exempt)+const SPECIFIER_PATTERNS = [+ /\bfrom\s*["'](\.\.?\/[^"']*)["']/g,+ /\bimport\s+["'](\.\.?\/[^"']*)["']/g,+ /\bimport\(\s*["'](\.\.?\/[^"']*)["']\s*\)/g,+ /\bimport\(\s*`(\.\.?\/[^`$]*)`\s*\)/g,+];++const COMMENT_LINE = /^\s*(?:\*|\/\/|\/\*)/;++/** Return the extensionless relative specifiers found in one file's source. */+export function scanSource(source) {+ const offenders = [];+ for (const line of source.split('\n')) {+ if (COMMENT_LINE.test(line)) continue;+ for (const pattern of SPECIFIER_PATTERNS) {+ pattern.lastIndex = 0;+ for (const match of line.matchAll(pattern)) {+ const specifier = match[1];+ if (!FULLY_SPECIFIED.test(specifier)) {+ offenders.push(specifier);+ }+ }+ }+ }+ return offenders;+}++function walk(dir) {+ const results = [];+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ results.push(...walk(full));+ } else if (/\.(js|mjs|cjs)$/.test(entry.name)) {+ results.push(full);+ }+ }+ return results;+}++/**+ * Scan every runtime file under `distDir`; return+ * {checked, offenders: [{file, specifiers}]}.+ */+export function findOffenders(distDir) {+ const files = walk(distDir);+ const offenders = [];+ for (const file of files) {+ const specifiers = scanSource(fs.readFileSync(file, 'utf-8'));+ if (specifiers.length > 0) {+ offenders.push({file: path.relative(distDir, file), specifiers});+ }+ }+ return {checked: files.length, offenders};+}++function main() {+ const distDir = path.resolve(process.cwd(), 'dist');+ if (!fs.existsSync(distDir)) {+ console.error(+ `❌ No dist directory at ${distDir} — build before checking.`,+ );+ process.exit(1);+ }++ const {checked, offenders} = findOffenders(distDir);++ if (offenders.length > 0) {+ console.error('❌ Extensionless relative specifiers in build output:\n');+ for (const {file, specifiers} of offenders.slice(0, 20)) {+ console.error(` dist/${file}: ${specifiers.join(', ')}`);+ }+ if (offenders.length > 20) {+ console.error(` …and ${offenders.length - 20} more file(s).`);+ }+ console.error(+ `\n${offenders.length} file(s) ship specifiers without a file ` ++ 'extension. The dist is "type": "module", so Node ESM and ' ++ 'strict-ESM bundlers cannot resolve them (see #4569).\n' ++ "Fix: make sure the package's babel-plugin-add-extensions.cjs " ++ 'rewrites the syntax form that produced them.',+ );+ process.exit(1);+ }++ console.log(+ `✅ ${checked} dist file(s) checked — every relative specifier is fully specified.`,+ );+}++// Run as a script, but stay importable for unit tests.+if (process.argv[1] === fileURLToPath(import.meta.url)) {+ main();+}diff --git a/scripts/check-fully-specified.test.mjs b/scripts/check-fully-specified.test.mjsnew file mode 100644index 0000000000..f8fbacf90d--- /dev/null+++ b/scripts/check-fully-specified.test.mjs@@ -0,0 +1,166 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file check-fully-specified.test.mjs+ * Unit tests for the fully-specified-dist gate: every relative specifier in+ * emitted ESM must carry an explicit extension (#4569 shipped a dist whose+ * dynamic `import()` specifiers had none, breaking strict-ESM consumers).+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {describe, it, expect, beforeAll, afterAll} from 'vitest';+import {scanSource, findOffenders} from './check-fully-specified.mjs';++describe('scanSource', () => {+ it('flags an extensionless static import specifier', () => {+ expect(scanSource(`import {x} from './XDSButton';`)).toEqual([+ './XDSButton',+ ]);+ });++ it('flags an extensionless re-export specifier', () => {+ expect(scanSource(`export * from '../utils';`)).toEqual(['../utils']);+ });++ it('flags an extensionless side-effect import', () => {+ expect(scanSource(`import './componentStyles';`)).toEqual([+ './componentStyles',+ ]);+ });++ it('flags an extensionless dynamic import() specifier', () => {+ // The exact emitted shape that broke Rspack consumers in #4569.+ const line = `const LazyXDSTooltip = /*#__PURE__*/lazy(async () => import("../Tooltip/Tooltip").then(mod => ({`;+ expect(scanSource(line)).toEqual(['../Tooltip/Tooltip']);+ });++ it('flags double-quoted specifiers (the shape babel emits)', () => {+ expect(scanSource(`import {mergeProps} from "../utils";`)).toEqual([+ '../utils',+ ]);+ });++ it('flags extensions outside the allowlist, e.g. .stylex', () => {+ // Source says './tokens.stylex' but the built file is tokens.stylex.js —+ // an emitted .stylex specifier is exactly as unresolvable as no extension.+ expect(scanSource(`import {vars} from './theme/tokens.stylex';`)).toEqual([+ './theme/tokens.stylex',+ ]);+ });++ it('handles CRLF line endings', () => {+ const source =+ `// import {x} from './commented-out';\r\n` ++ `import {x} from './nope';\r\n`;+ expect(scanSource(source)).toEqual(['./nope']);+ });++ it('accepts fully specified and non-relative specifiers', () => {+ const source = [+ `import {jsx} from "react/jsx-runtime";`,+ `import {Tooltip} from "../Tooltip/Tooltip.js";`,+ `import "./reset.css";`,+ `import data from "./data.json";`,+ `const p = import("../Tooltip/Tooltip.js");`,+ `const q = import(someVariable);`,+ ].join('\n');+ expect(scanSource(source)).toEqual([]);+ });++ it('flags an extensionless backtick dynamic import() specifier', () => {+ // A no-substitution template literal is a static specifier in disguise —+ // it escapes babel-plugin-add-extensions (which rewrites only string+ // literals), so the gate must catch it.+ expect(scanSource('const p = import(`../Tooltip/Tooltip`);')).toEqual([+ '../Tooltip/Tooltip',+ ]);+ });++ it('accepts backtick specifiers that are fully specified or computed', () => {+ const source = [+ 'const p = import(`../Tooltip/Tooltip.js`);',+ 'const q = (n) => import(`./locales/${n}`);',+ ].join('\n');+ expect(scanSource(source)).toEqual([]);+ });++ it('ignores specifiers on comment lines', () => {+ // dist keeps JSDoc usage examples, e.g. layerAnimations.stylex.js and+ // globalIconRegistry.js — those must not fail the gate.+ const source = [+ `/**`,+ ` * import {layerAnimations} from '../Layer/layerAnimations.stylex';`,+ ` * import { brandIcons } from './brand-icons';`,+ ` */`,+ `// import {x} from './commented-out';`,+ `export const ok = 1;`,+ ].join('\n');+ expect(scanSource(source)).toEqual([]);+ });+});++describe('findOffenders', () => {+ let distDir;++ beforeAll(() => {+ distDir = fs.mkdtempSync(path.join(os.tmpdir(), 'fully-specified-'));+ fs.writeFileSync(+ path.join(distDir, 'clean.js'),+ `import {x} from './other.js';\nexport const y = 1;\n`,+ );+ fs.mkdirSync(path.join(distDir, 'Text'));+ fs.writeFileSync(+ path.join(distDir, 'Text', 'Text.js'),+ `const L = lazy(() => import('../Tooltip/Tooltip'));\n`,+ );+ // Non-runtime files are not scanned.+ fs.writeFileSync(+ path.join(distDir, 'Text', 'Text.d.ts'),+ `export * from '../types';\n`,+ );+ });++ afterAll(() => {+ fs.rmSync(distDir, {recursive: true, force: true});+ });++ it('reports offending runtime files with their bad specifiers', () => {+ expect(findOffenders(distDir)).toEqual({+ // clean.js + Text/Text.js — the .d.ts file must not be scanned.+ checked: 2,+ offenders: [+ {+ file: path.join('Text', 'Text.js'),+ specifiers: ['../Tooltip/Tooltip'],+ },+ ],+ });+ });++ it('aggregates offenders across files, several per file', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fully-specified-agg-'));+ try {+ fs.writeFileSync(+ path.join(dir, 'a.js'),+ `import {x} from './one';\nconst p = import('./two');\n`,+ );+ fs.writeFileSync(path.join(dir, 'b.mjs'), `export * from '../three';\n`);+ fs.writeFileSync(path.join(dir, 'ok.js'), `import './fine.css';\n`);+ const {checked, offenders} = findOffenders(dir);+ expect(checked).toBe(3);+ expect(offenders).toHaveLength(2);+ expect(offenders).toContainEqual({+ file: 'a.js',+ specifiers: ['./one', './two'],+ });+ expect(offenders).toContainEqual({+ file: 'b.mjs',+ specifiers: ['../three'],+ });+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });+});