diff --git a/packages/devextreme-react/project.json b/packages/devextreme-react/project.json index 9d4ce6e975f9..c67143d38aa2 100644 --- a/packages/devextreme-react/project.json +++ b/packages/devextreme-react/project.json @@ -24,7 +24,8 @@ "excludePatterns": ["./src/**/__tests__/**/*", "./src/**/__mocks__/**/*"], "tsconfig": "./tsconfig.esm.json", "outDir": "./npm/esm", - "module": "esm" + "module": "esm", + "fullySpecifiedImports": true }, "outputs": ["{projectRoot}/npm/esm"], "inputs": ["default"] @@ -58,6 +59,25 @@ "distDirectory": "./npm" } }, + "npm:exports-map": { + "executor": "devextreme-nx-infra-plugin:generate-exports-map", + "options": { + "packageDir": "./npm", + "ignore": ["cjs", "esm"], + "directoryIndexes": ["esm", "cjs"], + "directoryIndexTypesFrom": { "esm": "cjs" }, + "extraExports": { + "./esm/*.js": { "types": "./cjs/*.d.ts", "default": "./esm/*.js" }, + "./esm/*": { "types": "./cjs/*.d.ts", "default": "./esm/*.js" }, + "./cjs/*.d.ts": "./cjs/*.d.ts", + "./cjs/*.js": { "types": "./cjs/*.d.ts", "default": "./cjs/*.js" }, + "./cjs/*": { "types": "./cjs/*.d.ts", "default": "./cjs/*.js" } + } + }, + "metadata": { + "description": "Adds the \"exports\" map to npm/package.json: the root module, one entry per module stub created by npm:prepare-modules, and the esm/ and cjs/ deep paths with their declarations from cjs/. Runs after prepare-package-json, which rewrites npm/package.json." + } + }, "copy-files": { "executor": "devextreme-nx-infra-plugin:copy-files", "dependsOn": ["prepare-package-json"], @@ -126,7 +146,8 @@ "pnpm --workspace-root nx run-many --targets=build:esm,build:cjs --projects=devextreme-react", "pnpm --workspace-root nx copy-files devextreme-react", "pnpm --workspace-root nx npm:prepare-modules devextreme-react", - "pnpm --workspace-root nx prepare-package-json devextreme-react" + "pnpm --workspace-root nx prepare-package-json devextreme-react", + "pnpm --workspace-root nx npm:exports-map devextreme-react" ], "parallel": false }, @@ -146,6 +167,7 @@ "pnpm --workspace-root nx prepare-package-json devextreme-react", "pnpm --workspace-root nx license-headers devextreme-react", "pnpm --workspace-root nx npm:prepare-modules devextreme-react", + "pnpm --workspace-root nx npm:exports-map devextreme-react", "pnpm --workspace-root nx npm:pack devextreme-react" ], "parallel": false diff --git a/packages/devextreme-themebuilder/src/tools/copy-resources.ts b/packages/devextreme-themebuilder/src/tools/copy-resources.ts index 70e5094c3afd..418ee209ea2f 100644 --- a/packages/devextreme-themebuilder/src/tools/copy-resources.ts +++ b/packages/devextreme-themebuilder/src/tools/copy-resources.ts @@ -5,10 +5,29 @@ import { copy, readJson, outputJson } from 'fs-extra'; import { version } from '../data/metadata/dx-theme-builder-metadata'; +const METADATA_FOLDERS = ['metadata', 'bootstrap-metadata', 'migration-metadata']; + +const EXPORTS = { + '.': './modules/builder.js', + './package.json': './package.json', + './modules/*.js': './modules/*.js', + './modules/*': './modules/*.js', + ...Object.fromEntries( + METADATA_FOLDERS.flatMap((folder) => [ + [`./data/${folder}/*.js`, `./data/${folder}/*.js`], + [`./data/${folder}/*`, `./data/${folder}/*.js`], + ]), + ), + './data/*.js': './data/*.js', + './data/*.json': './data/*.json', + './data/*': './data/*', +}; + const copyResources = async (): Promise => { await readJson('package.json').then(async (json) => { const packageConfig = json; packageConfig.version = version; + packageConfig.exports = EXPORTS; await outputJson('dist/package.json', packageConfig, { spaces: 2 }); }); await copy('src/data/scss', 'dist/data/scss'); diff --git a/packages/devextreme-vue/project.json b/packages/devextreme-vue/project.json index eea6ab679e9f..91c8017d280a 100644 --- a/packages/devextreme-vue/project.json +++ b/packages/devextreme-vue/project.json @@ -24,7 +24,8 @@ "excludePatterns": ["./src/**/__tests__/**/*", "./src/**/__mocks__/**/*"], "tsconfig": "./tsconfig.esm.json", "outDir": "./npm/esm", - "module": "esm" + "module": "esm", + "fullySpecifiedImports": true }, "outputs": ["{projectRoot}/npm/esm"], "inputs": ["default"] @@ -80,6 +81,25 @@ ] } }, + "npm:exports-map": { + "executor": "devextreme-nx-infra-plugin:generate-exports-map", + "options": { + "packageDir": "./npm", + "ignore": ["cjs", "esm"], + "directoryIndexes": ["esm", "cjs"], + "directoryIndexTypesFrom": { "esm": "cjs" }, + "extraExports": { + "./esm/*.js": { "types": "./cjs/*.d.ts", "default": "./esm/*.js" }, + "./esm/*": { "types": "./cjs/*.d.ts", "default": "./esm/*.js" }, + "./cjs/*.d.ts": "./cjs/*.d.ts", + "./cjs/*.js": { "types": "./cjs/*.d.ts", "default": "./cjs/*.js" }, + "./cjs/*": { "types": "./cjs/*.d.ts", "default": "./cjs/*.js" } + } + }, + "metadata": { + "description": "Adds the \"exports\" map to npm/package.json: the root module, one entry per module stub created by npm:prepare-modules, and the esm/ and cjs/ deep paths with their declarations from cjs/. Runs after prepare-package-json, which rewrites npm/package.json." + } + }, "npm:pack": { "executor": "devextreme-nx-infra-plugin:pack-npm", "outputs": ["{projectRoot}/npm/*.tgz"], @@ -148,7 +168,8 @@ "pnpm --workspace-root nx run-many --targets=build:esm,build:cjs --projects=devextreme-vue", "pnpm --workspace-root nx copy-files devextreme-vue", "pnpm --workspace-root nx npm:prepare-modules devextreme-vue", - "pnpm --workspace-root nx prepare-package-json devextreme-vue" + "pnpm --workspace-root nx prepare-package-json devextreme-vue", + "pnpm --workspace-root nx npm:exports-map devextreme-vue" ], "parallel": false }, @@ -168,6 +189,7 @@ "pnpm --workspace-root nx prepare-package-json devextreme-vue", "pnpm --workspace-root nx license-headers devextreme-vue", "pnpm --workspace-root nx npm:prepare-modules devextreme-vue", + "pnpm --workspace-root nx npm:exports-map devextreme-vue", "pnpm --workspace-root nx npm:pack devextreme-vue" ], "parallel": false diff --git a/packages/devextreme/build/babel-plugin-add-import-extensions.js b/packages/devextreme/build/babel-plugin-add-import-extensions.js new file mode 100644 index 000000000000..c38783e0cd80 --- /dev/null +++ b/packages/devextreme/build/babel-plugin-add-import-extensions.js @@ -0,0 +1,96 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +// Makes relative import/export specifiers in the ESM build fully specified, as Node's ESM loader +// and strict-ESM bundler modes require: +// './button' -> './button.js' +// './ui.errors' -> './ui.errors.js' (a dot in a file name is not an extension) +// './grids' -> './grids/index.js' +// The decision is made against the source tree, the way TypeScript resolves the import. + +const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx']; + +function isFile(filePath) { + try { + return fs.statSync(filePath).isFile(); + } catch { + return false; + } +} + +// Files compiled to an intermediate folder (tsc output) are resolved against their sources +function toSourcePath(filePath, sourceRoots) { + const root = sourceRoots.find(({ from }) => filePath.startsWith(from + path.sep)); + + return root ? path.join(root.to, path.relative(root.from, filePath)) : filePath; +} + +function fullySpecify(specifier, importerPath) { + const target = path.resolve(path.dirname(importerPath), specifier); + + if (isFile(target)) { + return specifier; + } + + if (SOURCE_EXTENSIONS.some((ext) => isFile(`${target}${ext}`))) { + return `${specifier}.js`; + } + + if (SOURCE_EXTENSIONS.some((ext) => isFile(path.join(target, `index${ext}`)))) { + return `${specifier}/index.js`; + } + + return null; +} + +module.exports = function addImportExtensions({ types: t }, { sourceRoots = [] } = {}) { + function rewriteSource(sourcePath, state) { + if (!sourcePath.node || !t.isStringLiteral(sourcePath.node)) { + return; + } + + const specifier = sourcePath.node.value; + + if (!specifier.startsWith('./') && !specifier.startsWith('../')) { + return; + } + + const { filename } = state.file.opts; + + if (!filename) { + throw sourcePath.buildCodeFrameError('add-import-extensions needs the file name to resolve relative imports'); + } + + const importerPath = toSourcePath(filename, sourceRoots); + const resolved = fullySpecify(specifier, importerPath); + + if (resolved === null) { + throw sourcePath.buildCodeFrameError(`Cannot resolve '${specifier}' from ${importerPath}`); + } + + if (resolved !== specifier) { + const quote = sourcePath.node.extra?.raw?.[0] ?? '\''; + const literal = t.stringLiteral(resolved); + literal.extra = { rawValue: resolved, raw: `${quote}${resolved}${quote}` }; + + sourcePath.replaceWith(literal); + } + } + + return { + name: 'add-import-extensions', + visitor: { + ImportDeclaration: (p, state) => rewriteSource(p.get('source'), state), + ExportNamedDeclaration: (p, state) => rewriteSource(p.get('source'), state), + ExportAllDeclaration: (p, state) => rewriteSource(p.get('source'), state), + ImportExpression: (p, state) => rewriteSource(p.get('source'), state), + CallExpression: (p, state) => { + if (p.get('callee').isImport()) { + rewriteSource(p.get('arguments.0'), state); + } + }, + }, + }; +}; diff --git a/packages/devextreme/build/babel-plugin-add-import-extensions.test.ts b/packages/devextreme/build/babel-plugin-add-import-extensions.test.ts new file mode 100644 index 000000000000..6695f19dc909 --- /dev/null +++ b/packages/devextreme/build/babel-plugin-add-import-extensions.test.ts @@ -0,0 +1,119 @@ +import { transformSync } from '@babel/core'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +const addImportExtensions = require('./babel-plugin-add-import-extensions'); + +describe('babel-plugin-add-import-extensions', () => { + let root: string; + + const write = (relativePath: string, content = ''): void => { + const filePath = path.join(root, relativePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, content); + }; + + const transform = (code: string, relativeFile: string, sourceRoots: object[] = []): string => { + const result = transformSync(code, { + filename: path.join(root, relativeFile), + babelrc: false, + configFile: false, + plugins: [[addImportExtensions, { sourceRoots }]], + }); + + return result?.code ?? ''; + }; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'add-import-extensions-')); + + write('js/ui/button.js'); + write('js/ui/widget/ui.errors.js'); + write('js/__internal/ui/button/index.ts'); + write('js/__internal/ui/button/wrapper.tsx'); + write('js/__internal/core/m_config.ts'); + write('js/viz/funnel.ts'); + write('js/viz/funnel/index.ts'); + write('js/localization/messages/en.json'); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('appends .js to file imports, including names that contain a dot', () => { + const code = transform( + "import Button from './button';\nimport errors from './widget/ui.errors';", + 'js/ui/component.js', + ); + + expect(code).toContain("from './button.js'"); + expect(code).toContain("from './widget/ui.errors.js'"); + }); + + it('resolves .ts and .tsx sources to .js output', () => { + const code = transform("import config from './m_config';\nimport Wrapper from '../ui/button/wrapper';", 'js/__internal/core/consumer.ts'); + + expect(code).toContain("from './m_config.js'"); + expect(code).toContain("from '../ui/button/wrapper.js'"); + }); + + it('points directory imports at index.js', () => { + const code = transform("import Button from '../__internal/ui/button';", 'js/ui/button.js'); + + expect(code).toContain("from '../__internal/ui/button/index.js'"); + }); + + it('prefers a file over a directory with the same name, like TypeScript', () => { + const code = transform("import funnel from './funnel';", 'js/viz/chart.ts'); + + expect(code).toContain("from './funnel.js'"); + }); + + it('rewrites re-exports and dynamic imports', () => { + const code = transform( + "export * from './button';\nexport { default } from './button';\nconst lazy = () => import('./button');", + 'js/ui/index.js', + ); + + expect(code).toContain("export * from './button.js'"); + expect(code).toContain("export { default } from './button.js'"); + expect(code).toContain("import('./button.js')"); + }); + + it('keeps the original quote style', () => { + const code = transform('import Button from "./button";', 'js/ui/component.js'); + + expect(code).toContain('from "./button.js"'); + }); + + it('leaves package imports and existing extensions untouched', () => { + const code = transform( + "import $ from 'jquery';\nimport helper from '@babel/runtime/helpers/extends';\nimport en from '../localization/messages/en.json';", + 'js/ui/button.js', + ); + + expect(code).toContain("from 'jquery'"); + expect(code).toContain("from '@babel/runtime/helpers/extends'"); + expect(code).toContain("from '../localization/messages/en.json'"); + }); + + it('resolves files compiled to another folder against their sources', () => { + write('artifacts/dist_ts/__internal/ui/button/wrapper.js'); + + const code = transform( + "import errors from '../../../ui/widget/ui.errors';\nimport config from '../../core/m_config';", + 'artifacts/dist_ts/__internal/ui/button/wrapper.js', + [{ from: path.join(root, 'artifacts/dist_ts'), to: path.join(root, 'js') }], + ); + + expect(code).toContain("from '../../../ui/widget/ui.errors.js'"); + expect(code).toContain("from '../../core/m_config.js'"); + }); + + it('fails the build on an import that does not resolve', () => { + expect(() => transform("import missing from './missing';", 'js/ui/button.js')) + .toThrow(/Cannot resolve '\.\/missing'/); + }); +}); diff --git a/packages/devextreme/build/transpile-config.js b/packages/devextreme/build/transpile-config.js index 9bee0fbd6141..3ba3bfb24375 100644 --- a/packages/devextreme/build/transpile-config.js +++ b/packages/devextreme/build/transpile-config.js @@ -1,5 +1,8 @@ 'use strict'; +const path = require('path'); +const addImportExtensions = require('./babel-plugin-add-import-extensions'); + const common = { plugins: [ ['babel-plugin-inferno', { 'imports': true }], @@ -14,6 +17,18 @@ const targets = { samsung: 13, }; +const esmQunit = Object.assign({}, common, { + // eslint-disable-next-line spellcheck/spell-checker + presets: [['@babel/preset-env', { targets, modules: false }]], + plugins: common.plugins.concat([ + // Plain `@babel/runtime/helpers/*` paths resolve to the ESM or CJS helper through + // @babel/runtime's exports map, so tools that run esm/ as CommonJS (Jest) can load them + ['@babel/plugin-transform-runtime', { + version: '7.5.0' // https://github.com/babel/babel/issues/10261#issuecomment-514687857 + }], + ]) +}); + module.exports = { cjs: Object.assign({}, common, { presets: [['@babel/preset-env', { targets }]], @@ -30,14 +45,20 @@ module.exports = { ]) }), - esm: Object.assign({}, common, { - // eslint-disable-next-line spellcheck/spell-checker - presets: [['@babel/preset-env', { targets, modules: false }]], - plugins: common.plugins.concat( - [['@babel/plugin-transform-runtime', { - useESModules: true, - version: '7.5.0' // https://github.com/babel/babel/issues/10261#issuecomment-514687857 - }]] - ) - }) + esm: Object.assign({}, esmQunit, { + plugins: esmQunit.plugins.concat([ + [addImportExtensions, { + // __internal is compiled by tsc into artifacts/dist_ts first + sourceRoots: [{ + from: path.resolve(__dirname, '../artifacts/dist_ts'), + to: path.resolve(__dirname, '../js'), + }], + }], + ]) + }), + + // The QUnit runner's import map gives tests extensionless URLs (testing/runner/lib/importMap.ts). + // A test and the library have to import a module by the same URL to share one instance, + // so QUnit artifacts keep extensionless imports. + esmQunit, }; diff --git a/packages/devextreme/js/__internal/scheduler/recurrence/generate_dates.ts b/packages/devextreme/js/__internal/scheduler/recurrence/generate_dates.ts index 572e0d64623a..8f17f3f563ae 100644 --- a/packages/devextreme/js/__internal/scheduler/recurrence/generate_dates.ts +++ b/packages/devextreme/js/__internal/scheduler/recurrence/generate_dates.ts @@ -1,8 +1,8 @@ import { addOffsets } from '@ts/core/utils/date'; -import { RRule, RRuleSet } from 'rrule'; import timeZoneUtils from '../utils_time_zone'; import { getDateByAsciiString, parseRecurrenceRule } from './base'; +import { RRule, RRuleSet } from './rrule'; import type { ProcessorOptions, RRuleParams } from './types'; import { validateRRuleObject } from './validate_rule'; diff --git a/packages/devextreme/js/__internal/scheduler/recurrence/rrule.ts b/packages/devextreme/js/__internal/scheduler/recurrence/rrule.ts new file mode 100644 index 000000000000..f34364ae55b5 --- /dev/null +++ b/packages/devextreme/js/__internal/scheduler/recurrence/rrule.ts @@ -0,0 +1,15 @@ +import * as rruleModule from 'rrule'; + +type RRuleModule = typeof rruleModule; + +// rrule's `main` is a UMD bundle, so Node's ESM loader exposes it only as a default export, +// while bundlers take rrule's ESM build (`module`) with named exports and no default. +// A namespace import works in both: named exports from the ESM build, +// `default` from the UMD bundle. +const resolveRRuleModule = (module: RRuleModule & { default?: RRuleModule }): RRuleModule => ( + module.RRule ? module : module.default as RRuleModule +); + +export const { RRule, RRuleSet } = resolveRRuleModule(rruleModule); +// eslint-disable-next-line @typescript-eslint/no-redeclare +export type RRuleSet = InstanceType; diff --git a/packages/devextreme/js/__internal/scheduler/view_model/filtration/utils/split_by_recurrence/generate_recurrence_utc_dates.ts b/packages/devextreme/js/__internal/scheduler/view_model/filtration/utils/split_by_recurrence/generate_recurrence_utc_dates.ts index 5aeaeafa2e80..df1960c95758 100644 --- a/packages/devextreme/js/__internal/scheduler/view_model/filtration/utils/split_by_recurrence/generate_recurrence_utc_dates.ts +++ b/packages/devextreme/js/__internal/scheduler/view_model/filtration/utils/split_by_recurrence/generate_recurrence_utc_dates.ts @@ -1,7 +1,7 @@ import { addOffsets } from '@ts/core/utils/date'; -import { RRule, RRuleSet } from 'rrule'; import { parseRecurrenceRule } from '../../../../recurrence/base'; +import { RRule, RRuleSet } from '../../../../recurrence/rrule'; import type { DateInterval, MinimalAppointmentEntity } from '../../../types'; import { getDateOffsetMs } from './get_date_information'; diff --git a/packages/devextreme/js/core/version.d.ts b/packages/devextreme/js/core/version.d.ts new file mode 100644 index 000000000000..6ced36e6ae5c --- /dev/null +++ b/packages/devextreme/js/core/version.d.ts @@ -0,0 +1,5 @@ +// eslint-disable-next-line @typescript-eslint/init-declarations +export const version: string; + +// eslint-disable-next-line @typescript-eslint/init-declarations +export const fullVersion: string; diff --git a/packages/devextreme/js/localization/ldml/number.js b/packages/devextreme/js/localization/ldml/number.js index 1da738055d75..14c17c038556 100644 --- a/packages/devextreme/js/localization/ldml/number.js +++ b/packages/devextreme/js/localization/ldml/number.js @@ -1,2 +1 @@ export * from '../../__internal/core/localization/ldml/number'; -export { FormatterConfig } from '../../__internal/core/localization/number'; diff --git a/packages/devextreme/js/viz/core/renderers/animation.js b/packages/devextreme/js/viz/core/renderers/animation.js index aac733a0e4d7..d186cf35c44c 100644 --- a/packages/devextreme/js/viz/core/renderers/animation.js +++ b/packages/devextreme/js/viz/core/renderers/animation.js @@ -1,3 +1,3 @@ -import * as Animation from '__internal/viz/core/renderers/animation'; +import * as Animation from '../../../__internal/viz/core/renderers/animation'; export default Animation; diff --git a/packages/devextreme/project.json b/packages/devextreme/project.json index 0933f5870c1d..2d540f000285 100644 --- a/packages/devextreme/project.json +++ b/packages/devextreme/project.json @@ -311,6 +311,7 @@ }, "configurations": { "qunit": { + "configKey": "esmQunit", "removeDebug": false } }, @@ -383,6 +384,7 @@ }, "configurations": { "qunit": { + "configKey": "esmQunit", "removeDebug": false } }, @@ -413,6 +415,7 @@ }, "configurations": { "qunit": { + "configKey": "esmQunit", "removeDebug": false } } @@ -433,6 +436,7 @@ }, "configurations": { "qunit": { + "configKey": "esmQunit", "removeDebug": false } } @@ -1288,6 +1292,39 @@ "{projectRoot}/artifacts/npm/devextreme-internal/package.json" ] }, + "build:npm:exports-map": { + "executor": "devextreme-nx-infra-plugin:generate-exports-map", + "cache": false, + "options": { + "packageDir": "./artifacts/npm/devextreme", + "ignore": ["__internal", "bin", "bundles", "cjs", "dist", "esm", "license", "scss"], + "declarationImports": true, + "directoryIndexes": ["esm", "cjs"], + "extraExports": { + "./bundles/*.d.ts": "./bundles/*.d.ts", + "./bundles/*.js": "./bundles/*.js", + "./bundles/*": { "types": "./bundles/*.d.ts", "default": "./bundles/*.js" }, + "./localization/messages/*.json": "./localization/messages/*.json", + "./localization/messages/*": "./localization/messages/*.json", + "./dist/*": "./dist/*", + "./scss/*": "./scss/*", + "./esm/*.json": "./esm/*.json", + "./esm/*.js": "./esm/*.js", + "./esm/*": "./esm/*.js", + "./cjs/*.json": "./cjs/*.json", + "./cjs/*.js": "./cjs/*.js", + "./cjs/*": "./cjs/*.js" + } + }, + "configurations": { + "internal": { + "packageDir": "./artifacts/npm/devextreme-internal" + } + }, + "metadata": { + "description": "Adds the \"exports\" map to the assembled package.json: one entry per module stub, type-only modules from declarations, plus extraExports." + } + }, "compress:npm-sources": { "executor": "devextreme-nx-infra-plugin:compress", "options": { @@ -1546,6 +1583,7 @@ "pnpm nx run devextreme:build:npm:dist:package-json", "pnpm nx run devextreme:build:npm:assemble", "pnpm nx run devextreme:build:npm:root-package-json", + "pnpm nx run devextreme:build:npm:exports-map", "pnpm nx run devextreme:compress:npm-sources", "pnpm nx run devextreme:verify:public-modules", "pnpm nx run devextreme:build:npm:scss" @@ -1587,6 +1625,7 @@ "pnpm nx run devextreme:build:npm:dist:package-json", "pnpm nx run devextreme:build:npm:assemble", "pnpm nx run devextreme:build:npm:root-package-json", + "pnpm nx run devextreme:build:npm:exports-map", "pnpm nx run devextreme:compress:npm-sources -c production", "pnpm nx run devextreme:verify:public-modules", "pnpm nx run devextreme:build:npm:scss" @@ -1599,6 +1638,7 @@ "pnpm nx run devextreme:build:npm:dist:package-json -c internal", "pnpm nx run devextreme:build:npm:assemble -c internal", "pnpm nx run devextreme:build:npm:root-package-json -c internal", + "pnpm nx run devextreme:build:npm:exports-map -c internal", "pnpm nx run devextreme:compress:npm-sources -c internal", "pnpm nx run devextreme:verify:public-modules", "pnpm nx run devextreme:build:npm:scss -c internal" @@ -1611,6 +1651,7 @@ "pnpm nx run devextreme:build:npm:dist:package-json -c internal", "pnpm nx run devextreme:build:npm:assemble -c internal", "pnpm nx run devextreme:build:npm:root-package-json -c internal", + "pnpm nx run devextreme:build:npm:exports-map -c internal", "pnpm nx run devextreme:compress:npm-sources -c production-internal", "pnpm nx run devextreme:verify:public-modules", "pnpm nx run devextreme:build:npm:scss -c internal" @@ -1623,6 +1664,7 @@ "pnpm nx run devextreme:build:npm:dist:package-json", "pnpm nx run devextreme:build:npm:assemble -c test-internal", "pnpm nx run devextreme:build:npm:root-package-json", + "pnpm nx run devextreme:build:npm:exports-map", "pnpm nx run devextreme:compress:npm-sources", "pnpm nx run devextreme:verify:public-modules", "pnpm nx run devextreme:build:npm:scss" @@ -1635,6 +1677,7 @@ "pnpm nx run devextreme:build:npm:dist:package-json", "pnpm nx run devextreme:build:npm:assemble -c test-internal", "pnpm nx run devextreme:build:npm:root-package-json", + "pnpm nx run devextreme:build:npm:exports-map", "pnpm nx run devextreme:compress:npm-sources -c production", "pnpm nx run devextreme:verify:public-modules", "pnpm nx run devextreme:build:npm:scss" diff --git a/packages/nx-infra-plugin/executors.json b/packages/nx-infra-plugin/executors.json index eef573b463a8..8211b33b3a33 100644 --- a/packages/nx-infra-plugin/executors.json +++ b/packages/nx-infra-plugin/executors.json @@ -129,6 +129,11 @@ "implementation": "./src/executors/scss-build/executor", "schema": "./src/executors/scss-build/schema.json", "description": "Run SCSS themes build pipeline in all or CI mode" + }, + "generate-exports-map": { + "implementation": "./src/executors/generate-exports-map/executor", + "schema": "./src/executors/generate-exports-map/schema.json", + "description": "Generate the package.json exports map of an npm package from its per-directory stubs and declarations" } } } diff --git a/packages/nx-infra-plugin/src/executors/build-typescript/build-typescript.impl.ts b/packages/nx-infra-plugin/src/executors/build-typescript/build-typescript.impl.ts index 445beac6ad0e..076addb3ea52 100644 --- a/packages/nx-infra-plugin/src/executors/build-typescript/build-typescript.impl.ts +++ b/packages/nx-infra-plugin/src/executors/build-typescript/build-typescript.impl.ts @@ -9,6 +9,7 @@ import { TsConfig, CompilerOptions } from '../../utils/types'; import { normalizeGlobPathForWindows, toPosixPath } from '../../utils/path-resolver'; import { isWindowsOS } from '../../utils/common'; import { exists, ensureDir, writeFileText } from '../../utils/file-operations'; +import { createFullySpecifiedImportsTransformer } from './fully-specified-imports'; type AliasTranspileFunc = (filePath: string, fileContents: string) => string; @@ -36,6 +37,7 @@ interface ResolvedConfig { excludePatterns: string[]; resolvePaths: boolean; resolvePathsBaseDir?: string; + customTransformers?: ts.CustomTransformers; } interface EmitProgramResult { @@ -46,6 +48,7 @@ interface EmitOptions { aliasTranspileFunc?: AliasTranspileFunc; outDir: string; aliasPath?: string; + customTransformers?: ts.CustomTransformers; } function resolveExecutorConfig( @@ -63,6 +66,13 @@ function resolveExecutorConfig( resolvePathsBaseDir: options.resolvePathsBaseDir ? path.join(projectRoot, options.resolvePathsBaseDir) : undefined, + customTransformers: options.fullySpecifiedImports + ? { + after: [ + createFullySpecifiedImportsTransformer({ aliases: options.resolvePaths ?? false }), + ], + } + : undefined, }; } @@ -177,19 +187,25 @@ async function emitWithAliasResolution( program: ts.Program, emitOptions: EmitOptions, ): Promise<{ success: boolean; diagnostics: ts.Diagnostic[] }> { - const { aliasTranspileFunc, outDir, aliasPath } = emitOptions; + const { aliasTranspileFunc, outDir, aliasPath, customTransformers } = emitOptions; const emittedFiles: Array<{ path: string; content: string }> = []; - const result = program.emit(undefined, (filePath, fileData) => { - let finalContent = fileData; - - if (aliasTranspileFunc && aliasPath) { - const normalizedFilePath = replacePathPrefix(filePath, outDir, aliasPath); - finalContent = aliasTranspileFunc(normalizedFilePath, fileData); - } - - emittedFiles.push({ path: filePath, content: finalContent }); - }); + const result = program.emit( + undefined, + (filePath, fileData) => { + let finalContent = fileData; + + if (aliasTranspileFunc && aliasPath) { + const normalizedFilePath = replacePathPrefix(filePath, outDir, aliasPath); + finalContent = aliasTranspileFunc(normalizedFilePath, fileData); + } + + emittedFiles.push({ path: filePath, content: finalContent }); + }, + undefined, + undefined, + customTransformers, + ); for (const file of emittedFiles) { const dir = path.dirname(file.path); @@ -216,6 +232,7 @@ async function emitWithPathAliasResolution( aliasTranspileFunc, outDir: config.outDir, aliasPath: config.resolvePathsBaseDir, + customTransformers: config.customTransformers, }); if (!success) { @@ -226,8 +243,11 @@ async function emitWithPathAliasResolution( return { success }; } -function emitStandard(program: ts.Program): EmitProgramResult { - const result = program.emit(); +function emitStandard( + program: ts.Program, + customTransformers?: ts.CustomTransformers, +): EmitProgramResult { + const result = program.emit(undefined, undefined, undefined, undefined, customTransformers); if (result.emitSkipped) { logger.error(ERROR_MESSAGES.COMPILATION_FAILED); @@ -282,6 +302,24 @@ async function runWatch(config: ResolvedConfig): Promise { ts.sys.writeFile(filePath, content, writeByteOrderMark); }; (host as { writeFile?: ts.WriteFileCallback }).writeFile = emitWriteFile; + + if (config.customTransformers) { + const { customTransformers } = config; + const afterProgramCreate = host.afterProgramCreate; + host.afterProgramCreate = (builderProgram) => { + const emit = builderProgram.emit.bind(builderProgram); + builderProgram.emit = (targetSourceFile, writeFile, cancellationToken, emitOnlyDts, custom) => + emit( + targetSourceFile, + writeFile, + cancellationToken, + emitOnlyDts, + custom ?? customTransformers, + ); + afterProgramCreate?.(builderProgram); + }; + } + const watchProgram = ts.createWatchProgram(host); logger.verbose(`TypeScript watch is emitting to ${config.outDir}...`); @@ -337,7 +375,7 @@ export default createExecutor { }, 10000); }); + describe('fullySpecifiedImports', () => { + const esmOptions: BuildTypescriptExecutorSchema = { + module: 'esm', + srcPattern: './src/**/*.{ts,tsx}', + excludePatterns: ['./src/**/__tests__/**/*'], + tsconfig: './tsconfig.esm.json', + outDir: './npm/esm', + }; + + beforeEach(async () => { + const srcDir = path.join(projectDir, 'src'); + await writeFileText( + path.join(srcDir, 'helpers.ts'), + `export const one = 1;\nexport type Id = number;\n`, + ); + await writeFileText( + path.join(srcDir, 'entry.ts'), + [ + `import { add } from './utils';`, + `import { one } from './helpers';`, + `import type { Id } from './helpers';`, + `export * from './helpers';`, + `export { add };`, + `export const id: Id = add(one, 1);`, + `export const lazy = () => import('./helpers');`, + '', + ].join('\n'), + ); + }); + + it('should add extensions to relative imports in the ESM output', async () => { + const result = await executor({ ...esmOptions, fullySpecifiedImports: true }, context); + expect(result.success).toBe(true); + + const content = await readFileText(path.join(projectDir, 'npm', 'esm', 'entry.js')); + expect(content).toContain(`from './utils/index.js'`); + expect(content).toContain(`import { one } from './helpers.js'`); + expect(content).toContain(`export * from './helpers.js'`); + expect(content).toContain(`import('./helpers.js')`); + expect(content).not.toMatch(/'\.\/helpers'/); + }, 10000); + + it('should keep relative imports as written by default', async () => { + const result = await executor(esmOptions, context); + expect(result.success).toBe(true); + + const content = await readFileText(path.join(projectDir, 'npm', 'esm', 'entry.js')); + expect(content).toContain(`from './utils'`); + expect(content).toContain(`from './helpers'`); + }, 10000); + + it('should add extensions to path aliases when resolvePaths is enabled', async () => { + await writeFileText( + path.join(projectDir, 'src', 'aliased.ts'), + `import { one } from '@lib/helpers';\nexport const two = one + 1;\nexport const lazy = () => import('@lib/helpers');\n`, + ); + + const result = await executor( + { + ...esmOptions, + fullySpecifiedImports: true, + resolvePaths: true, + resolvePathsBaseDir: './src', + }, + context, + ); + expect(result.success).toBe(true); + + const outDir = path.join(projectDir, 'npm', 'esm'); + const indexContent = await readFileText(path.join(outDir, 'index.js')); + expect(indexContent).toContain(`from './utils/index.js'`); + expect(indexContent).not.toContain('@lib/'); + + const aliasedContent = await readFileText(path.join(outDir, 'aliased.js')); + expect(aliasedContent).toContain(`from './helpers.js'`); + expect(aliasedContent).toContain(`import('./helpers.js')`); + expect(aliasedContent).not.toContain('@lib/'); + }, 10000); + + it('should fail on a relative import that does not resolve', async () => { + await writeFileText( + path.join(projectDir, 'src', 'broken.ts'), + `// @ts-ignore\nimport { missing } from './missing';\nexport const value = missing;\n`, + ); + + const result = await executor({ ...esmOptions, fullySpecifiedImports: true }, context); + expect(result.success).toBe(false); + }, 10000); + }); + describe('Error handling', () => { it('should fail when tsconfig is missing', async () => { fs.unlinkSync(path.join(projectDir, 'tsconfig.esm.json')); @@ -183,52 +273,61 @@ describe('BuildTypescriptExecutor E2E', () => { throw new Error('waitFor timed out'); } - it('emits to outDir with alias resolution and stops on SIGINT', async () => { - const options: BuildTypescriptExecutorSchema = { - module: 'esm', - tsconfig: './tsconfig.esm.json', - outDir: './npm/esm-watch', - resolvePaths: true, - resolvePathsBaseDir: './src', - watch: true, - }; - - const outIndex = path.join(projectDir, 'npm', 'esm-watch', 'index.js'); - - const originalOnce = process.once; - let stopWatch: (() => void) | undefined; - let run: Promise<{ success: boolean }> | undefined; - - (process as unknown as { once: typeof process.once }).once = (( - event: string, - handler: () => void, - ) => { - if (event === 'SIGINT' || event === 'SIGTERM') { - stopWatch = handler; - return process; + it.each([ + { fullySpecifiedImports: false, expectedImport: `from './utils'` }, + { fullySpecifiedImports: true, expectedImport: `from './utils/index.js'` }, + ])( + 'emits to outDir with alias resolution (fullySpecifiedImports: $fullySpecifiedImports) and stops on SIGINT', + async ({ fullySpecifiedImports, expectedImport }) => { + const options: BuildTypescriptExecutorSchema = { + module: 'esm', + tsconfig: './tsconfig.esm.json', + outDir: './npm/esm-watch', + resolvePaths: true, + resolvePathsBaseDir: './src', + fullySpecifiedImports, + watch: true, + }; + + const outIndex = path.join(projectDir, 'npm', 'esm-watch', 'index.js'); + + const originalOnce = process.once; + let stopWatch: (() => void) | undefined; + let run: Promise<{ success: boolean }> | undefined; + + (process as unknown as { once: typeof process.once }).once = (( + event: string, + handler: () => void, + ) => { + if (event === 'SIGINT' || event === 'SIGTERM') { + stopWatch = handler; + return process; + } + return originalOnce.call(process, event, handler as never); + }) as typeof process.once; + + try { + run = executor(options, context); + + await waitFor(() => fs.existsSync(outIndex)); + const indexContent = await readFileText(outIndex); + expect(indexContent).not.toContain('@lib/utils'); + expect(indexContent).toContain(expectedImport); + + stopWatch?.(); + stopWatch = undefined; + + expect((await run).success).toBe(true); + run = undefined; + } finally { + stopWatch?.(); + if (run) { + await run; + } + (process as unknown as { once: typeof process.once }).once = originalOnce; } - return originalOnce.call(process, event, handler as never); - }) as typeof process.once; - - try { - run = executor(options, context); - - await waitFor(() => fs.existsSync(outIndex)); - const indexContent = await readFileText(outIndex); - expect(indexContent).not.toContain('@lib/utils'); - - stopWatch?.(); - stopWatch = undefined; - - expect((await run).success).toBe(true); - run = undefined; - } finally { - stopWatch?.(); - if (run) { - await run; - } - (process as unknown as { once: typeof process.once }).once = originalOnce; - } - }, 30000); + }, + 30000, + ); }); }); diff --git a/packages/nx-infra-plugin/src/executors/build-typescript/fully-specified-imports.ts b/packages/nx-infra-plugin/src/executors/build-typescript/fully-specified-imports.ts new file mode 100644 index 000000000000..e32a7b940532 --- /dev/null +++ b/packages/nx-infra-plugin/src/executors/build-typescript/fully-specified-imports.ts @@ -0,0 +1,153 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import * as ts from 'typescript'; + +const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx']; +const OUTPUT_EXTENSION = '.js'; +const INDEX_FILE = 'index'; +const SPECIFIED_EXTENSION = /\.(js|mjs|cjs|json)$/; + +const ERROR_UNRESOLVED = (specifier: string, fileName: string) => + `Cannot make the import fully specified: '${specifier}' in ${fileName} does not resolve to a source file or folder index`; + +function isRelative(specifier: string): boolean { + return specifier.startsWith('./') || specifier.startsWith('../'); +} + +function fileExists(candidate: string): boolean { + return fs.existsSync(candidate) && fs.statSync(candidate).isFile(); +} + +// './core/component' -> './core/component.js', './common' -> './common/index.js' +export function toFullySpecifiedSpecifier(specifier: string, importerFileName: string): string { + if (!isRelative(specifier) || SPECIFIED_EXTENSION.test(specifier)) { + return specifier; + } + + const target = path.resolve(path.dirname(importerFileName), specifier); + + if (SOURCE_EXTENSIONS.some((extension) => fileExists(target + extension))) { + return `${specifier}${OUTPUT_EXTENSION}`; + } + + if ( + SOURCE_EXTENSIONS.some((extension) => fileExists(path.join(target, INDEX_FILE + extension))) + ) { + return `${specifier.replace(/\/$/, '')}/${INDEX_FILE}${OUTPUT_EXTENSION}`; + } + + throw new Error(ERROR_UNRESOLVED(specifier, importerFileName)); +} + +// A tsconfig "paths" alias of a project source becomes a fully specified relative import: +// '@ts/helpers' -> './helpers.js', '@ts/utils' -> './utils/index.js'. The output mirrors the source +// tree, so the relative path between the sources is the path between the emitted files. +// The alias must be resolved first: the alias replacement (tsc-alias) runs on the emitted text and +// emits extensionless paths, and it does not recognize an alias with an extension added. +// Node10 resolution finds folder indexes whatever moduleResolution the project uses. +// A specifier that is not an alias of a project source, such as a package, stays as it is. +export function toFullySpecifiedAlias( + specifier: string, + importerFileName: string, + compilerOptions: ts.CompilerOptions, +): string { + if (isRelative(specifier) || SPECIFIED_EXTENSION.test(specifier)) { + return specifier; + } + + const { resolvedModule } = ts.resolveModuleName( + specifier, + importerFileName, + { ...compilerOptions, moduleResolution: ts.ModuleResolutionKind.Node10 }, + ts.sys, + ); + if ( + !resolvedModule + || resolvedModule.isExternalLibraryImport + || resolvedModule.extension === ts.Extension.Dts + ) { + return specifier; + } + + const resolvedPath = resolvedModule.resolvedFileName.slice(0, -resolvedModule.extension.length); + const relativePath = path + .relative(path.dirname(importerFileName), resolvedPath) + .split(path.sep) + .join('/'); + const relativeSpecifier = relativePath.startsWith('.') ? relativePath : `./${relativePath}`; + + return `${relativeSpecifier}${OUTPUT_EXTENSION}`; +} + +export interface FullySpecifiedImportsOptions { + // Also rewrite tsconfig "paths" aliases of project sources, for builds with resolvePaths + aliases?: boolean; +} + +// Runs after TypeScript's own transforms, so type-only imports are already elided. +// Rewrites static imports, re-exports and dynamic import() calls with relative specifiers, +// which makes the ESM output loadable by Node and by bundlers in strict ESM mode. +export function createFullySpecifiedImportsTransformer( + options: FullySpecifiedImportsOptions = {}, +): ts.TransformerFactory { + return (context) => (sourceFile) => { + const { factory } = context; + const compilerOptions = context.getCompilerOptions(); + const rewrite = (literal: ts.StringLiteral): ts.StringLiteral => { + const specifier = + isRelative(literal.text) || !options.aliases + ? toFullySpecifiedSpecifier(literal.text, sourceFile.fileName) + : toFullySpecifiedAlias(literal.text, sourceFile.fileName, compilerOptions); + if (specifier === literal.text) { + return literal; + } + // Keep the quotes of the source; a synthesized literal (pos -1) has no source text + const isSingleQuote = literal.pos >= 0 && literal.getText(sourceFile).startsWith("'"); + return factory.createStringLiteral(specifier, isSingleQuote); + }; + + const visitor = (node: ts.Node): ts.Node => { + if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { + return factory.updateImportDeclaration( + node, + node.modifiers, + node.importClause, + rewrite(node.moduleSpecifier), + node.attributes, + ); + } + + if ( + ts.isExportDeclaration(node) + && node.moduleSpecifier + && ts.isStringLiteral(node.moduleSpecifier) + ) { + return factory.updateExportDeclaration( + node, + node.modifiers, + node.isTypeOnly, + node.exportClause, + rewrite(node.moduleSpecifier), + node.attributes, + ); + } + + if ( + ts.isCallExpression(node) + && node.expression.kind === ts.SyntaxKind.ImportKeyword + && node.arguments.length > 0 + && ts.isStringLiteral(node.arguments[0]) + ) { + const [specifier, ...rest] = node.arguments; + return factory.updateCallExpression(node, node.expression, node.typeArguments, [ + rewrite(specifier as ts.StringLiteral), + ...rest, + ]); + } + + return ts.visitEachChild(node, visitor, context); + }; + + return ts.visitEachChild(sourceFile, visitor, context); + }; +} diff --git a/packages/nx-infra-plugin/src/executors/build-typescript/schema.json b/packages/nx-infra-plugin/src/executors/build-typescript/schema.json index b77bb1964ee8..0162b14d597e 100644 --- a/packages/nx-infra-plugin/src/executors/build-typescript/schema.json +++ b/packages/nx-infra-plugin/src/executors/build-typescript/schema.json @@ -44,6 +44,11 @@ "type": "string", "description": "Base directory for path alias resolution (used as aliasRoot for tsc-alias). Relative to project root. Required when resolvePaths is true. Example: './js' for DevExtreme's __internal TypeScript compilation." }, + "fullySpecifiedImports": { + "type": "boolean", + "default": false, + "description": "Add the file extension to relative imports in the output ('./core/component' -> './core/component.js', './common' -> './common/index.js'), so Node can load the ESM output. Fails the build on a relative import that does not resolve to a source file or folder index." + }, "watch": { "type": "boolean", "default": false, diff --git a/packages/nx-infra-plugin/src/executors/build-typescript/schema.ts b/packages/nx-infra-plugin/src/executors/build-typescript/schema.ts index 7c3b2e10ccfe..906c642d72a2 100644 --- a/packages/nx-infra-plugin/src/executors/build-typescript/schema.ts +++ b/packages/nx-infra-plugin/src/executors/build-typescript/schema.ts @@ -6,5 +6,6 @@ export interface BuildTypescriptExecutorSchema { outDir?: string; resolvePaths?: boolean; resolvePathsBaseDir?: string; + fullySpecifiedImports?: boolean; watch?: boolean; } diff --git a/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/executor.e2e.spec.ts b/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/executor.e2e.spec.ts index 2b13b37dd718..1bbbc5bfe006 100644 --- a/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/executor.e2e.spec.ts +++ b/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/executor.e2e.spec.ts @@ -150,6 +150,46 @@ describe('CreateDualModeManifest Executor E2E', () => { }, 30000); }); + describe('Side effects', () => { + it('should follow fully specified and extensionless imports', async () => { + const esmDir = path.join(projectDir, 'artifacts', 'transpiled-esm-npm', 'esm'); + await writeFileText( + path.join(esmDir, 'editor.js'), + `import './events/click.js';\nimport { helper } from './helpers.js';\nexport const Editor = helper;`, + ); + await writeFileText(path.join(esmDir, 'events', 'click.js'), `window.click = true;`); + await writeFileText( + path.join(esmDir, 'helpers.js'), + `import './events/hover';\nexport const helper = () => {};`, + ); + await writeFileText(path.join(esmDir, 'events', 'hover.js'), `window.hover = true;`); + await writeFileText( + path.join(projectDir, 'artifacts', 'transpiled-esm-npm', 'cjs', 'editor.js'), + '', + ); + + const options: CreateDualModeManifestExecutorSchema = { + esmDir: './artifacts/transpiled-esm-npm/esm', + cjsDir: './artifacts/transpiled-esm-npm/cjs', + outputDir: './artifacts/transpiled-esm-npm', + srcDir: './js', + }; + + const result = await executor(options, context); + expect(result.success).toBe(true); + + const editorPackageJson = JSON.parse( + await readFileText( + path.join(projectDir, 'artifacts', 'transpiled-esm-npm', 'editor', 'package.json'), + ), + ); + expect(editorPackageJson.sideEffects).toEqual([ + '../esm/events/click.js', + '../esm/events/hover.js', + ]); + }, 30000); + }); + describe('Index file handling', () => { it('should place package.json in same directory for index.js files', async () => { const options: CreateDualModeManifestExecutorSchema = { diff --git a/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/side-effect-finder.ts b/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/side-effect-finder.ts index f2bc64430fb0..16bb132a7b6b 100644 --- a/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/side-effect-finder.ts +++ b/packages/nx-infra-plugin/src/executors/create-dual-mode-manifest/side-effect-finder.ts @@ -1,6 +1,16 @@ import * as fs from 'fs'; import * as path from 'path'; +const isFile = (filePath: string): boolean => + fs.existsSync(filePath) && fs.statSync(filePath).isFile(); + +// Specifiers may be fully specified ('./button.js') or extensionless ('./button', './grids') +function resolveImportPath(target: string): string { + const candidates = [target, `${target}.js`, path.join(target, 'index.js')]; + + return candidates.find(isFile) ?? `${target}.js`; +} + export class SideEffectFinder { private checkedPaths: Map> = new Map(); private recursiveHandlingPaths: Set = new Set(); @@ -50,12 +60,8 @@ export class SideEffectFinder { const match = str.match(relativePathRegExp); if (!match) return; - let importPath = match[0].replace(/(^['"]|['"]$)/g, ''); - importPath = path.join(path.dirname(modulePath), importPath) + '.js'; - - if (!fs.existsSync(importPath)) { - importPath = importPath.replace(/\.js$/, '/index.js'); - } + const specifier = match[0].replace(/(^['"]|['"]$)/g, ''); + const importPath = resolveImportPath(path.join(path.dirname(modulePath), specifier)); if (isSideEffectImportRegExp.test(str)) { foundPaths.add(importPath); diff --git a/packages/nx-infra-plugin/src/executors/generate-exports-map/executor.e2e.spec.ts b/packages/nx-infra-plugin/src/executors/generate-exports-map/executor.e2e.spec.ts new file mode 100644 index 000000000000..44a2f5dfb35f --- /dev/null +++ b/packages/nx-infra-plugin/src/executors/generate-exports-map/executor.e2e.spec.ts @@ -0,0 +1,224 @@ +import * as path from 'path'; +import { logger } from '@nx/devkit'; +import executor from './executor'; +import { GenerateExportsMapExecutorSchema } from './schema'; +import { createTempDir, cleanupTempDir, createMockContext } from '../../utils/test-utils'; +import { readJson, writeFileText } from '../../utils'; + +describe('GenerateExportsMapExecutor E2E', () => { + let tempDir: string; + let packageDir: string; + let context = createMockContext(); + + const write = (relativePath: string, content = ''): Promise => + writeFileText(path.join(packageDir, relativePath), content); + + const writeJsonFile = (relativePath: string, data: object): Promise => + write(relativePath, JSON.stringify(data)); + + const run = (options: Partial = {}) => + executor({ packageDir: './npm', ignore: ['esm', 'cjs', 'bundles'], ...options }, context); + + const readExports = async (): Promise> => + ( + await readJson>>(path.join(packageDir, 'package.json')) + )['exports']; + + beforeEach(async () => { + tempDir = createTempDir('nx-generate-exports-map-e2e-'); + context = createMockContext({ root: tempDir }); + packageDir = path.join(tempDir, 'packages', 'test-lib', 'npm'); + + await writeJsonFile('package.json', { + name: 'test-lib', + version: '1.0.0', + types: './bundles/all.d.ts', + }); + await write('bundles/all.d.ts'); + + await writeJsonFile('ui/button/package.json', { + sideEffects: false, + main: '../../cjs/ui/button.js', + module: '../../esm/ui/button.js', + typings: '../button.d.ts', + }); + await write('cjs/ui/button.js'); + await write('esm/ui/button.js'); + await write('ui/button.d.ts'); + }); + + afterEach(() => { + cleanupTempDir(tempDir); + }); + + it('should export every stub with types, module, import, require and default conditions', async () => { + const result = await run(); + expect(result.success).toBe(true); + + const exportsMap = await readExports(); + expect(exportsMap['.']).toEqual({ types: './bundles/all.d.ts' }); + expect(exportsMap['./package.json']).toBe('./package.json'); + expect(exportsMap['./ui/button']).toEqual({ + types: './ui/button.d.ts', + module: './esm/ui/button.js', + import: './esm/ui/button.js', + require: './cjs/ui/button.js', + default: './esm/ui/button.js', + }); + expect(Object.keys(exportsMap['./ui/button'] as object)[0]).toBe('types'); + }); + + it('should export declarations without a stub as type-only modules', async () => { + await write('ui/button_types.d.ts'); + await write('data/index.d.ts'); + await write('esm/ui/ignored.d.ts'); + + const result = await run(); + expect(result.success).toBe(true); + + const exportsMap = await readExports(); + expect(exportsMap['./ui/button_types']).toEqual({ types: './ui/button_types.d.ts' }); + expect(exportsMap['./data']).toEqual({ types: './data/index.d.ts' }); + expect(exportsMap['./esm/ui/ignored']).toBeUndefined(); + }); + + it('should append extra exports after the generated entries', async () => { + const result = await run({ + extraExports: { + './dist/*': './dist/*', + './scss/*': './scss/*', + }, + }); + expect(result.success).toBe(true); + + const keys = Object.keys(await readExports()); + expect(keys.slice(-2)).toEqual(['./dist/*', './scss/*']); + }); + + it('should add .d type imports per folder and per root declaration when declarationImports is set', async () => { + await write('common.d.ts'); + await write('ui/button_types.d.ts'); + await write('viz/core/utils.d.ts'); + await write('esm/ui/ignored.d.ts'); + + const result = await run({ declarationImports: true }); + expect(result.success).toBe(true); + + const exportsMap = await readExports(); + expect(exportsMap['./common.d']).toEqual({ types: './common.d.ts' }); + expect(exportsMap['./ui/*.d']).toEqual({ types: './ui/*.d.ts' }); + expect(exportsMap['./viz/*.d']).toEqual({ types: './viz/*.d.ts' }); + expect(exportsMap['./esm/*.d']).toBeUndefined(); + // A './*' pattern makes Node warn (DEP0155) on every 'test-lib/' request + expect(Object.keys(exportsMap).filter((key) => key.startsWith('./*'))).toEqual([]); + }); + + it('should not add .d type imports by default', async () => { + await write('common.d.ts'); + + const result = await run(); + expect(result.success).toBe(true); + + const keys = Object.keys(await readExports()); + expect(keys.filter((key) => key.endsWith('.d'))).toEqual([]); + }); + + it('should map folder modules in directoryIndexes folders to their index.js', async () => { + await write('esm/ui/list/index.js'); + await write('cjs/ui/list/index.js'); + await write('cjs/grids/utils.js'); + await write('cjs/grids/utils/index.js'); + await write('esm/ui/menu.js'); + + const result = await run({ + directoryIndexes: ['esm', 'cjs'], + extraExports: { './esm/*': './esm/*.js', './cjs/*': './cjs/*.js' }, + }); + expect(result.success).toBe(true); + + const exportsMap = await readExports(); + expect(exportsMap['./esm/ui/list']).toBe('./esm/ui/list/index.js'); + expect(exportsMap['./cjs/ui/list']).toBe('./cjs/ui/list/index.js'); + // The sibling file wins over the folder, so the folder stays on the './cjs/*' pattern + expect(exportsMap['./cjs/grids/utils']).toBeUndefined(); + expect(exportsMap['./esm/ui/menu']).toBeUndefined(); + }); + + it('should add types to folder entries from the folder or from directoryIndexTypesFrom', async () => { + await write('esm/common/index.js'); + await write('cjs/common/index.js'); + await write('cjs/common/index.d.ts'); + + const result = await run({ + directoryIndexes: ['esm', 'cjs'], + directoryIndexTypesFrom: { esm: 'cjs' }, + }); + expect(result.success).toBe(true); + + const exportsMap = await readExports(); + expect(exportsMap['./esm/common']).toEqual({ + types: './cjs/common/index.d.ts', + default: './esm/common/index.js', + }); + expect(exportsMap['./cjs/common']).toEqual({ + types: './cjs/common/index.d.ts', + default: './cjs/common/index.js', + }); + }); + + it('should not map folder modules by default', async () => { + await write('esm/ui/list/index.js'); + + const result = await run(); + expect(result.success).toBe(true); + + expect((await readExports())['./esm/ui/list']).toBeUndefined(); + }); + + describe('package with a root module', () => { + beforeEach(async () => { + await writeJsonFile('package.json', { + name: 'test-lib', + version: '1.0.0', + main: './cjs/index.js', + module: './esm/index.js', + types: './cjs/index.d.ts', + }); + await write('cjs/index.js'); + await write('cjs/index.d.ts'); + await write('esm/index.js'); + await writeJsonFile('ui/button/package.json', { + main: '../../cjs/ui/button.js', + module: '../../esm/ui/button.js', + typings: '../../cjs/ui/button.d.ts', + }); + await write('cjs/ui/button.d.ts'); + }); + + it('should export the root module from main, module and types', async () => { + const result = await run(); + expect(result.success).toBe(true); + + expect((await readExports())['.']).toEqual({ + types: './cjs/index.d.ts', + module: './esm/index.js', + import: './esm/index.js', + require: './cjs/index.js', + default: './esm/index.js', + }); + }); + }); + + it('should fail when an entry points to a missing file', async () => { + const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => undefined); + await writeJsonFile('ui/menu/package.json', { + main: '../../cjs/ui/menu.js', + module: '../../esm/ui/menu.js', + }); + + const result = await run(); + + expect(result.success).toBe(false); + errorSpy.mockRestore(); + }); +}); diff --git a/packages/nx-infra-plugin/src/executors/generate-exports-map/executor.ts b/packages/nx-infra-plugin/src/executors/generate-exports-map/executor.ts new file mode 100644 index 000000000000..4d18826f37de --- /dev/null +++ b/packages/nx-infra-plugin/src/executors/generate-exports-map/executor.ts @@ -0,0 +1 @@ +export { default } from './generate-exports-map.impl'; diff --git a/packages/nx-infra-plugin/src/executors/generate-exports-map/generate-exports-map.impl.ts b/packages/nx-infra-plugin/src/executors/generate-exports-map/generate-exports-map.impl.ts new file mode 100644 index 000000000000..edae679839f5 --- /dev/null +++ b/packages/nx-infra-plugin/src/executors/generate-exports-map/generate-exports-map.impl.ts @@ -0,0 +1,260 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import { glob } from 'glob'; +import { logger } from '@nx/devkit'; +import { createExecutor } from '../../utils/create-executor'; +import { readJson, writeJson } from '../../utils/file-operations'; +import { toPosixPath } from '../../utils/path-resolver'; +import { ExportsTarget, GenerateExportsMapExecutorSchema } from './schema'; + +type ExportsMap = Record; + +interface ModuleStub { + main?: string; + module?: string; + typings?: string; +} + +const PACKAGE_JSON = 'package.json'; +const DTS_EXTENSION = '.d.ts'; +const JS_EXTENSION = '.js'; +const INDEX_FILE = 'index.js'; +const INDEX_DTS_FILE = 'index.d.ts'; + +const ERROR_DUPLICATE_SUBPATH = (subpath: string) => + `extraExports redefines a generated subpath: ${subpath}`; +const ERROR_MISSING_TARGETS = (missing: string[]) => + `The exports map points to files that do not exist:\n${missing.join('\n')}`; + +function toSubpath(packageDir: string, absolutePath: string): string { + const relative = toPosixPath(path.relative(packageDir, absolutePath)); + return relative ? `./${relative}` : '.'; +} + +// `module` comes first, so bundlers resolve both import and require() to esm/, as they do through +// the stub's `module` field today, and an app never loads two copies of the package. +// Node and Jest ignore `module` and keep loading cjs/ through require(). +export function createStubEntry( + stubPath: string, + stub: ModuleStub, + packageDir: string, +): ExportsTarget | null { + const stubDir = path.dirname(stubPath); + const resolveTarget = (file?: string) => + file ? toSubpath(packageDir, path.resolve(stubDir, file)) : undefined; + + const esm = resolveTarget(stub.module); + const cjs = resolveTarget(stub.main); + const types = resolveTarget(stub.typings); + const fallback = esm ?? cjs; + + if (!fallback) { + return null; + } + + return { + ...(types && { types }), + ...(esm && { module: esm, import: esm }), + ...(cjs && { require: cjs }), + default: fallback, + }; +} + +// The root entry comes from the root package.json fields: { types } alone for a package +// without a root module, such as devextreme, or a full entry for main/module, such as devextreme-react. +export function createRootEntry( + rootPackageJsonPath: string, + pkg: Record, + packageDir: string, +): ExportsTarget | null { + const field = (name: string) => + typeof pkg[name] === 'string' ? (pkg[name] as string) : undefined; + const stub: ModuleStub = { + main: field('main'), + module: field('module'), + typings: field('types'), + }; + const entry = createStubEntry(rootPackageJsonPath, stub, packageDir); + + if (entry || !stub.typings) { + return entry; + } + + return { types: toSubpath(packageDir, path.resolve(packageDir, stub.typings)) }; +} + +// './ui/button_types.d.ts' -> './ui/button_types', './data/index.d.ts' -> './data' +export function toTypeOnlySubpath(dtsSubpath: string): string { + const withoutExtension = dtsSubpath.slice(0, -DTS_EXTENSION.length); + return withoutExtension.endsWith('/index') + ? withoutExtension.slice(0, -'/index'.length) + : withoutExtension; +} + +// Entries for type imports with a '.d' suffix ('pkg/ui/button.d'): a './ui/*.d' pattern per folder +// and an explicit entry per root file ('./common.d'). A root './*.d' pattern would also do, but +// Node warns (DEP0155) on every 'pkg/' request when a pattern key starts with './*', and bundlers +// make such requests for prefix shares, such as 'devextreme/' in Module Federation. +export function createDeclarationImportEntries(dtsFiles: string[]): ExportsMap { + const entries: ExportsMap = {}; + + for (const dtsFile of dtsFiles) { + const separatorIndex = dtsFile.indexOf('/'); + if (separatorIndex === -1) { + const withoutTs = dtsFile.slice(0, -'.ts'.length); + entries[`./${withoutTs}`] = { types: `./${dtsFile}` }; + } else { + const folder = dtsFile.slice(0, separatorIndex); + entries[`./${folder}/*.d`] = { types: `./${folder}/*.d.ts` }; + } + } + + return entries; +} + +export async function createDirectoryIndexEntries( + packageDir: string, + folders: string[], + typesFrom: Record = {}, +): Promise { + const entries: ExportsMap = {}; + + for (const folder of folders) { + const indexFiles = await glob(`${folder}/**/${INDEX_FILE}`, { cwd: packageDir, posix: true }); + const typesFolder = typesFrom[folder] ?? folder; + + for (const indexFile of indexFiles.sort()) { + const folderPath = indexFile.slice(0, -`/${INDEX_FILE}`.length); + if (fs.existsSync(path.join(packageDir, `${folderPath}${JS_EXTENSION}`))) { + continue; + } + + const types = `${typesFolder}${folderPath.slice(folder.length)}/${INDEX_DTS_FILE}`; + entries[`./${folderPath}`] = fs.existsSync(path.join(packageDir, types)) + ? { types: `./${types}`, default: `./${indexFile}` } + : `./${indexFile}`; + } + } + + return entries; +} + +function collectTargets(target: ExportsTarget): string[] { + return typeof target === 'string' ? [target] : Object.values(target); +} + +function findMissingTargets(packageDir: string, exportsMap: ExportsMap): string[] { + return Object.entries(exportsMap) + .filter(([subpath]) => !subpath.includes('*')) + .flatMap(([subpath, target]) => + collectTargets(target) + .filter((file) => !fs.existsSync(path.join(packageDir, file))) + .map((file) => `${subpath} -> ${file}`), + ); +} + +interface ResolvedGenerateExportsMap { + packageDir: string; + ignore: string[]; + declarationImports: boolean; + directoryIndexes: string[]; + directoryIndexTypesFrom: Record; + extraExports: ExportsMap; +} + +export default createExecutor({ + name: 'GenerateExportsMap', + resolve: (options, { projectRoot }) => ({ + packageDir: path.resolve(projectRoot, options.packageDir), + ignore: options.ignore ?? [], + declarationImports: options.declarationImports ?? false, + directoryIndexes: options.directoryIndexes ?? [], + directoryIndexTypesFrom: options.directoryIndexTypesFrom ?? {}, + extraExports: options.extraExports ?? {}, + }), + run: async ({ + packageDir, + ignore, + declarationImports, + directoryIndexes, + directoryIndexTypesFrom, + extraExports, + }) => { + const rootPackageJsonPath = path.join(packageDir, PACKAGE_JSON); + const pkg = await readJson>(rootPackageJsonPath); + const globIgnore = ['node_modules/**', ...ignore.map((dir) => `${dir}/**`)]; + + const exportsMap: ExportsMap = {}; + + const rootEntry = createRootEntry(rootPackageJsonPath, pkg, packageDir); + if (rootEntry) { + exportsMap['.'] = rootEntry; + } + exportsMap['./package.json'] = './package.json'; + + const stubPaths = await glob(`**/${PACKAGE_JSON}`, { + cwd: packageDir, + absolute: true, + ignore: [PACKAGE_JSON, ...globIgnore], + }); + let stubCount = 0; + + for (const stubPath of stubPaths.sort()) { + const entry = createStubEntry(stubPath, await readJson(stubPath), packageDir); + if (entry) { + exportsMap[toSubpath(packageDir, path.dirname(stubPath))] = entry; + stubCount += 1; + } + } + + // Declarations without a stub are type-only modules, such as ui/button_types + const dtsFiles = await glob(`**/*${DTS_EXTENSION}`, { + cwd: packageDir, + posix: true, + ignore: globIgnore, + }); + let typeOnlyCount = 0; + + // Sorted so that 'data.d.ts' wins over 'data/index.d.ts', as in TypeScript resolution + for (const dtsFile of dtsFiles.sort()) { + const types = `./${dtsFile}`; + const subpath = toTypeOnlySubpath(types); + if (!(subpath in exportsMap)) { + exportsMap[subpath] = { types }; + typeOnlyCount += 1; + } + } + + if (declarationImports) { + Object.assign(exportsMap, createDeclarationImportEntries(dtsFiles)); + } + + const directoryIndexEntries = await createDirectoryIndexEntries( + packageDir, + directoryIndexes, + directoryIndexTypesFrom, + ); + Object.assign(exportsMap, directoryIndexEntries); + + for (const [subpath, target] of Object.entries(extraExports)) { + if (subpath in exportsMap) { + throw new Error(ERROR_DUPLICATE_SUBPATH(subpath)); + } + exportsMap[subpath] = target; + } + + const missing = findMissingTargets(packageDir, exportsMap); + if (missing.length > 0) { + throw new Error(ERROR_MISSING_TARGETS(missing)); + } + + pkg['exports'] = exportsMap; + await writeJson(rootPackageJsonPath, pkg); + + logger.verbose( + `Generated exports in ${rootPackageJsonPath}: ${stubCount} modules, ${typeOnlyCount} type-only modules, ` + + `${Object.keys(directoryIndexEntries).length} folder indexes, ` + + `${Object.keys(extraExports).length} extra entries`, + ); + }, +}); diff --git a/packages/nx-infra-plugin/src/executors/generate-exports-map/schema.json b/packages/nx-infra-plugin/src/executors/generate-exports-map/schema.json new file mode 100644 index 000000000000..a13f6ad70846 --- /dev/null +++ b/packages/nx-infra-plugin/src/executors/generate-exports-map/schema.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/schema", + "version": 2, + "title": "Generate Exports Map Executor Schema", + "description": "Generates the package.json \"exports\" map of an assembled npm package from its per-directory package.json stubs and type declarations.", + "type": "object", + "properties": { + "packageDir": { + "type": "string", + "description": "Assembled npm package directory (root package.json plus per-directory stubs with main/module/typings)." + }, + "ignore": { + "type": "array", + "items": { "type": "string" }, + "description": "Directories (relative to packageDir) to skip when looking for stubs and type-only modules.", + "default": [] + }, + "declarationImports": { + "type": "boolean", + "description": "Adds entries for type imports with a '.d' suffix, such as 'pkg/ui/button.d': a './/*.d' pattern per top-level folder and an explicit entry per root declaration. No root './*.d' pattern, which makes Node warn (DEP0155) on 'pkg/' requests.", + "default": false + }, + "directoryIndexes": { + "type": "array", + "items": { "type": "string" }, + "description": "Deep-import folders (relative to packageDir), such as esm and cjs, whose subfolders with index.js get an explicit './' -> './/index.js' entry, because a './esm/*' -> './esm/*.js' pattern cannot reach a folder module. A folder with a sibling '.js' file gets no entry: the file keeps precedence.", + "default": [] + }, + "directoryIndexTypesFrom": { + "type": "object", + "additionalProperties": { "type": "string" }, + "description": "Declaration folder for a directoryIndexes folder that ships no declarations, such as { \"esm\": \"cjs\" }: the entry for esm/ gets types from cjs//index.d.ts. By default a folder entry gets types from its own index.d.ts, when there is one.", + "default": {} + }, + "extraExports": { + "type": "object", + "description": "Subpath entries appended to the generated map as-is, such as asset folders or wildcard patterns.", + "default": {} + } + }, + "required": ["packageDir"] +} diff --git a/packages/nx-infra-plugin/src/executors/generate-exports-map/schema.ts b/packages/nx-infra-plugin/src/executors/generate-exports-map/schema.ts new file mode 100644 index 000000000000..7e9b65e5a4dd --- /dev/null +++ b/packages/nx-infra-plugin/src/executors/generate-exports-map/schema.ts @@ -0,0 +1,10 @@ +export type ExportsTarget = string | { [condition: string]: string }; + +export interface GenerateExportsMapExecutorSchema { + packageDir: string; + ignore?: string[]; + declarationImports?: boolean; + directoryIndexes?: string[]; + directoryIndexTypesFrom?: Record; + extraExports?: Record; +} diff --git a/packages/nx-infra-plugin/src/executors/prepare-submodules/executor.e2e.spec.ts b/packages/nx-infra-plugin/src/executors/prepare-submodules/executor.e2e.spec.ts index 29be7577bafe..0f0c166e4608 100644 --- a/packages/nx-infra-plugin/src/executors/prepare-submodules/executor.e2e.spec.ts +++ b/packages/nx-infra-plugin/src/executors/prepare-submodules/executor.e2e.spec.ts @@ -116,6 +116,27 @@ describe('PrepareSubmodulesExecutor E2E', () => { expect(customPkg.module).toBe('../esm/custom.js'); }); + it('should treat fully specified imports in the ESM index file as the same modules', async () => { + const npmDir = path.join(tempDir, 'packages', 'test-package', 'npm'); + + await writeFileText( + path.join(npmDir, 'esm', 'index.js'), + `export { Button } from "./button.js";\nexport { Grid } from "./data/grid.js";`, + ); + + const result = await executor({ distDirectory: './npm' }, context); + + expect(result.success).toBe(true); + expect(fs.existsSync(path.join(npmDir, 'button.js'))).toBe(false); + + const buttonPkg = JSON.parse(await readFileText(path.join(npmDir, 'button', 'package.json'))); + expect(buttonPkg.module).toBe('../esm/button.js'); + expect(buttonPkg.typings).toBe('../cjs/button.d.ts'); + + const gridPkg = JSON.parse(await readFileText(path.join(npmDir, 'grid', 'package.json'))); + expect(gridPkg.main).toBe('../cjs/data/grid.js'); + }); + it('should generate package.json files for explicit submoduleFolders entries', async () => { const npmDir = path.join(tempDir, 'packages', 'test-package', 'npm'); diff --git a/packages/nx-infra-plugin/src/executors/prepare-submodules/prepare-submodules.impl.ts b/packages/nx-infra-plugin/src/executors/prepare-submodules/prepare-submodules.impl.ts index 90dab90e0c4f..cc1082333668 100644 --- a/packages/nx-infra-plugin/src/executors/prepare-submodules/prepare-submodules.impl.ts +++ b/packages/nx-infra-plugin/src/executors/prepare-submodules/prepare-submodules.impl.ts @@ -140,7 +140,11 @@ export default createExecutor { + const packParamsForModules: PackParam[] = Array.from(modulesPaths).map(([, importPath]) => { + // A fully specified import ('./button.js') names the same module as './button' + const modulePath = importPath.endsWith(JS_EXTENSION) + ? importPath.slice(0, -JS_EXTENSION.length) + : importPath; const match = modulePath.match(REGEX_PARSE_MODULE) || []; const moduleFilePath = match[2] as string | undefined; const moduleFileName = match[3] as string | undefined; diff --git a/packages/nx-infra-plugin/src/executors/state-manager-optimize/executor.e2e.spec.ts b/packages/nx-infra-plugin/src/executors/state-manager-optimize/executor.e2e.spec.ts index 4246a88e7ea2..198a81567914 100644 --- a/packages/nx-infra-plugin/src/executors/state-manager-optimize/executor.e2e.spec.ts +++ b/packages/nx-infra-plugin/src/executors/state-manager-optimize/executor.e2e.spec.ts @@ -14,7 +14,7 @@ import { writeFileText, readFileText } from '../../utils'; const WORKSPACE_ROOT = findWorkspaceRoot(); const INDEX_DEV_CONTENT = `export { setupStateManager, signal } from './dev/index';\n`; -const INDEX_PROD_CONTENT = `export * from './prod/index';`; +const INDEX_PROD_CONTENT = `export * from './prod/index.js';`; const DEV_FILE_CONTENT = `export const devOnly = () => {};\n`; const PROD_FILE_CONTENT = `export const prodOnly = () => {};\n`; const TOP_LEVEL_NON_INDEX_CONTENT = `export const topLevelNonIndex = () => {};\n`; @@ -97,7 +97,7 @@ describe('StateManagerOptimizeExecutor E2E', () => { expect(await readFileText(indexPathFor('esm'))).toBe(INDEX_PROD_CONTENT); const cjsIndexContent = await readFileText(indexPathFor('cjs')); - expect(cjsIndexContent).toContain('require("./prod/index")'); + expect(cjsIndexContent).toContain('require("./prod/index.js")'); }, 30000); it('should optimize index.js when state_manager lives at flat root layout (no cjs/esm variant subdir)', async () => { @@ -129,7 +129,7 @@ describe('StateManagerOptimizeExecutor E2E', () => { await runOptimize(); expect(await readFileText(path.join(flatStateManagerDir, 'index.js'))).toBe(INDEX_PROD_CONTENT); - expect(await readFileText(indexPathFor('cjs'))).toContain('require("./prod/index")'); + expect(await readFileText(indexPathFor('cjs'))).toContain('require("./prod/index.js")'); }, 30000); it('should throw when no state_manager directories are found in any transpiledDir', async () => { diff --git a/packages/nx-infra-plugin/src/executors/state-manager-optimize/state-manager-optimize.impl.ts b/packages/nx-infra-plugin/src/executors/state-manager-optimize/state-manager-optimize.impl.ts index 14e45dcc7aa2..3d45af0e1c20 100644 --- a/packages/nx-infra-plugin/src/executors/state-manager-optimize/state-manager-optimize.impl.ts +++ b/packages/nx-infra-plugin/src/executors/state-manager-optimize/state-manager-optimize.impl.ts @@ -8,7 +8,7 @@ import { removeDirectoryRespectingExclusions } from '../clean/clean.impl'; import { toPosixPath } from '../../utils/path-resolver'; import { StateManagerOptimizeExecutorSchema } from './schema'; -const ESM_REEXPORT = "export * from './prod/index';"; +const ESM_REEXPORT = "export * from './prod/index.js';"; const STATE_MANAGER_INDEX_GLOB = '**/__internal/core/state_manager/index.js'; const ERROR_BABEL_NO_CODE = 'Babel returned no code for CJS state_manager index.js'; const ERROR_NO_STATE_MANAGER_FOUND =