@mui/internal-code-infra 0.1.1-canary.36 → 0.1.1-canary.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +24 -5
  2. package/build/babel-config.d.mts +7 -1
  3. package/build/changelog/changelogChanges.d.mts +36 -0
  4. package/build/changelog/changelogTags.d.mts +15 -0
  5. package/build/changelog/fetchChangelogData.d.mts +16 -0
  6. package/build/changelog/index.d.mts +13 -0
  7. package/build/changelog/octokit.d.mts +7 -0
  8. package/build/changelog/types.d.ts +137 -0
  9. package/build/utils/babelPlugin.d.mts +8 -0
  10. package/build/utils/cjsSourcesPlugin.d.mts +11 -0
  11. package/build/utils/dtsExportsPlugin.d.mts +8 -0
  12. package/build/utils/dtsNamespacesPlugin.d.mts +19 -0
  13. package/build/utils/getPublishedPkgJson.d.mts +20 -0
  14. package/build/utils/jsNamespacesPlugin.d.mts +13 -0
  15. package/build/utils/publint.d.mts +6 -0
  16. package/build/utils/rolldownOutput.d.mts +38 -0
  17. package/build/utils/testUtils.d.mts +1 -0
  18. package/build/utils/typescript.d.mts +5 -0
  19. package/package.json +2 -2
  20. package/src/babel-config.mjs +35 -1
  21. package/src/changelog/changelogChanges.mjs +418 -0
  22. package/src/changelog/changelogTags.mjs +34 -0
  23. package/src/changelog/fetchChangelogData.mjs +171 -0
  24. package/src/changelog/fetchChangelogs.mjs +3 -30
  25. package/src/changelog/index.mjs +9 -0
  26. package/src/changelog/octokit.mjs +35 -0
  27. package/src/changelog/types.ts +142 -0
  28. package/src/cli/cmdBuild.mjs +9 -125
  29. package/src/cli/cmdBuildNew.mjs +403 -20
  30. package/src/utils/babelPlugin.mjs +52 -0
  31. package/src/utils/cjsSourcesPlugin.mjs +92 -0
  32. package/src/utils/dtsExportsPlugin.mjs +103 -0
  33. package/src/utils/dtsNamespacesPlugin.mjs +226 -0
  34. package/src/utils/getPublishedPkgJson.mjs +86 -0
  35. package/src/utils/jsNamespacesPlugin.mjs +505 -0
  36. package/src/utils/publint.mjs +34 -0
  37. package/src/utils/rolldownOutput.mjs +70 -0
  38. package/src/utils/testUtils.mjs +8 -0
  39. package/src/utils/typescript.mjs +22 -12
  40. package/build/brokenLinksChecker/__fixtures__/no-signal-forwarding.d.mts +0 -1
@@ -1,12 +1,38 @@
1
+ import getTargets from '@babel/helper-compilation-targets';
2
+ import { findWorkspaceDir } from '@pnpm/find-workspace-dir';
1
3
  import * as fs from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
2
5
  import * as path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { globby } from 'globby';
8
+ import * as semver from 'semver';
3
9
 
4
- import { getOutExtension, getPackageSources, validatePkgJson } from '../utils/build.mjs';
10
+ import {
11
+ getOutExtension,
12
+ getPackageSources,
13
+ validateEnginesNode,
14
+ validatePkgJson,
15
+ } from '../utils/build.mjs';
16
+ import { getVersionEnvVariables } from '../utils/babel.mjs';
17
+ import { babelPlugin } from '../utils/babelPlugin.mjs';
18
+ import { cjsSourcesPlugin } from '../utils/cjsSourcesPlugin.mjs';
19
+ import { dtsExportsPlugin } from '../utils/dtsExportsPlugin.mjs';
20
+ import { dtsNamespacesPlugin } from '../utils/dtsNamespacesPlugin.mjs';
21
+ import { jsNamespacesPlugin } from '../utils/jsNamespacesPlugin.mjs';
5
22
  import { fileUrlEntriesPlugin } from '../utils/fileUrlEntriesPlugin.mjs';
23
+ import { getPublishedPkgJson } from '../utils/getPublishedPkgJson.mjs';
24
+ import { readPnpmConfig } from '../utils/pnpm.mjs';
25
+ import { validateWithPublint } from '../utils/publint.mjs';
26
+ import { getTsconfig } from '../utils/typescript.mjs';
6
27
 
7
28
  /**
8
29
  * @typedef {Object} Args
9
30
  * @property {import('../utils/build.mjs').BundleType[]} bundle
31
+ * @property {string[]} copy
32
+ * @property {boolean} buildTypes
33
+ * @property {boolean} enableReactCompiler
34
+ * @property {boolean} cjsCopy
35
+ * @property {boolean} expand
10
36
  */
11
37
 
12
38
  const SOURCE_DIR = 'src';
@@ -17,6 +43,201 @@ const MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE';
17
43
  /** @type {Record<import('../utils/build.mjs').BundleType, 'es' | 'cjs'>} */
18
44
  const FORMATS = { esm: 'es', cjs: 'cjs' };
19
45
 
46
+ const BABEL_CONFIG_FILES = ['babel.config.js', 'babel.config.mjs'];
47
+
48
+ const TYPESCRIPT = 'typescript';
49
+
50
+ const BABEL_RUNTIME = '@babel/runtime';
51
+
52
+ const OXC_HELPERS = '@oxc-project/runtime/helpers/';
53
+ // Oxc's legacy decorator helpers have no `@babel/runtime` equivalent, so Rolldown bundles them.
54
+ const OXC_SHARED_HELPERS = /^@oxc-project\/runtime\/helpers\/(?!decorate)/;
55
+
56
+ /** @type {Record<import('../utils/build.mjs').BundleType, string>} */
57
+ const BROWSERSLIST_ENVS = { esm: 'stable', cjs: 'node' };
58
+
59
+ // Oxc exports no compat table and accepts some engines it then ignores (android, ie, hermes,
60
+ // rhino), so this lists the Babel target engines Oxc was verified to lower for.
61
+ const OXC_ENGINES = new Set([
62
+ 'chrome',
63
+ 'edge',
64
+ 'electron',
65
+ 'firefox',
66
+ 'ios',
67
+ 'node',
68
+ 'opera',
69
+ 'safari',
70
+ 'samsung',
71
+ ]);
72
+
73
+ /**
74
+ * Resolves the bundle's browserslist environment the way `@babel/preset-env` does. Oxc can't lower
75
+ * for every engine Babel knows, so those fail instead of silently shipping less-compiled code.
76
+ * @param {string} cwd
77
+ * @param {import('../utils/build.mjs').BundleType} bundle
78
+ * @returns {string[]} Oxc targets.
79
+ */
80
+ function getTarget(cwd, bundle) {
81
+ const env = BROWSERSLIST_ENVS[bundle];
82
+ const targets = Object.entries(getTargets({}, { configPath: cwd, browserslistEnv: env }));
83
+ if (targets.length === 0) {
84
+ throw new Error(`No browserslist targets found for the "${env}" environment.`);
85
+ }
86
+
87
+ const unsupported = targets.filter(([engine]) => !OXC_ENGINES.has(engine));
88
+ if (unsupported.length > 0) {
89
+ const engines = unsupported.map(([engine]) => engine).join(', ');
90
+ throw new Error(`Oxc cannot target ${engines} from the "${env}" browserslist environment.`);
91
+ }
92
+
93
+ return targets.map(([engine, version]) => `${engine}${version}`);
94
+ }
95
+
96
+ /**
97
+ * The workspace Babel config, or the base config without one.
98
+ * @param {string} cwd
99
+ * @returns {Promise<string>}
100
+ */
101
+ async function getBabelConfigFile(cwd) {
102
+ const workspaceDir = await findWorkspaceDir(cwd);
103
+ if (!workspaceDir) {
104
+ throw new Error('Workspace directory not found');
105
+ }
106
+ for (const name of BABEL_CONFIG_FILES) {
107
+ const file = path.join(workspaceDir, name);
108
+ // eslint-disable-next-line no-await-in-loop
109
+ if (await exists(file)) {
110
+ return file;
111
+ }
112
+ }
113
+ return path.join(import.meta.dirname, '../babel-config.mjs');
114
+ }
115
+
116
+ /**
117
+ * @param {string} cwd
118
+ * @returns {Promise<string>} The native binary of the workspace's TypeScript 7, which
119
+ * rolldown-plugin-dts runs as `tsgo`.
120
+ */
121
+ async function getTsc(cwd) {
122
+ const workspaceDir = await findWorkspaceDir(cwd);
123
+ if (!workspaceDir) {
124
+ throw new Error('Workspace directory not found');
125
+ }
126
+ const manifest = path.join(workspaceDir, 'package.json');
127
+ const { dependencies, devDependencies } = JSON.parse(await fs.readFile(manifest, 'utf8'));
128
+ const require = createRequire(manifest);
129
+ const candidates = await Promise.all(
130
+ Object.entries({ ...dependencies, ...devDependencies })
131
+ .filter(([name, spec]) => name === TYPESCRIPT || spec.startsWith(`npm:${TYPESCRIPT}@`))
132
+ .map(async ([name]) => {
133
+ const file = require.resolve(`${name}/package.json`);
134
+ const { version } = JSON.parse(await fs.readFile(file, 'utf8'));
135
+ return { dir: path.dirname(file), version };
136
+ }),
137
+ );
138
+ const native = candidates.find(({ version }) => semver.major(version) >= 7);
139
+ if (!native) {
140
+ throw new Error(
141
+ 'Install TypeScript 7 at the workspace root, as "typescript@^7" or under an alias such as "@typescript/native", to build types.',
142
+ );
143
+ }
144
+ // `node_modules/.bin/tsc` is a shell script on Windows, which rolldown-plugin-dts can't spawn.
145
+ const { default: getExePath } = await import(
146
+ pathToFileURL(path.join(native.dir, 'lib/getExePath.js')).href
147
+ );
148
+ return getExePath();
149
+ }
150
+
151
+ /**
152
+ * @param {import('./packageJson').PackageJson} packageJson
153
+ * @returns {Promise<string | undefined>} The `@babel/runtime` range the package depends on.
154
+ */
155
+ async function getBabelRuntime(packageJson) {
156
+ const version = packageJson.dependencies?.[BABEL_RUNTIME];
157
+ if (version !== 'catalog:') {
158
+ return version;
159
+ }
160
+ const config = await readPnpmConfig();
161
+ return config.catalog[BABEL_RUNTIME];
162
+ }
163
+
164
+ /**
165
+ * The environment Babel runs in; workspace configs branch on it.
166
+ * @param {import('./packageJson').PackageJson} packageJson
167
+ * @param {{ bundles: import('../utils/build.mjs').BundleType[]; babelRuntime: string | undefined; reactCompiler: 'on' | 'off' }} options
168
+ * @returns {Record<string, string>}
169
+ */
170
+ function getBabelEnv(packageJson, { bundles, babelRuntime, reactCompiler }) {
171
+ const dependencies = packageJson.dependencies ?? {};
172
+ /** @type {Record<string, string>} */
173
+ const env = {
174
+ NODE_ENV: 'production',
175
+ // One Babel pass serves every format, so configs see the first bundle's environment.
176
+ BABEL_ENV: BROWSERSLIST_ENVS[bundles[0]],
177
+ };
178
+ if (dependencies['prop-types'] !== undefined) {
179
+ env.MUI_REMOVE_PROP_TYPES = 'true';
180
+ }
181
+ if (dependencies.clsx !== undefined || dependencies.classnames !== undefined) {
182
+ env.MUI_OPTIMIZE_CLSX = 'true';
183
+ }
184
+ if (babelRuntime) {
185
+ env.MUI_BABEL_RUNTIME_VERSION = babelRuntime;
186
+ }
187
+ if (reactCompiler === 'on') {
188
+ env.MUI_REACT_COMPILER = '1';
189
+ env.MUI_REACT_COMPILER_REACT_VERSION =
190
+ semver.minVersion(packageJson.peerDependencies?.react ?? '')?.version ?? 'latest';
191
+ }
192
+ return env;
193
+ }
194
+
195
+ /**
196
+ * @param {import('./packageJson').PackageJson} packageJson
197
+ * @returns {string | undefined} The package's license header.
198
+ */
199
+ function getBanner(packageJson) {
200
+ if (!packageJson.license) {
201
+ return undefined;
202
+ }
203
+ return `/**
204
+ * ${packageJson.name} v${packageJson.version}
205
+ *
206
+ * @license ${packageJson.license}
207
+ * This source code is licensed under the ${packageJson.license} license found in the
208
+ * LICENSE file in the root directory of this source tree.
209
+ */`;
210
+ }
211
+
212
+ /**
213
+ * Fails the build when the output imports Babel helpers the package doesn't depend on.
214
+ * @param {string | undefined} babelRuntime
215
+ * @returns {import('tsdown').Rolldown.Plugin}
216
+ */
217
+ function babelRuntimePlugin(babelRuntime) {
218
+ return {
219
+ name: 'code-infra:babel-runtime',
220
+ generateBundle(_options, bundle) {
221
+ if (babelRuntime) {
222
+ return;
223
+ }
224
+ const chunk = Object.values(bundle).find(
225
+ (output) =>
226
+ output.type === 'chunk' &&
227
+ output.imports.some(
228
+ (id) => id.startsWith(`${BABEL_RUNTIME}/`) || id.startsWith(OXC_HELPERS),
229
+ ),
230
+ );
231
+ if (!chunk) {
232
+ return;
233
+ }
234
+ this.error(
235
+ `${chunk.fileName} imports Babel helpers, so package.json needs a dependency on \`${BABEL_RUNTIME}\`.`,
236
+ );
237
+ },
238
+ };
239
+ }
240
+
20
241
  /**
21
242
  * Resolves the source modules behind the package's published paths, keyed by output name.
22
243
  * @param {import('./packageJson').PackageJson} packageJson
@@ -35,27 +256,125 @@ async function getEntry(packageJson, cwd) {
35
256
  );
36
257
  }
37
258
 
259
+ const DOCUMENTS = ['README.md', 'LICENSE', 'CHANGELOG.md'];
260
+
261
+ /** @param {string} file */
262
+ function exists(file) {
263
+ return fs.stat(file).then(
264
+ () => true,
265
+ () => false,
266
+ );
267
+ }
268
+
269
+ /**
270
+ * Package documents fall back to the workspace root, `source:target` globs expand directories and
271
+ * drop the first source directory, and missing paths are skipped.
272
+ * @param {string} cwd
273
+ * @param {string} outDir
274
+ * @param {string[]} globs
275
+ * @returns {Promise<import('tsdown').UserConfig['copy']>}
276
+ */
277
+ async function getCopy(cwd, outDir, globs) {
278
+ const workspaceDir = await findWorkspaceDir(cwd);
279
+ if (!workspaceDir) {
280
+ throw new Error('Workspace directory not found');
281
+ }
282
+
283
+ const documents = Promise.all(
284
+ DOCUMENTS.map(async (name) => {
285
+ const local = path.join(cwd, name);
286
+ if (await exists(local)) {
287
+ return [{ from: local, to: outDir }];
288
+ }
289
+ const root = path.join(workspaceDir, name);
290
+ return (await exists(root)) ? [{ from: root, to: outDir }] : [];
291
+ }),
292
+ );
293
+
294
+ const extras = Promise.all(
295
+ globs.map(async (glob) => {
296
+ const [pattern, target = ''] = glob.split(':');
297
+ const from = await globby(pattern, { cwd });
298
+ if (!from.length) {
299
+ return [];
300
+ }
301
+ return [{ from, to: path.join(outDir, target), flatten: false }];
302
+ }),
303
+ );
304
+
305
+ return (await Promise.all([documents, extras])).flat(2);
306
+ }
307
+
38
308
  export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
39
309
  command: 'build-new',
40
- describe: 'Experimental tsdown build. Compiles JavaScript only.',
310
+ describe: 'Experimental tsdown build. Compiles JavaScript, copies files and writes package.json.',
41
311
  builder: (yargs) =>
42
- yargs.option('bundle', {
43
- array: true,
44
- type: 'string',
45
- choices: /** @type {const} */ (['esm', 'cjs']),
46
- default: /** @type {import('../utils/build.mjs').BundleType[]} */ (['esm', 'cjs']),
47
- description: 'Bundles to output.',
48
- }),
312
+ yargs
313
+ .option('bundle', {
314
+ array: true,
315
+ type: 'string',
316
+ choices: /** @type {const} */ (['esm', 'cjs']),
317
+ default: /** @type {import('../utils/build.mjs').BundleType[]} */ (['esm', 'cjs']),
318
+ description: 'Bundles to output.',
319
+ })
320
+ .option('copy', {
321
+ array: true,
322
+ type: 'string',
323
+ default: /** @type {string[]} */ ([]),
324
+ description: 'Files to copy to the output directory, as `glob` or `glob:target`.',
325
+ })
326
+ .option('buildTypes', {
327
+ type: 'boolean',
328
+ default: true,
329
+ description: 'Whether to write declarations with the workspace TypeScript 7 `tsc`.',
330
+ })
331
+ .option('enableReactCompiler', {
332
+ type: 'boolean',
333
+ default: false,
334
+ description: 'Compile components with the React compiler.',
335
+ })
336
+ // Remove once `next` has an `exports` map: https://github.com/vercel/next.js/issues/77200
337
+ .option('cjsCopy', {
338
+ type: 'boolean',
339
+ deprecated: 'Only for `@mui/material-nextjs`.',
340
+ default: false,
341
+ description:
342
+ 'Emit imported `.cjs` sources unchanged instead of compiling them, and build the local modules they require.',
343
+ })
344
+ .option('expand', {
345
+ type: 'boolean',
346
+ default: true,
347
+ deprecated:
348
+ 'Patterns will always be expanded; this flag will be removed in a future release.',
349
+ description:
350
+ 'Enumerate glob patterns in the package.json "exports"/"imports" into concrete entries. Use --no-expand to keep them as Node runtime subpath patterns.',
351
+ }),
49
352
  async handler(args) {
50
353
  const cwd = process.cwd();
51
354
  const packageJson = JSON.parse(await fs.readFile(path.join(cwd, 'package.json'), 'utf8'));
52
- validatePkgJson(packageJson);
355
+ validatePkgJson(packageJson, { enableReactCompiler: args.enableReactCompiler });
356
+ validateEnginesNode(packageJson, cwd);
53
357
 
54
358
  const outDir = path.join(cwd, packageJson.publishConfig.directory);
55
359
  const packageType = packageJson.type === 'module' ? 'module' : 'commonjs';
56
- const entry = await getEntry(packageJson, cwd);
360
+ const bundles = [...new Set(args.bundle)];
57
361
 
58
- const { build } = await import('tsdown');
362
+ const [entry, copy, babelRuntime, babelConfigFile, tsconfig, tsc, { build }] =
363
+ await Promise.all([
364
+ getEntry(packageJson, cwd),
365
+ getCopy(cwd, outDir, args.copy),
366
+ getBabelRuntime(packageJson),
367
+ getBabelConfigFile(cwd),
368
+ args.buildTypes ? getTsconfig(cwd) : undefined,
369
+ args.buildTypes ? getTsc(cwd) : undefined,
370
+ import('tsdown'),
371
+ ]);
372
+
373
+ const { MUI_PRERELEASE: prerelease, ...versionEnv } = getVersionEnvVariables(
374
+ packageJson.version,
375
+ );
376
+ const reactCompiler = args.enableReactCompiler ? 'on' : 'off';
377
+ Object.assign(process.env, getBabelEnv(packageJson, { bundles, babelRuntime, reactCompiler }));
59
378
  await build({
60
379
  cwd,
61
380
  config: false,
@@ -65,24 +384,88 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
65
384
  root: SOURCE_DIR,
66
385
  outDir,
67
386
  clean: true,
68
- format: [...new Set(args.bundle)].map((bundle) => FORMATS[bundle]),
387
+ format: Object.fromEntries(
388
+ bundles.map((bundle) => [FORMATS[bundle], { target: getTarget(cwd, bundle) }]),
389
+ ),
390
+ env: versionEnv,
391
+ // `env` values go through JSON, which can't hold the `undefined` of a stable version.
392
+ define: {
393
+ 'process.env.MUI_PRERELEASE':
394
+ prerelease === undefined ? 'undefined' : JSON.stringify(prerelease),
395
+ },
396
+ envPrefix: [],
397
+ // `.js` sources may contain JSX.
398
+ loader: { '.js': 'jsx' },
399
+ plugins: [
400
+ args.cjsCopy &&
401
+ cjsSourcesPlugin(
402
+ path.join(cwd, SOURCE_DIR),
403
+ bundles.includes('cjs') ? getOutExtension('cjs', { packageType }) : undefined,
404
+ ),
405
+ fileUrlEntriesPlugin(),
406
+ babelPlugin(babelConfigFile),
407
+ // https://github.com/rolldown/rolldown/issues/6669
408
+ jsNamespacesPlugin(),
409
+ babelRuntimePlugin(babelRuntime),
410
+ ],
411
+ // tsdown leaves `plugins` out of its CJS declaration pass; `inputOptions` reaches every pass.
412
+ inputOptions: (options) => ({
413
+ ...options,
414
+ // tsdown otherwise takes `jsx` from the package's tsconfig, which may preserve JSX.
415
+ transform: { ...options.transform, jsx: { runtime: 'automatic' } },
416
+ plugins: [
417
+ dtsExportsPlugin(),
418
+ // https://github.com/sxzz/rolldown-plugin-dts/issues/300
419
+ dtsNamespacesPlugin(),
420
+ options.plugins,
421
+ ],
422
+ external: [PACKAGE_IMPORTS, OXC_SHARED_HELPERS],
423
+ }),
69
424
  outExtensions: ({ format }) => ({
70
425
  js: getOutExtension(format === 'es' ? 'esm' : 'cjs', { packageType }),
71
426
  }),
72
427
  deps: { neverBundle: true },
73
- plugins: [fileUrlEntriesPlugin()],
74
- inputOptions: {
75
- external: [PACKAGE_IMPORTS],
76
- // tsdown otherwise takes `jsx` from the package's tsconfig, which may preserve JSX.
77
- transform: { jsx: { runtime: 'automatic' } },
428
+ outputOptions: {
429
+ exports: 'named',
430
+ // Returning the id itself would print relative externals unresolved; `undefined` keeps
431
+ // Rolldown's own path for them.
432
+ paths: /** @type {(id: string) => string} */ (
433
+ (id) =>
434
+ id.startsWith(OXC_HELPERS)
435
+ ? `${BABEL_RUNTIME}/helpers/${id.slice(OXC_HELPERS.length)}`
436
+ : undefined
437
+ ),
78
438
  },
79
- outputOptions: { exports: 'named' },
80
- dts: false,
439
+ banner: { js: getBanner(packageJson) },
440
+ tsconfig,
441
+ // Keeps CJS declarations on `export default`, matching the named-exports JS interop.
442
+ cjsDefault: false,
443
+ // TODO: tsdown >=0.23.5 (rolldown-plugin-dts >=0.29) runs TS7 through its API, which needs
444
+ // TypeScript 7.1. Once it's stable, bump and replace `tsgo.path` with `tsgo.moduleUrl`.
445
+ dts: args.buildTypes ? { generator: 'tsgo', tsgo: { path: tsc }, sourcemap: false } : false,
81
446
  exports: false,
82
447
  report: false,
448
+ copy,
83
449
  logLevel: 'warn',
84
450
  // Unbundled output keeps each module's directives; the warning is about bundling.
85
451
  suppressWarnings: [MODULE_LEVEL_DIRECTIVE],
86
452
  });
453
+
454
+ const publishedPkgJson = await getPublishedPkgJson({
455
+ packageJson,
456
+ bundles,
457
+ outputDir: outDir,
458
+ cwd,
459
+ addTypes: args.buildTypes,
460
+ expand: args.expand,
461
+ packageType,
462
+ });
463
+ await fs.writeFile(
464
+ path.join(outDir, 'package.json'),
465
+ JSON.stringify(publishedPkgJson, null, 2),
466
+ 'utf-8',
467
+ );
468
+
469
+ await validateWithPublint(outDir);
87
470
  },
88
471
  });
@@ -0,0 +1,52 @@
1
+ import { transformAsync } from '@babel/core';
2
+
3
+ const BABEL_FILES = /\.[cm]?[jt]sx?$/;
4
+ const TS_FILES = /\.[cm]?tsx?$/;
5
+ const TS_WITHOUT_JSX = /\.[cm]?ts$/;
6
+ const COMMONJS_FILES = /\.c[jt]s$/;
7
+
8
+ /** @type {NonNullable<import('@babel/core').InputOptions['caller']> & { compiler: import('../babel-config.mjs').Compiler }} */
9
+ const CALLER = { name: 'code-infra build-new', compiler: 'oxc' };
10
+
11
+ /**
12
+ * Runs a Babel config in `oxc` mode: `getBaseConfig` keeps only the plugins Oxc has no
13
+ * equivalent for, and the config file adds its own. Oxc then strips types, compiles JSX and
14
+ * lowers syntax.
15
+ * @param {string} configFile
16
+ * @returns {import('tsdown').Rolldown.Plugin}
17
+ */
18
+ export function babelPlugin(configFile) {
19
+ return {
20
+ name: 'code-infra:babel',
21
+ transform: {
22
+ // rolldown-plugin-dts turns declarations into JS stubs Babel can't parse.
23
+ filter: { id: { include: BABEL_FILES, exclude: [/node_modules/, /\.d\.[cm]?ts$/] } },
24
+ async handler(code, id) {
25
+ /** @type {NonNullable<import('@babel/core').InputOptions['parserOpts']>['plugins']} */
26
+ const syntax = [];
27
+ if (TS_FILES.test(id)) {
28
+ syntax.push('typescript');
29
+ }
30
+ if (!TS_WITHOUT_JSX.test(id)) {
31
+ syntax.push('jsx');
32
+ }
33
+ const result = await transformAsync(code, {
34
+ filename: id,
35
+ configFile,
36
+ babelrc: false,
37
+ caller: CALLER,
38
+ sourceMaps: true,
39
+ sourceType: COMMONJS_FILES.test(id) ? 'commonjs' : 'module',
40
+ parserOpts: { plugins: syntax },
41
+ });
42
+ if (!result?.code) {
43
+ return null;
44
+ }
45
+ return {
46
+ code: result.code,
47
+ map: /** @type {import('tsdown').Rolldown.SourceMapInput} */ (result.map),
48
+ };
49
+ },
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,92 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { parse, Visitor } from 'rolldown/utils';
4
+
5
+ /**
6
+ * @param {string} file
7
+ * @param {string} code
8
+ * @returns {Promise<string[]>} The local specifiers the file passes to `require`.
9
+ */
10
+ async function getRequires(file, code) {
11
+ const { program } = await parse(file, code);
12
+ /** @type {string[]} */
13
+ const specifiers = [];
14
+ new Visitor({
15
+ CallExpression(node) {
16
+ const [arg] = node.arguments;
17
+ if (node.callee.type !== 'Identifier' || node.callee.name !== 'require') {
18
+ return;
19
+ }
20
+ if (arg?.type !== 'Literal' || typeof arg.value !== 'string' || !arg.value.startsWith('.')) {
21
+ return;
22
+ }
23
+ specifiers.push(arg.value);
24
+ },
25
+ }).visit(program);
26
+ return specifiers;
27
+ }
28
+
29
+ /**
30
+ * Ships `.cjs` sources unchanged. Rolldown would turn them into ESM whose `require` calls go
31
+ * through a runtime helper bundlers can't resolve, so imports of them stay as written and each is
32
+ * emitted as is. The local modules one requires are built at the path the `require` names. Only
33
+ * `@mui/material-nextjs` needs it: its `.cjs` shims exist because `next` has no `exports` map
34
+ * (https://github.com/vercel/next.js/issues/77200). Remove this plugin once that is fixed.
35
+ * @param {string} sourceDir
36
+ * @param {string | undefined} cjsExtension The CommonJS bundle's output extension, if it is built.
37
+ * @returns {import('tsdown').Rolldown.Plugin}
38
+ */
39
+ export function cjsSourcesPlugin(sourceDir, cjsExtension) {
40
+ /**
41
+ * @param {import('tsdown').Rolldown.PluginContext} context
42
+ * @param {string} file
43
+ * @param {Set<string>} seen The `.cjs` sources already emitted along this `require` chain.
44
+ */
45
+ async function emitSource(context, file, seen = new Set()) {
46
+ if (seen.has(file)) {
47
+ return;
48
+ }
49
+ seen.add(file);
50
+
51
+ const code = await fs.readFile(file, 'utf8');
52
+ context.emitFile({ type: 'asset', fileName: path.relative(sourceDir, file), source: code });
53
+
54
+ for (const specifier of await getRequires(file, code)) {
55
+ // eslint-disable-next-line no-await-in-loop
56
+ const target = await context.resolve(specifier, file);
57
+ if (!target || target.external || path.relative(sourceDir, target.id).startsWith('..')) {
58
+ continue;
59
+ }
60
+ if (target.id.endsWith('.cjs')) {
61
+ // eslint-disable-next-line no-await-in-loop
62
+ await emitSource(context, target.id, seen);
63
+ continue;
64
+ }
65
+ if (path.extname(target.id) !== cjsExtension) {
66
+ context.error(
67
+ `${path.relative(sourceDir, file)} requires '${specifier}', which no CommonJS bundle outputs at that path.`,
68
+ );
69
+ }
70
+ context.emitFile({ type: 'chunk', id: target.id, preserveSignature: 'strict' });
71
+ }
72
+ }
73
+
74
+ return {
75
+ name: 'code-infra:cjs-sources',
76
+ resolveId: {
77
+ filter: { id: /\.cjs$/ },
78
+ async handler(source, importer) {
79
+ // Entries can't be external.
80
+ if (!importer) {
81
+ return null;
82
+ }
83
+ const resolved = await this.resolve(source, importer, { skipSelf: true });
84
+ if (!resolved || resolved.external) {
85
+ return null;
86
+ }
87
+ await emitSource(this, resolved.id);
88
+ return { id: source, external: true };
89
+ },
90
+ },
91
+ };
92
+ }