@mui/internal-code-infra 0.1.1-canary.4 → 0.1.1-canary.40

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 (102) hide show
  1. package/README.md +36 -4
  2. package/build/babel-config.d.mts +7 -1
  3. package/build/changelog/changelogChanges.d.mts +42 -0
  4. package/build/changelog/changelogGrouping.d.mts +52 -0
  5. package/build/changelog/changelogMarkdown.d.mts +69 -0
  6. package/build/changelog/changelogTags.d.mts +15 -0
  7. package/build/changelog/changelogTitle.d.mts +28 -0
  8. package/build/changelog/fetchChangelogData.d.mts +16 -0
  9. package/build/changelog/fetchChangelogs.d.mts +11 -12
  10. package/build/changelog/index.d.mts +25 -0
  11. package/build/changelog/octokit.d.mts +7 -0
  12. package/build/changelog/types.d.ts +174 -0
  13. package/build/eslint/baseConfig.d.mts +1 -1
  14. package/build/eslint/index.d.mts +1 -0
  15. package/build/eslint/mui/rules/no-constructor-assigned-field.d.mts +50 -0
  16. package/build/eslint/nodeSupportConfig.d.mts +11 -0
  17. package/build/eslint/packageJsonConfig.d.mts +7 -0
  18. package/build/remark/config.d.mts +5 -14
  19. package/build/utils/babelPlugin.d.mts +8 -0
  20. package/build/utils/build.d.mts +22 -0
  21. package/build/utils/cjsSourcesPlugin.d.mts +11 -0
  22. package/build/utils/credentials.d.mts +2 -2
  23. package/build/utils/dtsExportsPlugin.d.mts +8 -0
  24. package/build/utils/dtsNamespacesPlugin.d.mts +19 -0
  25. package/build/utils/fileUrlEntriesPlugin.d.mts +9 -0
  26. package/build/utils/getPublishedPkgJson.d.mts +20 -0
  27. package/build/utils/git.d.mts +30 -9
  28. package/build/utils/github.d.mts +8 -0
  29. package/build/utils/jsNamespacesPlugin.d.mts +13 -0
  30. package/build/utils/pnpm.d.mts +67 -3
  31. package/build/utils/publint.d.mts +6 -0
  32. package/build/utils/rolldownOutput.d.mts +38 -0
  33. package/build/utils/testUtils.d.mts +8 -0
  34. package/build/utils/typescript.d.mts +17 -0
  35. package/package.json +61 -49
  36. package/src/babel-config.mjs +35 -1
  37. package/src/brokenLinksChecker/index.mjs +8 -1
  38. package/src/changelog/changelogChanges.mjs +479 -0
  39. package/src/changelog/changelogGrouping.mjs +148 -0
  40. package/src/changelog/changelogMarkdown.mjs +110 -0
  41. package/src/changelog/changelogTags.mjs +34 -0
  42. package/src/changelog/changelogTitle.mjs +56 -0
  43. package/src/changelog/fetchChangelogData.mjs +172 -0
  44. package/src/changelog/fetchChangelogs.mjs +47 -34
  45. package/src/changelog/index.mjs +34 -0
  46. package/src/changelog/octokit.mjs +35 -0
  47. package/src/changelog/types.ts +187 -0
  48. package/src/cli/cmdBaseline.mjs +31 -0
  49. package/src/cli/cmdBuild.mjs +20 -89
  50. package/src/cli/cmdBuildNew.mjs +471 -0
  51. package/src/cli/cmdNetlifyIgnore.mjs +14 -7
  52. package/src/cli/cmdPublish.mjs +17 -3
  53. package/src/cli/cmdPublishNewPackage.mjs +11 -4
  54. package/src/cli/cmdValidateBuiltTypes.mjs +447 -32
  55. package/src/cli/index.mjs +4 -0
  56. package/src/eslint/baseConfig.mjs +10 -2
  57. package/src/eslint/docsConfig.mjs +28 -10
  58. package/src/eslint/index.mjs +1 -0
  59. package/src/eslint/jsonConfig.mjs +2 -1
  60. package/src/eslint/mui/config.mjs +16 -1
  61. package/src/eslint/mui/index.mjs +2 -0
  62. package/src/eslint/mui/rules/disallow-react-api-in-server-components.mjs +4 -1
  63. package/src/eslint/mui/rules/no-constructor-assigned-field.mjs +183 -0
  64. package/src/eslint/nodeSupportConfig.mjs +70 -0
  65. package/src/eslint/packageJsonConfig.mjs +50 -0
  66. package/src/eslint/testConfig.mjs +4 -2
  67. package/src/remark/config.mjs +60 -13
  68. package/src/utils/babelPlugin.mjs +52 -0
  69. package/src/utils/build.mjs +81 -0
  70. package/src/utils/cjsSourcesPlugin.mjs +92 -0
  71. package/src/utils/credentials.mjs +4 -3
  72. package/src/utils/dtsExportsPlugin.mjs +103 -0
  73. package/src/utils/dtsNamespacesPlugin.mjs +226 -0
  74. package/src/utils/extractErrorCodes.mjs +1 -3
  75. package/src/utils/fileUrlEntriesPlugin.mjs +84 -0
  76. package/src/utils/getPublishedPkgJson.mjs +86 -0
  77. package/src/utils/git.mjs +107 -46
  78. package/src/utils/github.mjs +27 -0
  79. package/src/utils/jsNamespacesPlugin.mjs +505 -0
  80. package/src/utils/pnpm.mjs +126 -25
  81. package/src/utils/publint.mjs +34 -0
  82. package/src/utils/rolldownOutput.mjs +70 -0
  83. package/src/utils/testUtils.mjs +26 -0
  84. package/src/utils/typescript.mjs +23 -13
  85. package/vale/styles/MUI/GoogleLatin.yml +5 -2
  86. package/build/cli/cmdArgosPush.d.mts +0 -18
  87. package/build/cli/cmdBuild.d.mts +0 -64
  88. package/build/cli/cmdCopyFiles.d.mts +0 -20
  89. package/build/cli/cmdExtractErrorCodes.d.mts +0 -6
  90. package/build/cli/cmdGenerateChangelog.d.mts +0 -32
  91. package/build/cli/cmdGithubAuth.d.mts +0 -11
  92. package/build/cli/cmdListWorkspaces.d.mts +0 -29
  93. package/build/cli/cmdNetlifyIgnore.d.mts +0 -17
  94. package/build/cli/cmdPublish.d.mts +0 -32
  95. package/build/cli/cmdPublishCanary.d.mts +0 -34
  96. package/build/cli/cmdPublishNewPackage.d.mts +0 -17
  97. package/build/cli/cmdRenameScope.d.mts +0 -18
  98. package/build/cli/cmdSetVersionOverrides.d.mts +0 -9
  99. package/build/cli/cmdVale.d.mts +0 -46
  100. package/build/cli/cmdValidateBuiltTypes.d.mts +0 -2
  101. package/build/cli/index.d.mts +0 -1
  102. package/vale/styles/MUI/CorrectRererenceCased.yml +0 -14
@@ -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
+ }
@@ -23,11 +23,12 @@ const accessedCredentials = new Map();
23
23
 
24
24
  /**
25
25
  * @param {string} key
26
- * @returns {Promise<string | undefined>}
26
+ * @returns {Promise<string | null>}
27
27
  */
28
28
  export async function getPassword(key) {
29
- if (accessedCredentials.has(key)) {
30
- return accessedCredentials.get(key);
29
+ const cached = accessedCredentials.get(key);
30
+ if (cached) {
31
+ return cached;
31
32
  }
32
33
  let credential = credentials.get(key);
33
34
  if (!credential) {
@@ -0,0 +1,103 @@
1
+ import { RolldownMagicString } from 'rolldown';
2
+ import { parse } from 'rolldown/utils';
3
+
4
+ import { DTS_FILES } from './rolldownOutput.mjs';
5
+
6
+ /** @typedef {import('rolldown/utils').ParseResult['program']['body']} Body */
7
+
8
+ /**
9
+ * @param {string} code
10
+ * @param {Body} body
11
+ */
12
+ function reexportImports(code, body) {
13
+ /** @type {Map<string, { name: string; source: string; typeOnly: boolean }>} */
14
+ const imports = new Map();
15
+
16
+ for (const node of body) {
17
+ if (node.type !== 'ImportDeclaration') {
18
+ continue;
19
+ }
20
+
21
+ for (const specifier of node.specifiers) {
22
+ if (specifier.type === 'ImportNamespaceSpecifier') {
23
+ continue;
24
+ }
25
+
26
+ imports.set(specifier.local.name, {
27
+ name:
28
+ specifier.type === 'ImportDefaultSpecifier'
29
+ ? 'default'
30
+ : code.slice(specifier.imported.start, specifier.imported.end),
31
+ source: code.slice(node.source.start, node.source.end),
32
+ typeOnly:
33
+ node.importKind === 'type' ||
34
+ (specifier.type === 'ImportSpecifier' && specifier.importKind === 'type'),
35
+ });
36
+ }
37
+ }
38
+
39
+ const result = new RolldownMagicString(code);
40
+
41
+ for (const node of body) {
42
+ if (node.type !== 'ExportNamedDeclaration' || node.source || node.declaration) {
43
+ continue;
44
+ }
45
+
46
+ const kept = [];
47
+ const statements = [];
48
+
49
+ for (const specifier of node.specifiers) {
50
+ const imported = specifier.local.type === 'Identifier' && imports.get(specifier.local.name);
51
+
52
+ if (!imported) {
53
+ kept.push(code.slice(specifier.start, specifier.end));
54
+ continue;
55
+ }
56
+
57
+ const exported = code.slice(specifier.exported.start, specifier.exported.end);
58
+ const binding = imported.name === exported ? exported : `${imported.name} as ${exported}`;
59
+
60
+ const typeOnly =
61
+ imported.typeOnly || node.exportKind === 'type' || specifier.exportKind === 'type';
62
+
63
+ statements.push(`export ${typeOnly ? 'type ' : ''}{ ${binding} } from ${imported.source};`);
64
+ }
65
+
66
+ if (statements.length === 0) {
67
+ continue;
68
+ }
69
+
70
+ if (kept.length > 0) {
71
+ statements.push(`export ${node.exportKind === 'type' ? 'type ' : ''}{ ${kept.join(', ')} };`);
72
+ }
73
+
74
+ result.update(node.start, node.end, statements.join('\n'));
75
+ }
76
+
77
+ return result.toString();
78
+ }
79
+
80
+ /**
81
+ * rolldown-plugin-dts prints re-exports as `import { X } from …; export { X }`. Module
82
+ * augmentation of the exported alias then doesn't reach the interface other declarations
83
+ * reference, so these become `export { X } from …`.
84
+ * @returns {import('tsdown').Rolldown.Plugin}
85
+ */
86
+ export function dtsExportsPlugin() {
87
+ return {
88
+ name: 'code-infra:dts-exports',
89
+ async generateBundle(_options, bundle) {
90
+ await Promise.all(
91
+ Object.values(bundle).map(async (chunk) => {
92
+ if (chunk.type !== 'chunk' || !DTS_FILES.test(chunk.fileName)) {
93
+ return;
94
+ }
95
+
96
+ const { program } = await parse(chunk.fileName, chunk.code, { lang: 'dts' });
97
+
98
+ chunk.code = reexportImports(chunk.code, program.body);
99
+ }),
100
+ );
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,226 @@
1
+ import * as path from 'node:path';
2
+ import { parse } from 'rolldown/utils';
3
+
4
+ import {
5
+ applyEdits,
6
+ countReferences,
7
+ DTS_FILES,
8
+ GENERATED_NAMESPACE,
9
+ getBinding,
10
+ getName,
11
+ slice,
12
+ } from './rolldownOutput.mjs';
13
+
14
+ /** @typedef {import('./rolldownOutput.mjs').Node} Node */
15
+
16
+ /**
17
+ * @param {import('tsdown').Rolldown.OutputChunk} chunk
18
+ */
19
+ async function parseChunk(chunk) {
20
+ const { program } = await parse(chunk.fileName, chunk.code, { lang: 'dts' });
21
+ return program.body;
22
+ }
23
+
24
+ /**
25
+ * @typedef {Object} Namespace
26
+ * @property {string} local The binding the module exports the namespace by.
27
+ * @property {Node} node The declaration or import that creates it.
28
+ */
29
+
30
+ /**
31
+ * The `<name>_exports` namespaces Rolldown creates for a module's namespace object: a declared
32
+ * namespace, or a package's namespace a module only re-exports.
33
+ * @param {Awaited<ReturnType<typeof parseChunk>>} body
34
+ * @returns {Map<string, Namespace>}
35
+ */
36
+ function getNamespaces(body) {
37
+ /** @type {Map<string, import('rolldown/utils').ESTree.ImportDeclaration>} */
38
+ const packageNamespaces = new Map();
39
+ /** @type {Map<string, Namespace>} */
40
+ const namespaces = new Map();
41
+ for (const node of body) {
42
+ if (
43
+ node.type === 'ImportDeclaration' &&
44
+ !node.source.value.startsWith('.') &&
45
+ node.specifiers.length === 1 &&
46
+ node.specifiers[0].type === 'ImportNamespaceSpecifier'
47
+ ) {
48
+ packageNamespaces.set(node.specifiers[0].local.name, node);
49
+ continue;
50
+ }
51
+ if (
52
+ node.type === 'TSModuleDeclaration' &&
53
+ node.declare &&
54
+ node.id.type === 'Identifier' &&
55
+ GENERATED_NAMESPACE.test(node.id.name) &&
56
+ node.body?.type === 'TSModuleBlock' &&
57
+ node.body.body.every((child) => child.type === 'ExportNamedDeclaration' && !child.source)
58
+ ) {
59
+ namespaces.set(node.id.name, { local: node.id.name, node });
60
+ }
61
+ }
62
+
63
+ for (const node of body) {
64
+ if (node.type !== 'ExportNamedDeclaration' || node.source || node.declaration) {
65
+ continue;
66
+ }
67
+ for (const specifier of node.specifiers) {
68
+ const [local, exported] = getBinding(specifier);
69
+ const imported = local && packageNamespaces.get(getName(local));
70
+ if (!imported || !exported || !GENERATED_NAMESPACE.test(getName(exported))) {
71
+ continue;
72
+ }
73
+ namespaces.set(getName(exported), { local: getName(local), node: imported });
74
+ }
75
+ }
76
+ return namespaces;
77
+ }
78
+
79
+ /**
80
+ * Rewrites imports of generated namespaces to `import * as`, then drops the namespaces.
81
+ * @param {import('tsdown').Rolldown.OutputChunk[]} chunks
82
+ */
83
+ async function inlineNamespaces(chunks) {
84
+ const parsed = await Promise.all(
85
+ chunks.map(async (chunk) => ({ chunk, body: await parseChunk(chunk) })),
86
+ );
87
+ const namespacesByFile = new Map(
88
+ parsed.map(({ chunk, body }) => [jsFileName(chunk.fileName), getNamespaces(body)]),
89
+ );
90
+
91
+ for (const { chunk, body } of parsed) {
92
+ /** @type {import('./rolldownOutput.mjs').Edit[]} */
93
+ const edits = [];
94
+ for (const node of body) {
95
+ if (
96
+ (node.type !== 'ImportDeclaration' && node.type !== 'ExportNamedDeclaration') ||
97
+ !node.source?.value.startsWith('.')
98
+ ) {
99
+ continue;
100
+ }
101
+ const target = path.posix.join(path.posix.dirname(chunk.fileName), node.source.value);
102
+ const namespaces = namespacesByFile.get(target);
103
+ if (!namespaces?.size) {
104
+ continue;
105
+ }
106
+ const source = JSON.stringify(node.source.value);
107
+ const typeOnly =
108
+ node.type === 'ImportDeclaration' && node.importKind === 'type' ? 'type ' : '';
109
+ const keyword = node.type === 'ImportDeclaration' ? 'import' : 'export';
110
+ /** @type {string[]} */
111
+ const rest = [];
112
+ /** @type {string[]} */
113
+ const statements = [];
114
+ /** @type {string | undefined} */
115
+ let defaultImport;
116
+ let rewritten = false;
117
+ for (const specifier of node.specifiers) {
118
+ if (specifier.type === 'ImportDefaultSpecifier') {
119
+ defaultImport = specifier.local.name;
120
+ continue;
121
+ }
122
+ const [imported, alias] = getBinding(specifier);
123
+ if (!imported || !alias || !namespaces.has(getName(imported))) {
124
+ rest.push(slice(chunk.code, specifier));
125
+ continue;
126
+ }
127
+ rewritten = true;
128
+ // Rolldown also imports namespaces it doesn't use.
129
+ if (keyword === 'import' && countReferences(chunk.code, getName(alias)) === 1) {
130
+ continue;
131
+ }
132
+ statements.push(`${keyword} ${typeOnly}* as ${getName(alias)} from ${source};`);
133
+ }
134
+ if (!rewritten) {
135
+ continue;
136
+ }
137
+ const clauses = [defaultImport, rest.length > 0 ? `{ ${rest.join(', ')} }` : undefined];
138
+ if (defaultImport || rest.length > 0) {
139
+ statements.unshift(
140
+ `${keyword} ${typeOnly}${clauses.filter(Boolean).join(', ')} from ${source};`,
141
+ );
142
+ }
143
+ edits.push({
144
+ start: node.start,
145
+ end: node.end,
146
+ text: statements.join('\n'),
147
+ });
148
+ }
149
+ chunk.code = applyEdits(chunk.code, edits);
150
+ }
151
+
152
+ const rewritten = await Promise.all(
153
+ chunks.map(async (chunk) => ({ chunk, body: await parseChunk(chunk) })),
154
+ );
155
+ for (const { chunk, body } of rewritten) {
156
+ const exports = body.flatMap((node) =>
157
+ node.type === 'ExportNamedDeclaration' && !node.source && !node.declaration
158
+ ? node.specifiers.map((specifier) => getBinding(specifier)[0])
159
+ : [],
160
+ );
161
+ // A namespace the module uses itself is referenced beyond its declaration and exports.
162
+ const unused = [...getNamespaces(body)].filter(([, { local }]) => {
163
+ const exported = exports.filter((binding) => binding && getName(binding) === local).length;
164
+ return countReferences(chunk.code, local) === 1 + exported;
165
+ });
166
+ if (unused.length === 0) {
167
+ continue;
168
+ }
169
+ const names = new Set(unused.map(([name]) => name));
170
+ /** @type {import('./rolldownOutput.mjs').Edit[]} */
171
+ const edits = unused.map(([, { node }]) => ({
172
+ start: node.start,
173
+ end: node.end,
174
+ text: '',
175
+ }));
176
+ for (const node of body) {
177
+ if (node.type !== 'ExportNamedDeclaration' || node.source || node.declaration) {
178
+ continue;
179
+ }
180
+ const kept = node.specifiers.filter((specifier) => {
181
+ const [, exported] = getBinding(specifier);
182
+ return !exported || !names.has(getName(exported));
183
+ });
184
+ if (kept.length === node.specifiers.length) {
185
+ continue;
186
+ }
187
+ edits.push({
188
+ start: node.start,
189
+ end: node.end,
190
+ text:
191
+ kept.length === 0
192
+ ? 'export {};'
193
+ : `export { ${kept.map((specifier) => slice(chunk.code, specifier)).join(', ')} };`,
194
+ });
195
+ }
196
+ chunk.code = applyEdits(chunk.code, edits);
197
+ }
198
+ }
199
+
200
+ /**
201
+ * `models/index.d.mts` → `models/index.mjs`, the path declarations import it by.
202
+ * @param {string} fileName
203
+ */
204
+ function jsFileName(fileName) {
205
+ return fileName.replace(/\.d\.([cm]?)ts$/, '.$1js');
206
+ }
207
+
208
+ /**
209
+ * For a namespace import, rolldown-plugin-dts declares a `<name>_exports` namespace that leaves out
210
+ * names re-exported from packages. Importers get `import * as` instead, as tsc emits, and the
211
+ * namespace is dropped. Remove this plugin once rolldown-plugin-dts keeps those names:
212
+ * https://github.com/sxzz/rolldown-plugin-dts/issues/300
213
+ * @returns {import('tsdown').Rolldown.Plugin}
214
+ */
215
+ export function dtsNamespacesPlugin() {
216
+ return {
217
+ name: 'code-infra:dts-namespaces',
218
+ async generateBundle(_options, bundle) {
219
+ const chunks = Object.values(bundle).filter(
220
+ /** @returns {output is import('tsdown').Rolldown.OutputChunk} */
221
+ (output) => output.type === 'chunk' && DTS_FILES.test(output.fileName),
222
+ );
223
+ await inlineNamespaces(chunks);
224
+ },
225
+ };
226
+ }
@@ -99,9 +99,7 @@ export default async function extractErrorCodes(args) {
99
99
  const packages = basePackages.filter(
100
100
  (pkg) =>
101
101
  // Ignore obvious packages that do not have user-facing errors
102
- !pkg.name.startsWith('@mui/internal-') &&
103
- !pkg.name.startsWith('@mui-internal/') &&
104
- !skipPackages.includes(pkg.name),
102
+ !pkg.name.startsWith('@mui/internal-') && !skipPackages.includes(pkg.name),
105
103
  );
106
104
  const files = await Promise.all(packages.map((pkg) => getFilesForPackage(pkg)));
107
105
  packages.forEach((pkg, index) => {
@@ -0,0 +1,84 @@
1
+ import * as path from 'node:path';
2
+ import { RolldownMagicString } from 'rolldown';
3
+ import { parse, Visitor } from 'rolldown/utils';
4
+
5
+ const SCRIPT_FILES = /\.[cm]?[jt]sx?$/;
6
+ const TS_FILES = /\.[cm]?ts$/;
7
+
8
+ /**
9
+ * @typedef {import('rolldown/utils').ESTree.NewExpression} NewExpression
10
+ */
11
+
12
+ /**
13
+ * Returns the relative path of `new URL('./file', import.meta.url)`.
14
+ * @param {NewExpression} node
15
+ */
16
+ function getFileUrlPath(node) {
17
+ const [file, base] = node.arguments;
18
+ if (
19
+ node.callee.type !== 'Identifier' ||
20
+ node.callee.name !== 'URL' ||
21
+ file?.type !== 'Literal' ||
22
+ typeof file.value !== 'string' ||
23
+ !file.value.startsWith('.') ||
24
+ base?.type !== 'MemberExpression' ||
25
+ base.object.type !== 'MetaProperty' ||
26
+ base.property.type !== 'Identifier' ||
27
+ base.property.name !== 'url'
28
+ ) {
29
+ return undefined;
30
+ }
31
+ return file.value;
32
+ }
33
+
34
+ /**
35
+ * Builds the modules sources load with `new URL('./file', import.meta.url)`, such as workers. No
36
+ * import or `exports` entry reaches them, so they would be missing from the output. Each becomes
37
+ * an entry, compiled like any other source, and the URL is rewritten to its output path and
38
+ * extension (`new URL('./worker.ts', …)` → `new URL('./worker.mjs', …)`).
39
+ * @returns {import('tsdown').Rolldown.Plugin}
40
+ */
41
+ export function fileUrlEntriesPlugin() {
42
+ return {
43
+ name: 'code-infra:file-url-entries',
44
+ transform: {
45
+ filter: { id: { exclude: /node_modules/ }, code: 'import.meta.url' },
46
+ async handler(code, id) {
47
+ // `.js` sources may contain JSX.
48
+ const lang = TS_FILES.test(id) ? 'ts' : 'tsx';
49
+ const { program } = await parse(id, code, { lang });
50
+
51
+ /** @type {NewExpression[]} */
52
+ const urls = [];
53
+ new Visitor({
54
+ NewExpression(node) {
55
+ if (getFileUrlPath(node)) {
56
+ urls.push(node);
57
+ }
58
+ },
59
+ }).visit(program);
60
+
61
+ const result = new RolldownMagicString(code);
62
+ const resolved = await Promise.all(
63
+ urls.map((node) => this.resolve(/** @type {string} */ (getFileUrlPath(node)), id)),
64
+ );
65
+ resolved.forEach((target, index) => {
66
+ if (!target || target.external || !SCRIPT_FILES.test(target.id)) {
67
+ return;
68
+ }
69
+ const ref = this.emitFile({ type: 'chunk', id: target.id, preserveSignature: 'strict' });
70
+ result.update(urls[index].start, urls[index].end, `import.meta.ROLLUP_FILE_URL_${ref}`);
71
+ });
72
+ return result.hasChanged() ? result.toString() : null;
73
+ },
74
+ },
75
+ resolveFileUrl({ chunkId, fileName, format }) {
76
+ const relative = path.posix.relative(path.posix.dirname(chunkId), fileName);
77
+ const file = JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`);
78
+ // Bundlers only treat the literal `new URL('./file', import.meta.url)` as a worker or asset.
79
+ return format === 'es'
80
+ ? `new URL(${file}, import.meta.url)`
81
+ : `new URL(${file}, require("node:url").pathToFileURL(__filename))`;
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,86 @@
1
+ import { createPackageBin, createPackageExports, createPackageImports } from './build.mjs';
2
+
3
+ /**
4
+ * @param {Object} options
5
+ * @param {import('../cli/packageJson').PackageJson} options.packageJson - The source package.json content.
6
+ * @param {import('./build.mjs').BundleType[]} options.bundles
7
+ * @param {string} options.outputDir
8
+ * @param {string} options.cwd
9
+ * @param {boolean} options.addTypes - Whether to add type declarations for the package.
10
+ * @param {boolean} [options.expand] - Whether to enumerate glob patterns into concrete entries.
11
+ * @param {'module' | 'commonjs'} options.packageType - The package.json type field.
12
+ * @returns {Promise<import('../cli/packageJson').PackageJson>} The package.json to publish from `outputDir`.
13
+ */
14
+ export async function getPublishedPkgJson({
15
+ packageJson: source,
16
+ bundles,
17
+ outputDir,
18
+ cwd,
19
+ addTypes = false,
20
+ expand = true,
21
+ packageType,
22
+ }) {
23
+ const {
24
+ scripts,
25
+ devDependencies,
26
+ exports: originalExports,
27
+ imports: originalImports,
28
+ bin: originalBin,
29
+ ...packageJson
30
+ } = source;
31
+
32
+ if (packageJson.publishConfig) {
33
+ const { directory, scripts: publishedScripts, ...publishConfig } = packageJson.publishConfig;
34
+ packageJson.publishConfig = publishConfig;
35
+
36
+ if (publishedScripts) {
37
+ Object.assign(packageJson, { scripts: publishedScripts });
38
+ }
39
+ }
40
+
41
+ const resolvedPackageType = packageType || packageJson.type || 'commonjs';
42
+ packageJson.type = resolvedPackageType;
43
+
44
+ const [{ exports: packageExports, main, types }, packageImports] = await Promise.all([
45
+ createPackageExports(originalExports, {
46
+ bundles,
47
+ outputDir,
48
+ cwd,
49
+ addTypes,
50
+ expand,
51
+ packageType: resolvedPackageType,
52
+ }),
53
+ originalImports
54
+ ? createPackageImports(originalImports, {
55
+ bundles,
56
+ cwd,
57
+ outputDir,
58
+ addTypes,
59
+ expand,
60
+ packageType: resolvedPackageType,
61
+ })
62
+ : Promise.resolve(undefined),
63
+ ]);
64
+
65
+ packageJson.exports = packageExports;
66
+ if (packageImports) {
67
+ packageJson.imports = packageImports;
68
+ }
69
+ if (main) {
70
+ packageJson.main = main;
71
+ }
72
+ if (types) {
73
+ packageJson.types = types;
74
+ }
75
+
76
+ const bin = await createPackageBin(originalBin, {
77
+ bundles,
78
+ cwd,
79
+ packageType: resolvedPackageType,
80
+ });
81
+ if (bin) {
82
+ packageJson.bin = bin;
83
+ }
84
+
85
+ return packageJson;
86
+ }