@mui/internal-code-infra 0.1.1-canary.34 → 0.1.1-canary.36
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.
- package/README.md +10 -0
- package/build/changelog/fetchChangelogs.d.mts +2 -2
- package/build/utils/build.d.mts +8 -0
- package/build/utils/fileUrlEntriesPlugin.d.mts +9 -0
- package/build/utils/testUtils.d.mts +7 -0
- package/build/utils/typescript.d.mts +12 -0
- package/package.json +8 -6
- package/src/changelog/fetchChangelogs.mjs +2 -2
- package/src/cli/cmdBuildNew.mjs +88 -0
- package/src/cli/cmdValidateBuiltTypes.mjs +447 -32
- package/src/cli/index.mjs +2 -0
- package/src/utils/build.mjs +47 -0
- package/src/utils/fileUrlEntriesPlugin.mjs +84 -0
- package/src/utils/testUtils.mjs +18 -0
- package/src/utils/typescript.mjs +1 -1
- package/build/cli/cmdArgosPush.d.mts +0 -18
- package/build/cli/cmdBaseline.d.mts +0 -18
- package/build/cli/cmdBuild.d.mts +0 -68
- package/build/cli/cmdCopyFiles.d.mts +0 -20
- package/build/cli/cmdExtractErrorCodes.d.mts +0 -6
- package/build/cli/cmdGenerateChangelog.d.mts +0 -32
- package/build/cli/cmdGithubAuth.d.mts +0 -11
- package/build/cli/cmdListWorkspaces.d.mts +0 -29
- package/build/cli/cmdNetlifyIgnore.d.mts +0 -17
- package/build/cli/cmdPublish.d.mts +0 -32
- package/build/cli/cmdPublishCanary.d.mts +0 -34
- package/build/cli/cmdPublishNewPackage.d.mts +0 -17
- package/build/cli/cmdRenameScope.d.mts +0 -18
- package/build/cli/cmdSetVersionOverrides.d.mts +0 -9
- package/build/cli/cmdVale.d.mts +0 -46
- package/build/cli/cmdValidateBuiltTypes.d.mts +0 -2
- package/build/cli/index.d.mts +0 -1
|
@@ -1,48 +1,463 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
|
-
import {
|
|
2
|
+
import { $ } from 'execa';
|
|
3
3
|
import * as fs from 'node:fs/promises';
|
|
4
|
+
import * as os from 'node:os';
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
import { mapAsync, uniqBy } from 'es-toolkit/array';
|
|
7
|
+
import { isEqual } from 'es-toolkit/predicate';
|
|
4
8
|
import { findWorkspaceDir } from '@pnpm/find-workspace-dir';
|
|
5
|
-
import {
|
|
9
|
+
import { resolveExports } from 'resolve-pkg-maps';
|
|
10
|
+
import * as semver from 'semver';
|
|
11
|
+
import { stringify } from 'yaml';
|
|
12
|
+
import { getWorkspacePackages, readPackageJson, writePackageJson } from '../utils/pnpm.mjs';
|
|
13
|
+
import { findTscPair } from '../utils/typescript.mjs';
|
|
6
14
|
|
|
7
|
-
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {import('./packageJson').PackageJson} PackageJson
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {Object} TypeScriptError
|
|
21
|
+
* @property {string} file `<package>/<path>` for files inside a packed package, otherwise relative
|
|
22
|
+
* to the consumer project.
|
|
23
|
+
* @property {string} code
|
|
24
|
+
* @property {string} message
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @typedef {Map<string, string>} EntryPoints Import specifier to the declaration file it resolves
|
|
29
|
+
* to.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The kinds of consumers, with the runtime `exports` conditions each matches besides `default`.
|
|
34
|
+
* `types` comes first in every published manifest, so matching it in all modes is what TypeScript
|
|
35
|
+
* does too.
|
|
36
|
+
*/
|
|
37
|
+
const CONSUMERS = [
|
|
38
|
+
{ kind: 'esm', extension: 'mts', conditions: ['import', 'node'], module: 'nodenext' },
|
|
39
|
+
{ kind: 'cjs', extension: 'cts', conditions: ['require', 'node'], module: 'nodenext' },
|
|
40
|
+
{
|
|
41
|
+
kind: 'bundler',
|
|
42
|
+
extension: 'mts',
|
|
43
|
+
conditions: ['import'],
|
|
44
|
+
module: 'esnext',
|
|
45
|
+
moduleResolution: 'bundler',
|
|
46
|
+
},
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {unknown} packageExports
|
|
51
|
+
* @param {string} subpath `''` for the package itself.
|
|
52
|
+
* @param {string[]} conditions
|
|
53
|
+
* @returns {string | undefined} The first target, or `undefined` when the subpath doesn't resolve.
|
|
54
|
+
*/
|
|
55
|
+
function resolveTarget(packageExports, subpath, conditions) {
|
|
56
|
+
try {
|
|
57
|
+
return resolveExports(
|
|
58
|
+
/** @type {Parameters<typeof resolveExports>[0]} */ (packageExports),
|
|
59
|
+
subpath,
|
|
60
|
+
conditions,
|
|
61
|
+
)[0];
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (/** @type {{ code?: string }} */ (error).code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Lists the modules consumers can import types from under `conditions`. Glob subpaths are skipped:
|
|
72
|
+
* `code-infra build` expands them into concrete entries. Entry points without a runtime target,
|
|
73
|
+
* such as code-infra's `build-env`, are left out: nothing imports them.
|
|
74
|
+
*
|
|
75
|
+
* @param {PackageJson} packageJson A published manifest.
|
|
76
|
+
* @param {string[]} conditions
|
|
77
|
+
* @returns {EntryPoints}
|
|
78
|
+
*/
|
|
79
|
+
function getTypedEntryPoints(packageJson, conditions) {
|
|
80
|
+
const name = /** @type {string} */ (packageJson.name);
|
|
81
|
+
const types = packageJson.types ?? packageJson.typings;
|
|
82
|
+
const packageExports =
|
|
83
|
+
packageJson.exports ?? (types ? { types, default: packageJson.main ?? './index.js' } : null);
|
|
84
|
+
if (!packageExports) {
|
|
85
|
+
return new Map();
|
|
86
|
+
}
|
|
87
|
+
const subpaths =
|
|
88
|
+
typeof packageExports === 'object' &&
|
|
89
|
+
!Array.isArray(packageExports) &&
|
|
90
|
+
Object.keys(packageExports).some((key) => key.startsWith('.'))
|
|
91
|
+
? Object.keys(packageExports)
|
|
92
|
+
.filter((key) => !key.includes('*'))
|
|
93
|
+
.map((key) => key.slice(2))
|
|
94
|
+
: [''];
|
|
95
|
+
/** @type {EntryPoints} */
|
|
96
|
+
const entryPoints = new Map();
|
|
97
|
+
for (const subpath of subpaths) {
|
|
98
|
+
const declarations = resolveTarget(packageExports, subpath, ['types', ...conditions]);
|
|
99
|
+
if (
|
|
100
|
+
declarations &&
|
|
101
|
+
/\.d\.[cm]?ts$/.test(declarations) &&
|
|
102
|
+
resolveTarget(packageExports, subpath, conditions)
|
|
103
|
+
) {
|
|
104
|
+
entryPoints.set(subpath ? `${name}/${subpath}` : name, declarations);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return entryPoints;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @param {EntryPoints} entryPoints
|
|
112
|
+
* @returns {string}
|
|
113
|
+
*/
|
|
114
|
+
function createEntryFile(entryPoints) {
|
|
115
|
+
return `${Array.from(entryPoints.keys())
|
|
116
|
+
.map((specifier, index) => `import type * as entry${index} from '${specifier}';`)
|
|
117
|
+
.join('\n')}\nexport {};\n`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* `@scope/pkg` → `scope+pkg`, the same file names as @mui/internal-benchmark's `packWorkspace`.
|
|
122
|
+
* `+` cannot appear in a package name, so no two collide.
|
|
123
|
+
*
|
|
124
|
+
* @param {string} packageName
|
|
125
|
+
*/
|
|
126
|
+
function toFileStem(packageName) {
|
|
127
|
+
return packageName.replace(/^@/, '').replace('/', '+');
|
|
128
|
+
}
|
|
8
129
|
|
|
9
130
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
131
|
+
* The range of versions that satisfy both `a` and `b`.
|
|
132
|
+
*
|
|
133
|
+
* @param {string} name
|
|
134
|
+
* @param {string} a
|
|
135
|
+
* @param {string} b
|
|
136
|
+
* @returns {string}
|
|
12
137
|
*/
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
138
|
+
function intersectRanges(name, a, b) {
|
|
139
|
+
if (!semver.validRange(a) || !semver.validRange(b)) {
|
|
140
|
+
return a;
|
|
141
|
+
}
|
|
142
|
+
const setsOf = (/** @type {string} */ range) =>
|
|
143
|
+
new semver.Range(range).set.map((comparators) => comparators.map(String).join(' '));
|
|
144
|
+
const intersection = setsOf(a)
|
|
145
|
+
.flatMap((setA) => setsOf(b).map((setB) => `${setA} ${setB}`.trim()))
|
|
146
|
+
.filter((range) => semver.intersects(range, range));
|
|
147
|
+
if (intersection.length === 0) {
|
|
148
|
+
throw new Error(`No version of "${name}" satisfies every peer range: "${a}" and "${b}".`);
|
|
149
|
+
}
|
|
150
|
+
return intersection.join(' || ');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Parses the errors in `tsc --pretty false` output that point at a file.
|
|
155
|
+
*
|
|
156
|
+
* @param {string} output
|
|
157
|
+
* @returns {TypeScriptError[]}
|
|
158
|
+
*/
|
|
159
|
+
function parseTypeScriptErrors(output) {
|
|
160
|
+
/** @type {TypeScriptError[]} */
|
|
161
|
+
const errors = [];
|
|
162
|
+
for (const line of output.split(/\r?\n/)) {
|
|
163
|
+
const match = /^(.+?)\(\d+,\d+\): error (TS\d+): (.*)$/.exec(line);
|
|
164
|
+
if (match) {
|
|
165
|
+
errors.push({ file: match[1], code: match[2], message: match[3] });
|
|
166
|
+
} else if (line.startsWith(' ') && errors.length > 0) {
|
|
167
|
+
errors[errors.length - 1].message += `\n${line}`;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return errors;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Keeps the errors in the packed packages and the generated entry files. Errors inside a packed
|
|
175
|
+
* package are reported relative to that package, so the output doesn't depend on the store layout.
|
|
176
|
+
*
|
|
177
|
+
* @param {TypeScriptError[]} errors
|
|
178
|
+
* @param {string[]} packageNames
|
|
179
|
+
* @param {string} tempDir Stripped from messages.
|
|
180
|
+
* @returns {TypeScriptError[]}
|
|
181
|
+
*/
|
|
182
|
+
function getOwnErrors(errors, packageNames, tempDir) {
|
|
183
|
+
return errors.flatMap((error) => {
|
|
184
|
+
const message = error.message.replaceAll(`${tempDir}/`, '');
|
|
185
|
+
const index = error.file.lastIndexOf('node_modules/');
|
|
186
|
+
if (index === -1) {
|
|
187
|
+
return [{ ...error, message }];
|
|
188
|
+
}
|
|
189
|
+
const modulePath = error.file.slice(index + 'node_modules/'.length);
|
|
190
|
+
const owner = packageNames.find((name) => modulePath.startsWith(`${name}/`));
|
|
191
|
+
// Errors in third-party declarations are not ours to fix.
|
|
192
|
+
return owner ? [{ ...error, file: modulePath, message }] : [];
|
|
21
193
|
});
|
|
194
|
+
}
|
|
22
195
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
{ concurrency: 20 },
|
|
32
|
-
)
|
|
33
|
-
).filter((file) => typeof file === 'string');
|
|
196
|
+
/**
|
|
197
|
+
* @param {string} tarball
|
|
198
|
+
* @returns {Promise<PackageJson>}
|
|
199
|
+
*/
|
|
200
|
+
async function readPackedManifest(tarball) {
|
|
201
|
+
const { stdout } = await $`tar -xzOf ${tarball} package/package.json`;
|
|
202
|
+
return JSON.parse(stdout);
|
|
203
|
+
}
|
|
34
204
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
205
|
+
/**
|
|
206
|
+
* Installs the packed public packages into a fresh project, the way a consumer would, and
|
|
207
|
+
* type-checks an import of every typed entry point with `skipLibCheck` off.
|
|
208
|
+
*
|
|
209
|
+
* @param {Object} options
|
|
210
|
+
* @param {string} options.workspaceRoot
|
|
211
|
+
* @param {string} options.tempDir An empty directory outside the workspace.
|
|
212
|
+
* @returns {Promise<{ errors: TypeScriptError[], entryPointCount: number, packageCount: number }>}
|
|
213
|
+
*/
|
|
214
|
+
async function validateBuiltTypes({ workspaceRoot, tempDir }) {
|
|
215
|
+
const packages = await getWorkspacePackages({ cwd: workspaceRoot, publicOnly: true });
|
|
216
|
+
if (packages.length === 0) {
|
|
217
|
+
throw new Error('No public packages found.');
|
|
218
|
+
}
|
|
219
|
+
const tarballDir = path.join(tempDir, 'tarballs');
|
|
220
|
+
const projectDir = path.join(tempDir, 'project');
|
|
221
|
+
await Promise.all([
|
|
222
|
+
fs.mkdir(tarballDir, { recursive: true }),
|
|
223
|
+
fs.mkdir(path.join(projectDir, 'checks'), { recursive: true }),
|
|
224
|
+
]);
|
|
225
|
+
|
|
226
|
+
// Packed like @mui/internal-benchmark's `packWorkspace`, so each tarball is what `pnpm publish`
|
|
227
|
+
// would upload.
|
|
228
|
+
const packed = await mapAsync(
|
|
229
|
+
packages,
|
|
230
|
+
async (pkg) => {
|
|
231
|
+
const tarball = path.join(tarballDir, `${toFileStem(pkg.name)}.tgz`);
|
|
232
|
+
await $({ cwd: pkg.path })`pnpm pack --out ${tarball}`;
|
|
233
|
+
return { tarball, manifest: await readPackedManifest(tarball), dir: pkg.path };
|
|
234
|
+
},
|
|
235
|
+
{ concurrency: os.availableParallelism() },
|
|
236
|
+
);
|
|
237
|
+
|
|
238
|
+
/** @type {Record<string, string>} */
|
|
239
|
+
const tarballs = Object.fromEntries(
|
|
240
|
+
packed.map(({ manifest, tarball }) => [manifest.name, `file:${tarball}`]),
|
|
241
|
+
);
|
|
242
|
+
const packageNames = Object.keys(tarballs);
|
|
243
|
+
// Consumers provide every peer, optional ones included, at a version in range of every package.
|
|
244
|
+
// The versions the workspace installed for its packages come first: they are fixed by the
|
|
245
|
+
// lockfile, so a new upstream release can't change the outcome until the workspace updates.
|
|
246
|
+
const declaredPeers = await Promise.all(
|
|
247
|
+
packed.flatMap(({ manifest, dir }) =>
|
|
248
|
+
Object.entries(manifest.peerDependencies ?? {})
|
|
249
|
+
.filter(([name, range]) => range && !tarballs[name])
|
|
250
|
+
.map(async ([name, range]) => {
|
|
251
|
+
const installed = await readPackageJson(path.join(dir, 'node_modules', name)).catch(
|
|
252
|
+
() => undefined,
|
|
253
|
+
);
|
|
254
|
+
return {
|
|
255
|
+
name,
|
|
256
|
+
range: /** @type {string} */ (range),
|
|
257
|
+
version: installed?.version,
|
|
258
|
+
// An aliased install, such as `typescript: npm:@typescript/typescript6@6.0.2`.
|
|
259
|
+
spec:
|
|
260
|
+
installed?.name === name
|
|
261
|
+
? installed.version
|
|
262
|
+
: `npm:${installed?.name}@${installed?.version}`,
|
|
263
|
+
};
|
|
264
|
+
}),
|
|
265
|
+
),
|
|
266
|
+
);
|
|
267
|
+
/** @type {Record<string, string>} */
|
|
268
|
+
const peerRanges = {};
|
|
269
|
+
for (const { name, range } of declaredPeers) {
|
|
270
|
+
peerRanges[name] = peerRanges[name] ? intersectRanges(name, peerRanges[name], range) : range;
|
|
271
|
+
}
|
|
272
|
+
/** @type {Record<string, string>} */
|
|
273
|
+
const peers = {};
|
|
274
|
+
for (const [name, range] of Object.entries(peerRanges)) {
|
|
275
|
+
peers[name] =
|
|
276
|
+
declaredPeers.find(
|
|
277
|
+
(peer) => peer.name === name && peer.version && semver.satisfies(peer.version, range),
|
|
278
|
+
)?.spec ?? range;
|
|
279
|
+
}
|
|
280
|
+
// Installed as in any project that uses Node packages, but not made ambient: a program only loads
|
|
281
|
+
// Node types when declarations reference them, so they don't reach sources that shouldn't see them.
|
|
282
|
+
peers['@types/node'] ??= await readPackageJson(
|
|
283
|
+
path.join(workspaceRoot, 'node_modules', '@types/node'),
|
|
284
|
+
).then(
|
|
285
|
+
(packageJson) => packageJson.version ?? '*',
|
|
286
|
+
() => '*',
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
// One program per package and consumer kind. A consumer is either ESM or CommonJS, and installs
|
|
290
|
+
// one package rather than all of them: a shared program would check the global augmentations of
|
|
291
|
+
// unrelated packages, and of a package's CommonJS and ESM declarations, against each other.
|
|
292
|
+
// CommonJS and bundler consumers only get a program of their own when they resolve other
|
|
293
|
+
// declarations than ESM consumers; on the same files, they find nothing an ESM program misses.
|
|
294
|
+
const checks = packed.flatMap(({ manifest }) => {
|
|
295
|
+
const stem = path.join('checks', toFileStem(/** @type {string} */ (manifest.name)));
|
|
296
|
+
const [esm, ...others] = CONSUMERS.map(({ kind, extension, conditions, ...options }) => ({
|
|
297
|
+
file: `${stem}.${kind}.${extension}`,
|
|
298
|
+
entryPoints: getTypedEntryPoints(manifest, conditions),
|
|
299
|
+
...options,
|
|
300
|
+
}));
|
|
301
|
+
return [
|
|
302
|
+
esm,
|
|
303
|
+
...others.filter(({ entryPoints }) => !isEqual(entryPoints, esm.entryPoints)),
|
|
304
|
+
].filter(({ entryPoints }) => entryPoints.size > 0);
|
|
305
|
+
});
|
|
306
|
+
const entryPointCount = new Set(
|
|
307
|
+
checks.flatMap(({ entryPoints }) => Array.from(entryPoints.keys())),
|
|
308
|
+
).size;
|
|
309
|
+
if (entryPointCount === 0) {
|
|
310
|
+
throw new Error(
|
|
311
|
+
`No entry points with types found in ${packed.length} packages. Build the packages first.`,
|
|
312
|
+
);
|
|
39
313
|
}
|
|
40
314
|
|
|
41
|
-
|
|
315
|
+
await writePackageJson(projectDir, { private: true, dependencies: { ...peers, ...tarballs } });
|
|
316
|
+
// Every package and peer is a dependency of the project, so a package that looked them up from
|
|
317
|
+
// the project's node_modules would resolve what it never declared. With hoisting off and the
|
|
318
|
+
// virtual store outside the project, it only finds the dependencies pnpm linked for it.
|
|
319
|
+
await fs.writeFile(
|
|
320
|
+
path.join(projectDir, 'pnpm-workspace.yaml'),
|
|
321
|
+
stringify({
|
|
322
|
+
virtualStoreDir: '../virtual-store',
|
|
323
|
+
enableGlobalVirtualStore: false,
|
|
324
|
+
hoistPattern: [],
|
|
325
|
+
publicHoistPattern: [],
|
|
326
|
+
autoInstallPeers: false,
|
|
327
|
+
strictPeerDependencies: false,
|
|
328
|
+
blockExoticSubdeps: false,
|
|
329
|
+
ignoreScripts: true,
|
|
330
|
+
overrides: tarballs,
|
|
331
|
+
}),
|
|
332
|
+
);
|
|
333
|
+
await $({ cwd: projectDir })`pnpm install --lockfile=false --prefer-offline`;
|
|
334
|
+
|
|
335
|
+
const compilerOptions = {
|
|
336
|
+
strict: true,
|
|
337
|
+
skipLibCheck: false,
|
|
338
|
+
noEmit: true,
|
|
339
|
+
types: [],
|
|
340
|
+
lib: ['esnext', 'dom', 'dom.iterable'],
|
|
341
|
+
jsx: 'react-jsx',
|
|
342
|
+
};
|
|
343
|
+
const { native, js } = await findTscPair(workspaceRoot);
|
|
344
|
+
const tsc = native ?? js;
|
|
345
|
+
const realTempDir = await fs.realpath(tempDir);
|
|
346
|
+
const ownErrors = await mapAsync(
|
|
347
|
+
checks,
|
|
348
|
+
async ({ file, entryPoints, module, moduleResolution }) => {
|
|
349
|
+
const tsconfigFile = `${file}.json`;
|
|
350
|
+
await Promise.all([
|
|
351
|
+
fs.writeFile(path.join(projectDir, file), createEntryFile(entryPoints)),
|
|
352
|
+
fs.writeFile(
|
|
353
|
+
path.join(projectDir, tsconfigFile),
|
|
354
|
+
`${JSON.stringify({ compilerOptions: { ...compilerOptions, module, moduleResolution }, files: [path.basename(file)] }, null, 2)}\n`,
|
|
355
|
+
),
|
|
356
|
+
]);
|
|
357
|
+
const result = await $({
|
|
358
|
+
cwd: projectDir,
|
|
359
|
+
reject: false,
|
|
360
|
+
})`${tsc} -p ${tsconfigFile} --pretty false`;
|
|
361
|
+
const fileErrors = parseTypeScriptErrors(result.stdout);
|
|
362
|
+
// Errors in third-party declarations also fail tsc, but a failure without any error in a
|
|
363
|
+
// file means tsc didn't check the program at all.
|
|
364
|
+
if (result.failed && fileErrors.length === 0) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
`TypeScript failed to check ${tsconfigFile}:\n${result.stdout || result.stderr || result.message}`,
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
return getOwnErrors(fileErrors, packageNames, realTempDir);
|
|
370
|
+
},
|
|
371
|
+
// Native tsc checks on several threads of its own and takes hundreds of MB per program.
|
|
372
|
+
{
|
|
373
|
+
concurrency: native
|
|
374
|
+
? Math.max(1, Math.floor(os.availableParallelism() / 4))
|
|
375
|
+
: os.availableParallelism(),
|
|
376
|
+
},
|
|
377
|
+
);
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
errors: uniqBy(ownErrors.flat(), (error) => `${error.file}\0${error.code}\0${error.message}`),
|
|
381
|
+
entryPointCount,
|
|
382
|
+
packageCount: packed.length,
|
|
383
|
+
};
|
|
42
384
|
}
|
|
43
385
|
|
|
44
|
-
|
|
386
|
+
/**
|
|
387
|
+
* @typedef {Object} Args
|
|
388
|
+
* @property {boolean} keep
|
|
389
|
+
* @property {string[]} [expectError]
|
|
390
|
+
*/
|
|
391
|
+
|
|
392
|
+
export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
|
|
45
393
|
command: 'validate-built-types',
|
|
46
|
-
describe:
|
|
47
|
-
|
|
394
|
+
describe:
|
|
395
|
+
'Install the packed public packages into a fresh project and type-check every entry point that has types, as a consumer would. Run after building.',
|
|
396
|
+
builder: (yargs) =>
|
|
397
|
+
yargs
|
|
398
|
+
.option('keep', {
|
|
399
|
+
type: 'boolean',
|
|
400
|
+
default: false,
|
|
401
|
+
description: 'Keep the consumer project for inspection.',
|
|
402
|
+
})
|
|
403
|
+
.option('expect-error', {
|
|
404
|
+
type: 'string',
|
|
405
|
+
array: true,
|
|
406
|
+
default: [],
|
|
407
|
+
description:
|
|
408
|
+
'A path in a package, such as `@scope/pkg/subdir`, whose declarations are known to fail. Errors in files under it are not reported, and the check fails once there are none. Repeatable.',
|
|
409
|
+
}),
|
|
410
|
+
handler: async ({ keep, expectError = [] }) => {
|
|
411
|
+
const workspaceRoot = await findWorkspaceDir(process.cwd());
|
|
412
|
+
if (!workspaceRoot) {
|
|
413
|
+
throw new Error('Workspace directory not found');
|
|
414
|
+
}
|
|
415
|
+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'code-infra-built-types-'));
|
|
416
|
+
let failed = false;
|
|
417
|
+
try {
|
|
418
|
+
const { errors, entryPointCount, packageCount } = await validateBuiltTypes({
|
|
419
|
+
workspaceRoot,
|
|
420
|
+
tempDir,
|
|
421
|
+
});
|
|
422
|
+
// Errors are matched by the file they are in rather than by entry point: declarations can
|
|
423
|
+
// fail only next to another entry point's, such as conflicting module augmentations.
|
|
424
|
+
const expectedPaths = expectError.map((expected) => expected.replace(/\/+$/, ''));
|
|
425
|
+
const isUnder = (/** @type {string} */ file, /** @type {string} */ prefix) =>
|
|
426
|
+
file === prefix || file.startsWith(`${prefix}/`);
|
|
427
|
+
const unexpectedErrors = errors.filter(
|
|
428
|
+
(error) => !expectedPaths.some((prefix) => isUnder(error.file, prefix)),
|
|
429
|
+
);
|
|
430
|
+
for (const expected of expectedPaths) {
|
|
431
|
+
const count = errors.filter((error) => isUnder(error.file, expected)).length;
|
|
432
|
+
if (count > 0) {
|
|
433
|
+
console.log(`Ignoring ${count} expected type errors in ${expected}.`);
|
|
434
|
+
} else {
|
|
435
|
+
failed = true;
|
|
436
|
+
console.error(`❌ No type errors in ${expected}: remove it from --expect-error.`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (unexpectedErrors.length > 0) {
|
|
440
|
+
failed = true;
|
|
441
|
+
console.error(
|
|
442
|
+
`❌ Found ${unexpectedErrors.length} type errors in ${entryPointCount} entry points of ${packageCount} packages.\n`,
|
|
443
|
+
);
|
|
444
|
+
for (const error of unexpectedErrors) {
|
|
445
|
+
console.error(`${error.file}: ${error.code} ${error.message}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (failed) {
|
|
449
|
+
process.exitCode = 1;
|
|
450
|
+
} else {
|
|
451
|
+
console.log(
|
|
452
|
+
`✅ ${entryPointCount} entry points of ${packageCount} packages type-check for consumers.`,
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
} finally {
|
|
456
|
+
if (keep || failed) {
|
|
457
|
+
console.error(`\nConsumer project: ${path.join(tempDir, 'project')}`);
|
|
458
|
+
} else {
|
|
459
|
+
await fs.rm(tempDir, { recursive: true, force: true });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
},
|
|
48
463
|
});
|
package/src/cli/index.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { hideBin } from 'yargs/helpers';
|
|
|
6
6
|
import cmdArgosPush from './cmdArgosPush.mjs';
|
|
7
7
|
import cmdBaseline from './cmdBaseline.mjs';
|
|
8
8
|
import cmdBuild from './cmdBuild.mjs';
|
|
9
|
+
import cmdBuildNew from './cmdBuildNew.mjs';
|
|
9
10
|
import cmdCopyFiles from './cmdCopyFiles.mjs';
|
|
10
11
|
import cmdExtractErrorCodes from './cmdExtractErrorCodes.mjs';
|
|
11
12
|
import cmdGenerateChangelog from './cmdGenerateChangelog.mjs';
|
|
@@ -41,6 +42,7 @@ await yargs(hideBin(process.argv))
|
|
|
41
42
|
.command(cmdArgosPush)
|
|
42
43
|
.command(cmdBaseline)
|
|
43
44
|
.command(cmdBuild)
|
|
45
|
+
.command(cmdBuildNew)
|
|
44
46
|
.command(cmdCopyFiles)
|
|
45
47
|
.command(cmdExtractErrorCodes)
|
|
46
48
|
.command(cmdGenerateChangelog)
|
package/src/utils/build.mjs
CHANGED
|
@@ -794,6 +794,53 @@ export async function createPackageBin(bin, { bundles, cwd, packageType }) {
|
|
|
794
794
|
return newBin;
|
|
795
795
|
}
|
|
796
796
|
|
|
797
|
+
/**
|
|
798
|
+
* @param {unknown} value
|
|
799
|
+
* @returns {string[]}
|
|
800
|
+
*/
|
|
801
|
+
function getLeaves(value) {
|
|
802
|
+
if (typeof value === 'string') {
|
|
803
|
+
return [value];
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
if (!value || typeof value !== 'object') {
|
|
807
|
+
return [];
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
return Object.values(value).flatMap(getLeaves);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* The JS/TS sources the package's `exports`, `imports` and `bin` point at, relative to `cwd`.
|
|
815
|
+
* Glob patterns are expanded against the files on disk, as in the published `package.json`.
|
|
816
|
+
* @param {import('../cli/packageJson').PackageJson} packageJson
|
|
817
|
+
* @param {string} cwd
|
|
818
|
+
* @returns {Promise<string[]>}
|
|
819
|
+
*/
|
|
820
|
+
export async function getPackageSources({ exports, imports, bin }, cwd) {
|
|
821
|
+
const maps = await Promise.all(
|
|
822
|
+
[
|
|
823
|
+
typeof exports === 'string' || Array.isArray(exports) ? { '.': exports } : exports,
|
|
824
|
+
imports,
|
|
825
|
+
].map((map) =>
|
|
826
|
+
expandExportGlobs(
|
|
827
|
+
/** @type {import('../cli/packageJson').PackageJson.ExportConditions} */ (map ?? {}),
|
|
828
|
+
cwd,
|
|
829
|
+
),
|
|
830
|
+
),
|
|
831
|
+
);
|
|
832
|
+
|
|
833
|
+
return [...new Set(getLeaves([...maps, bin]))].flatMap((leaf) => {
|
|
834
|
+
const rel = srcRelative(leaf);
|
|
835
|
+
|
|
836
|
+
if (rel === null || rel.includes('*') || !JS_TS_EXTENSIONS.has(path.extname(rel))) {
|
|
837
|
+
return [];
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
return [path.posix.join('src', rel)];
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
|
|
797
844
|
/**
|
|
798
845
|
* Validates the package.json before building.
|
|
799
846
|
* @param {Record<string, any>} packageJson
|
|
@@ -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
|
+
}
|
package/src/utils/testUtils.mjs
CHANGED
|
@@ -19,6 +19,24 @@ export async function makeTempDir() {
|
|
|
19
19
|
return tmpDir;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Creates a temporary directory (see {@link makeTempDir}) containing `files`.
|
|
24
|
+
*
|
|
25
|
+
* @param {Record<string, string>} files - File contents keyed by path relative to the directory.
|
|
26
|
+
* @returns {Promise<string>} The path of the created temporary directory.
|
|
27
|
+
*/
|
|
28
|
+
export async function makeTempFiles(files) {
|
|
29
|
+
const tmpDir = await makeTempDir();
|
|
30
|
+
await Promise.all(
|
|
31
|
+
Object.entries(files).map(async ([name, contents]) => {
|
|
32
|
+
const file = path.join(tmpDir, name);
|
|
33
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
34
|
+
await fs.writeFile(file, contents);
|
|
35
|
+
}),
|
|
36
|
+
);
|
|
37
|
+
return tmpDir;
|
|
38
|
+
}
|
|
39
|
+
|
|
22
40
|
/**
|
|
23
41
|
* Write a package.json into a subdirectory of a temp workspace.
|
|
24
42
|
*
|
package/src/utils/typescript.mjs
CHANGED
|
@@ -37,7 +37,7 @@ async function findBin(dir, name) {
|
|
|
37
37
|
* @param {string} cwd
|
|
38
38
|
* @returns {Promise<{ native: string | null, js: string }>}
|
|
39
39
|
*/
|
|
40
|
-
async function findTscPair(cwd) {
|
|
40
|
+
export async function findTscPair(cwd) {
|
|
41
41
|
const workspaceDir = await findWorkspaceDir(cwd);
|
|
42
42
|
if (!workspaceDir) {
|
|
43
43
|
return { native: null, js: 'tsc' };
|