@mui/internal-code-infra 0.1.1-canary.3 → 0.1.1-canary.31

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 (47) hide show
  1. package/README.md +7 -4
  2. package/build/brokenLinksChecker/__fixtures__/no-signal-forwarding.d.mts +1 -0
  3. package/build/changelog/fetchChangelogs.d.mts +9 -10
  4. package/build/changelog/index.d.mts +1 -0
  5. package/build/cli/cmdBaseline.d.mts +18 -0
  6. package/build/cli/cmdBuild.d.mts +4 -0
  7. package/build/cli/cmdNetlifyIgnore.d.mts +1 -1
  8. package/build/eslint/index.d.mts +1 -0
  9. package/build/eslint/mui/rules/no-constructor-assigned-field.d.mts +50 -0
  10. package/build/eslint/nodeSupportConfig.d.mts +11 -0
  11. package/build/eslint/packageJsonConfig.d.mts +7 -0
  12. package/build/remark/config.d.mts +5 -14
  13. package/build/utils/build.d.mts +14 -0
  14. package/build/utils/credentials.d.mts +2 -2
  15. package/build/utils/git.d.mts +30 -9
  16. package/build/utils/github.d.mts +8 -0
  17. package/build/utils/pnpm.d.mts +67 -3
  18. package/package.json +54 -44
  19. package/src/brokenLinksChecker/index.mjs +8 -1
  20. package/src/changelog/fetchChangelogs.mjs +66 -26
  21. package/src/changelog/index.mjs +3 -0
  22. package/src/cli/cmdBaseline.mjs +31 -0
  23. package/src/cli/cmdBuild.mjs +47 -0
  24. package/src/cli/cmdNetlifyIgnore.mjs +14 -7
  25. package/src/cli/cmdPublish.mjs +17 -3
  26. package/src/cli/cmdPublishNewPackage.mjs +11 -4
  27. package/src/cli/index.mjs +2 -0
  28. package/src/eslint/baseConfig.mjs +8 -0
  29. package/src/eslint/docsConfig.mjs +28 -10
  30. package/src/eslint/index.mjs +1 -0
  31. package/src/eslint/jsonConfig.mjs +2 -1
  32. package/src/eslint/mui/config.mjs +16 -1
  33. package/src/eslint/mui/index.mjs +2 -0
  34. package/src/eslint/mui/rules/disallow-react-api-in-server-components.mjs +4 -1
  35. package/src/eslint/mui/rules/no-constructor-assigned-field.mjs +183 -0
  36. package/src/eslint/nodeSupportConfig.mjs +70 -0
  37. package/src/eslint/packageJsonConfig.mjs +50 -0
  38. package/src/eslint/testConfig.mjs +4 -2
  39. package/src/remark/config.mjs +60 -13
  40. package/src/utils/build.mjs +34 -0
  41. package/src/utils/credentials.mjs +4 -3
  42. package/src/utils/extractErrorCodes.mjs +1 -3
  43. package/src/utils/git.mjs +107 -46
  44. package/src/utils/github.mjs +27 -0
  45. package/src/utils/pnpm.mjs +126 -25
  46. package/vale/styles/MUI/GoogleLatin.yml +5 -2
  47. package/vale/styles/MUI/CorrectRererenceCased.yml +0 -14
@@ -1,9 +1,25 @@
1
+ import { retry } from '@octokit/plugin-retry';
2
+ import { throttling } from '@octokit/plugin-throttling';
1
3
  import { Octokit } from '@octokit/rest';
2
- import { $ } from 'execa';
4
+ import { mapAsync } from 'es-toolkit/array';
3
5
 
4
- import { getRepositoryInfo } from '../utils/git.mjs';
5
6
  import { persistentAuthStrategy } from '../utils/github.mjs';
6
7
 
8
+ const ThrottledOctokit = Octokit.plugin(throttling, retry);
9
+
10
+ /**
11
+ * Waits out short rate limits. Longer ones fail with the original error.
12
+ *
13
+ * @param {number} retryAfter - Seconds until the request may be retried
14
+ * @param {unknown} options
15
+ * @param {unknown} octokit
16
+ * @param {number} retryCount
17
+ * @returns {boolean}
18
+ */
19
+ function shouldRetryRateLimit(retryAfter, options, octokit, retryCount) {
20
+ return retryAfter <= 60 && retryCount < 3;
21
+ }
22
+
7
23
  /**
8
24
  * @typedef {import('@octokit/rest').Octokit} OctokitType
9
25
  */
@@ -18,27 +34,9 @@ import { persistentAuthStrategy } from '../utils/github.mjs';
18
34
  * @property {string} lastRelease
19
35
  * @property {string} release
20
36
  * @property {string} [org='mui'] - GitHub organization name, defaults to 'mui'
37
+ * @property {(progress: { phase: string; count: number; total: number }) => void} [onProgress] - Called as commits are listed and their pull request details are fetched
21
38
  */
22
39
 
23
- /**
24
- * @param {Object} opts
25
- * @param {string} opts.cwd
26
- * @param {boolean} [opts.fetchAll=true] Whether to fetch all tags from all remotes before finding the latest tag.
27
- * @returns {Promise<string>}
28
- */
29
- export async function findLatestTaggedVersion(opts) {
30
- const $$ = $({ cwd: opts.cwd });
31
- const fetchAll = opts.fetchAll ?? true;
32
- if (fetchAll) {
33
- const { remoteName } = await getRepositoryInfo();
34
- // Fetch all tags from the mui remote to ensure we have the latest tags.
35
- // --force to update any existing tags that may have changed to avoid the clobering error.
36
- await $$`git fetch --tags --force ${remoteName}`;
37
- }
38
- const { stdout } = await $$`git describe --tags --abbrev=0 --match ${'v*'}`; // only include "version-tags"
39
- return stdout.trim();
40
- }
41
-
42
40
  /**
43
41
  * Fetches commits between two refs (lastRelease..release) including PR details.
44
42
  * Automatically handles GitHub OAuth authentication if none provided.
@@ -50,7 +48,13 @@ export async function fetchCommitsBetweenRefs(opts) {
50
48
  const octokit =
51
49
  'octokit' in opts && opts.octokit
52
50
  ? opts.octokit
53
- : new Octokit({ authStrategy: persistentAuthStrategy });
51
+ : new ThrottledOctokit({
52
+ authStrategy: persistentAuthStrategy,
53
+ throttle: {
54
+ onRateLimit: shouldRetryRateLimit,
55
+ onSecondaryRateLimit: shouldRetryRateLimit,
56
+ },
57
+ });
54
58
 
55
59
  return fetchCommitsRest({
56
60
  octokit,
@@ -58,6 +62,7 @@ export async function fetchCommitsBetweenRefs(opts) {
58
62
  lastRelease: opts.lastRelease,
59
63
  release: opts.release,
60
64
  org: opts.org ?? 'mui',
65
+ onProgress: opts.onProgress,
61
66
  });
62
67
  }
63
68
 
@@ -70,7 +75,7 @@ export async function fetchCommitsBetweenRefs(opts) {
70
75
  *
71
76
  * @returns {Promise<FetchedCommitDetails[]>}
72
77
  */
73
- async function fetchCommitsRest({ octokit, repo, lastRelease, release, org = 'mui' }) {
78
+ async function fetchCommitsRest({ octokit, repo, lastRelease, release, org = 'mui', onProgress }) {
74
79
  /**
75
80
  * @typedef {Awaited<ReturnType<Octokit['repos']['compareCommits']>>['data']['commits']} Commits
76
81
  */
@@ -90,9 +95,19 @@ async function fetchCommitsRest({ octokit, repo, lastRelease, release, org = 'mu
90
95
  );
91
96
  for await (const response of timeline) {
92
97
  results.push(...response.data.commits);
98
+ onProgress?.({
99
+ phase: 'Listing commits',
100
+ count: results.length,
101
+ total: response.data.total_commits,
102
+ });
93
103
  }
94
104
 
95
- const promises = results.map(async (commit) => {
105
+ /**
106
+ * @param {Commits[number]} commit
107
+ * @param {AbortSignal} signal
108
+ * @returns {Promise<FetchedCommitDetails | null>}
109
+ */
110
+ const fetchCommitDetails = async (commit, signal) => {
96
111
  const matches = [...commit.commit.message.matchAll(/#(\d+)/g)];
97
112
  // The PR number is always the last match.
98
113
  // Sometimes the PR titles include an issue number like this:
@@ -111,6 +126,7 @@ async function fetchCommitsRest({ octokit, repo, lastRelease, release, org = 'mu
111
126
  headers: {
112
127
  Accept: 'application/vnd.github.text+json',
113
128
  },
129
+ request: { signal },
114
130
  });
115
131
 
116
132
  const labels = pr.data.labels.map((label) => label.name);
@@ -132,9 +148,33 @@ async function fetchCommitsRest({ octokit, repo, lastRelease, release, org = 'mu
132
148
  prTitle: pr.data.title,
133
149
  prBody: pr.data.body,
134
150
  });
135
- });
151
+ };
152
+
153
+ // `mapAsync` rejects on the first error but still runs every queued callback.
154
+ // Aborted once it settles, which cancels requests in flight and skips the ones not started yet.
155
+ const controller = new AbortController();
136
156
 
137
- return (await Promise.all(promises)).filter((entry) => entry !== null);
157
+ let fetched = 0;
158
+ try {
159
+ const commits = await mapAsync(
160
+ results,
161
+ async (commit) => {
162
+ if (controller.signal.aborted) {
163
+ return null;
164
+ }
165
+ const details = await fetchCommitDetails(commit, controller.signal);
166
+ if (!controller.signal.aborted) {
167
+ fetched += 1;
168
+ onProgress?.({ phase: 'Fetching pull requests', count: fetched, total: results.length });
169
+ }
170
+ return details;
171
+ },
172
+ { concurrency: 10 },
173
+ );
174
+ return commits.filter((entry) => entry !== null);
175
+ } finally {
176
+ controller.abort();
177
+ }
138
178
  }
139
179
 
140
180
  /**
@@ -5,3 +5,6 @@
5
5
  export { generateChangelog } from './generateChangelog.mjs';
6
6
  export * from './loadChangelogConfig.mjs';
7
7
  export * from './fetchChangelogs.mjs';
8
+ // Moved to the git utilities, where the rest of the local git plumbing lives. Re-exported because
9
+ // `@mui/internal-code-infra/changelog` is a published entry point and this was part of it.
10
+ export { findLatestTaggedVersion } from '../utils/git.mjs';
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+
3
+ /* eslint-disable no-console */
4
+
5
+ import { resolveBaseline } from '../utils/git.mjs';
6
+
7
+ /**
8
+ * @typedef {Object} Args
9
+ * @property {string} [baseBranch] - Branch pull requests fork from
10
+ * @property {string} [remote] - Remote the base branch is fetched from
11
+ */
12
+
13
+ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
14
+ command: 'baseline',
15
+ describe: 'Print the commit HEAD should be compared against',
16
+ builder: (yargs) => {
17
+ return yargs
18
+ .option('base-branch', {
19
+ type: 'string',
20
+ description: "Branch pull requests fork from. Default: the remote's default branch",
21
+ })
22
+ .option('remote', {
23
+ type: 'string',
24
+ description:
25
+ 'Remote the base branch is fetched from. Default: upstream, else origin, whichever points at a mui repository',
26
+ });
27
+ },
28
+ handler: async (argv) => {
29
+ console.log(await resolveBaseline({ baseBranch: argv.baseBranch, remote: argv.remote }));
30
+ },
31
+ });
@@ -12,6 +12,7 @@ import {
12
12
  createPackageExports,
13
13
  createPackageImports,
14
14
  getOutExtension,
15
+ validateEnginesNode,
15
16
  validatePkgJson,
16
17
  } from '../utils/build.mjs';
17
18
  import { readPnpmConfig } from '../utils/pnpm.mjs';
@@ -27,6 +28,7 @@ import { readPnpmConfig } from '../utils/pnpm.mjs';
27
28
  * @property {boolean} skipBabelRuntimeCheck - Whether to skip checking for Babel runtime dependencies in the package.
28
29
  * @property {boolean} skipPackageJson - Whether to skip generating the package.json file in the bundle output.
29
30
  * @property {boolean} skipMainCheck - Whether to skip checking for main field in package.json.
31
+ * @property {boolean} skipPublint - Whether to skip validating the output directory with publint.
30
32
  * @property {string[]} ignore - Globs to be ignored by Babel.
31
33
  * @property {string[]} [copy] - Files/Directories to be copied. Can be a glob pattern.
32
34
  * @property {boolean} [enableReactCompiler] - Whether to use the React compiler.
@@ -215,6 +217,11 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
215
217
  default: false,
216
218
  description: 'Skip checking for main field in package.json.',
217
219
  })
220
+ .option('skipPublint', {
221
+ type: 'boolean',
222
+ default: false,
223
+ description: 'Skip validating the output directory with publint.',
224
+ })
218
225
  .option('copy', {
219
226
  type: 'string',
220
227
  array: true,
@@ -266,6 +273,7 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
266
273
  const pkgJsonPath = path.join(cwd, 'package.json');
267
274
  const packageJson = JSON.parse(await fs.readFile(pkgJsonPath, { encoding: 'utf8' }));
268
275
  validatePkgJson(packageJson, { skipMainCheck: args.skipMainCheck, enableReactCompiler });
276
+ validateEnginesNode(packageJson, cwd);
269
277
 
270
278
  const buildDirBase = /** @type {string} */ (packageJson.publishConfig?.directory);
271
279
  const buildDir = path.join(cwd, buildDirBase);
@@ -390,9 +398,48 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
390
398
  buildDir,
391
399
  verbose: args.verbose,
392
400
  });
401
+
402
+ if (!args.skipPublint) {
403
+ await validateWithPublint(buildDir);
404
+ }
393
405
  },
394
406
  });
395
407
 
408
+ /**
409
+ * Lints the output directory with publint. Errors fail the build, warnings are only reported.
410
+ * @param {string} buildDir - The build directory to validate.
411
+ * @returns {Promise<void>}
412
+ */
413
+ async function validateWithPublint(buildDir) {
414
+ const [{ publint }, { formatMessage }] = await Promise.all([
415
+ import('publint'),
416
+ import('publint/utils'),
417
+ ]);
418
+ // Everything in the output directory is published, so there is nothing to pack.
419
+ const result = await publint({ pkgDir: buildDir, pack: false, level: 'warning' });
420
+ const { pkg } = result;
421
+ // TODO: remove this filter and bump publint to >=0.3.25, which ships the fix from
422
+ // https://github.com/publint/publint/pull/265 (publint checks `browser` values
423
+ // that point at another package as local files).
424
+ const messages = result.messages.filter((message) => {
425
+ if (message.code !== 'FILE_DOES_NOT_EXIST' || message.path[0] !== 'browser') {
426
+ return true;
427
+ }
428
+ const value = message.path.length === 2 ? pkg.browser?.[message.path[1]] : undefined;
429
+ return typeof value !== 'string' || value.startsWith('.');
430
+ });
431
+
432
+ for (const message of messages) {
433
+ const log = message.type === 'error' ? console.error : console.warn;
434
+ log(`publint ${message.type}: ${formatMessage(message, pkg)}`);
435
+ }
436
+
437
+ const errorCount = messages.filter((message) => message.type === 'error').length;
438
+ if (errorCount > 0) {
439
+ throw new Error(`publint found ${errorCount} error(s) in "${buildDir}".`);
440
+ }
441
+ }
442
+
396
443
  /**
397
444
  * @param {Object} param0
398
445
  * @param {string} param0.cwd - The current working directory.
@@ -4,7 +4,7 @@
4
4
 
5
5
  /**
6
6
  * @typedef {Object} Args
7
- * @property {string[]} workspaces - List of workspace names to process
7
+ * @property {string[]} workspaces - Workspace names or root-relative paths to process
8
8
  * @property {boolean} [check] - Check mode - error if the generated content differs from current
9
9
  * @property {string} [baseBranch] - Branch to compare PRs against (default: master)
10
10
  */
@@ -100,7 +100,7 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
100
100
  .positional('workspaces', {
101
101
  type: 'string',
102
102
  array: true,
103
- describe: 'List of workspace names to process',
103
+ describe: 'Workspace names or root-relative paths to process',
104
104
  demandOption: true,
105
105
  })
106
106
  .option('check', {
@@ -115,6 +115,7 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
115
115
  "Branch to compare PRs against (the site's production branch on Netlify). Production and branch deploys always rebuild regardless of this value.",
116
116
  })
117
117
  .example('$0 netlify-ignore @mui/internal-docs-infra', 'Update netlify.toml for a workspace')
118
+ .example('$0 netlify-ignore ./apps/dashboard', 'Update an unnamed workspace by path')
118
119
  .example(
119
120
  '$0 netlify-ignore @mui/internal-docs-infra @mui/internal-code-infra',
120
121
  'Update netlify.toml for multiple workspaces',
@@ -135,11 +136,17 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
135
136
 
136
137
  // Get all workspace packages and create workspace map
137
138
  const allWorkspaces = await getWorkspacePackages({ cwd: workspaceRoot });
138
- const workspaceMap = new Map(
139
- allWorkspaces.flatMap((workspace) =>
140
- workspace.name ? [[workspace.name, workspace.path]] : [],
141
- ),
142
- );
139
+ /** @type {Map<string, string>} */
140
+ const workspaceMap = new Map();
141
+ for (const workspace of allWorkspaces) {
142
+ if (workspace.name) {
143
+ workspaceMap.set(workspace.name, workspace.path);
144
+ }
145
+
146
+ // Paths also identify private workspaces that have no package name.
147
+ const relativePath = toPosixPath(path.relative(workspaceRoot, workspace.path));
148
+ workspaceMap.set(`./${relativePath}`, workspace.path);
149
+ }
143
150
 
144
151
  // Process each workspace concurrently
145
152
  await Promise.all(
@@ -19,7 +19,9 @@ import * as semver from 'semver';
19
19
 
20
20
  import { persistentAuthStrategy } from '../utils/github.mjs';
21
21
  import {
22
+ getDistTagConflicts,
22
23
  getPackagesNeedingManualPublish,
24
+ getRegistryPackages,
23
25
  getReleaseVersion,
24
26
  getWorkspacePackages,
25
27
  publishPackages,
@@ -364,7 +366,8 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
364
366
  githubReleaseData = await validateGitHubRelease(version);
365
367
  }
366
368
 
367
- const newPackages = await getPackagesNeedingManualPublish(filteredPackages);
369
+ const registryPackages = await getRegistryPackages(filteredPackages);
370
+ const newPackages = getPackagesNeedingManualPublish(filteredPackages, registryPackages);
368
371
 
369
372
  if (newPackages.length > 0) {
370
373
  const newPackageNames = newPackages.map((pkg) => pkg.name).join(', ');
@@ -373,6 +376,15 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
373
376
  );
374
377
  }
375
378
 
379
+ const distTagConflicts = getDistTagConflicts(filteredPackages, tag, registryPackages);
380
+ if (distTagConflicts.length > 0) {
381
+ throw new Error(
382
+ `Publishing with the "${tag}" dist-tag would move it to the wrong release line:
383
+ ${distTagConflicts.map(({ pkg, reason }) => ` * ${pkg.name}: ${reason}`).join('\n')}
384
+ Publish a previous major with its "latest-vX" dist-tag and a prerelease of the next major with "next". On a release branch, also make that dist-tag the "dist-tag" default of the publish workflow. If the dist-tag on npm is outdated, fix it with "npm dist-tag" first.`,
385
+ );
386
+ }
387
+
376
388
  // Publish to npm (pnpm handles duplicate checking automatically)
377
389
  // No git checks, we'll do our own
378
390
  console.log('\n📦 Publishing packages to npm...');
@@ -426,8 +438,10 @@ const PUBLISH_WORKFLOW_ID = `.github/${WORKFLOW_PATH}`;
426
438
  */
427
439
  async function triggerLocalGithubPublishWorkflow(opts) {
428
440
  console.log(`🔍 Checking if there are new packages to publish in the workspace...`);
429
- const newPackages = await getPackagesNeedingManualPublish(
430
- await getWorkspacePackages({ publicOnly: true }),
441
+ const packages = await getWorkspacePackages({ publicOnly: true });
442
+ const newPackages = getPackagesNeedingManualPublish(
443
+ packages,
444
+ await getRegistryPackages(packages, { npmOnly: true }),
431
445
  );
432
446
  if (newPackages.length) {
433
447
  console.warn(
@@ -11,7 +11,12 @@ import { findWorkspaceDir } from '@pnpm/find-workspace-dir';
11
11
 
12
12
  import { getRepositoryInfo } from '../utils/git.mjs';
13
13
  import { toPosixPath } from '../utils/path.mjs';
14
- import { getPackagesNeedingManualPublish, getWorkspacePackages } from '../utils/pnpm.mjs';
14
+ import {
15
+ getPackagesNeedingManualPublish,
16
+ getRegistryPackages,
17
+ getWorkspacePackages,
18
+ PLACEHOLDER_VERSION,
19
+ } from '../utils/pnpm.mjs';
15
20
 
16
21
  /**
17
22
  * @typedef {Object} Args
@@ -46,8 +51,10 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
46
51
  }),
47
52
  async handler(args) {
48
53
  console.log(`🔍 Detecting new packages to publish in workspace...`);
49
- const newPackages = await getPackagesNeedingManualPublish(
50
- await getWorkspacePackages({ publicOnly: true }),
54
+ const packages = await getWorkspacePackages({ publicOnly: true });
55
+ const newPackages = getPackagesNeedingManualPublish(
56
+ packages,
57
+ await getRegistryPackages(packages, { npmOnly: true }),
51
58
  );
52
59
 
53
60
  if (!newPackages.length) {
@@ -78,7 +85,7 @@ export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({
78
85
  const repo = await getRepositoryInfo();
79
86
  const packageJson = {
80
87
  name: pkg.name,
81
- version: '0.0.1',
88
+ version: PLACEHOLDER_VERSION,
82
89
  repository: {
83
90
  type: 'git',
84
91
  url: `git+https://github.com/${repo.owner}/${repo.repo}.git`,
package/src/cli/index.mjs CHANGED
@@ -4,6 +4,7 @@ import yargs from 'yargs';
4
4
  import { hideBin } from 'yargs/helpers';
5
5
 
6
6
  import cmdArgosPush from './cmdArgosPush.mjs';
7
+ import cmdBaseline from './cmdBaseline.mjs';
7
8
  import cmdBuild from './cmdBuild.mjs';
8
9
  import cmdCopyFiles from './cmdCopyFiles.mjs';
9
10
  import cmdExtractErrorCodes from './cmdExtractErrorCodes.mjs';
@@ -38,6 +39,7 @@ await yargs(hideBin(process.argv))
38
39
  globalArgv = argv;
39
40
  }, true)
40
41
  .command(cmdArgosPush)
42
+ .command(cmdBaseline)
41
43
  .command(cmdBuild)
42
44
  .command(cmdCopyFiles)
43
45
  .command(cmdExtractErrorCodes)
@@ -3,6 +3,7 @@ import eslintJs from '@eslint/js';
3
3
  import { defineConfig } from 'eslint/config';
4
4
  import prettier from 'eslint-config-prettier/flat';
5
5
  import compatPlugin from 'eslint-plugin-compat';
6
+ import nPlugin from 'eslint-plugin-n';
6
7
  import importPlugin from 'eslint-plugin-import';
7
8
  import jsxA11yPlugin from 'eslint-plugin-jsx-a11y';
8
9
  import reactPlugin from 'eslint-plugin-react';
@@ -17,6 +18,8 @@ import { createCoreConfig } from './mui/config.mjs';
17
18
  import muiPlugin from './mui/index.mjs';
18
19
  import { EXTENSION_TS } from './extensions.mjs';
19
20
  import { createJsonConfig } from './jsonConfig.mjs';
21
+ import { createNodeSupportConfig } from './nodeSupportConfig.mjs';
22
+ import { createPackageJsonConfig } from './packageJsonConfig.mjs';
20
23
 
21
24
  /**
22
25
  * @param {string} filePath
@@ -58,6 +61,9 @@ export function createBaseConfig({
58
61
  },
59
62
  plugins: {
60
63
  mui: muiPlugin,
64
+ // Registered once for all files, so consumers can enable `n/*` rules without registering
65
+ // a second, possibly different, instance of the plugin.
66
+ n: nPlugin,
61
67
  },
62
68
  settings: {
63
69
  react: {
@@ -73,6 +79,8 @@ export function createBaseConfig({
73
79
  includeIgnoreIfExists(path.join(baseDirectory, '.gitignore'), `Ignore rules from .gitignore`),
74
80
  includeIgnoreIfExists(path.join(baseDirectory, '.lintignore'), `Ignore rules from .lintignore`),
75
81
  createJsonConfig(),
82
+ createNodeSupportConfig(baseDirectory),
83
+ createPackageJsonConfig(),
76
84
  prettier,
77
85
  // Markdown + MDX linting via eslint-plugin-mdx. Severities for markdown
78
86
  // quality checks live in the project's `.remarkrc` (see
@@ -19,17 +19,35 @@ export function createDocsConfig() {
19
19
  ? nextjsAlias.flatConfig.recommended
20
20
  : nextjsAlias.configs.recommended;
21
21
 
22
- return defineConfig(recommendedConfig, {
23
- settings: {
24
- next: {
25
- rootDir: 'docs',
22
+ return defineConfig(
23
+ recommendedConfig,
24
+ {
25
+ settings: {
26
+ next: {
27
+ rootDir: 'docs',
28
+ },
29
+ },
30
+ files: [`**/*${EXTENSION_TS}`],
31
+ rules: {
32
+ 'compat/compat': 'off',
33
+ 'jsx-a11y/anchor-is-valid': 'off',
34
+ 'no-irregular-whitespace': ['error', { skipJSXText: true, skipStrings: true }],
26
35
  },
27
36
  },
28
- files: [`**/*${EXTENSION_TS}`],
29
- rules: {
30
- 'compat/compat': 'off',
31
- 'jsx-a11y/anchor-is-valid': 'off',
32
- 'no-irregular-whitespace': ['error', { skipJSXText: true, skipStrings: true }],
37
+ {
38
+ // Build configuration and maintenance scripts aren't documentation examples
39
+ // and are often intentionally outside the docs TypeScript project.
40
+ files: [`**/*${EXTENSION_TS}`],
41
+ ignores: ['**/*.config.*', '**/scripts/**'],
42
+ languageOptions: {
43
+ parserOptions: {
44
+ projectService: true,
45
+ tsconfigRootDir: process.cwd(),
46
+ },
47
+ },
48
+ rules: {
49
+ '@typescript-eslint/no-deprecated': 'error',
50
+ },
33
51
  },
34
- });
52
+ );
35
53
  }
@@ -3,5 +3,6 @@
3
3
 
4
4
  export * from './baseConfig.mjs';
5
5
  export * from './docsConfig.mjs';
6
+ export * from './nodeSupportConfig.mjs';
6
7
  export * from './testConfig.mjs';
7
8
  export * from './extensions.mjs';
@@ -9,7 +9,8 @@ export function createJsonConfig() {
9
9
  {
10
10
  name: 'JSON files',
11
11
  files: ['**/*.json'],
12
- ignores: ['package-lock.json'],
12
+ // package.json is linted by eslint-plugin-package-json, whose rules need the jsonc-eslint-parser AST.
13
+ ignores: ['package-lock.json', '**/package.json'],
13
14
  plugins: { json },
14
15
  language: 'json/json',
15
16
  extends: [json.configs.recommended],
@@ -1,5 +1,5 @@
1
1
  import { defineConfig } from 'eslint/config';
2
- import { EXTENSION_DTS } from '../extensions.mjs';
2
+ import { EXTENSION_DTS, EXTENSION_TS_ONLY } from '../extensions.mjs';
3
3
 
4
4
  const restrictedMethods = ['setTimeout', 'setInterval', 'clearTimeout', 'clearInterval'];
5
5
 
@@ -184,6 +184,14 @@ const typescriptOverrides = {
184
184
  // TypeScript equivalents of ESLint rules
185
185
  'default-param-last': 'off',
186
186
  '@typescript-eslint/default-param-last': 'error',
187
+ '@typescript-eslint/ban-ts-comment': [
188
+ 'error',
189
+ {
190
+ 'ts-expect-error': 'allow-with-description',
191
+ 'ts-ignore': true,
192
+ minimumDescriptionLength: 10,
193
+ },
194
+ ],
187
195
  'no-array-constructor': 'off',
188
196
  '@typescript-eslint/no-array-constructor': 'error',
189
197
  '@typescript-eslint/triple-slash-reference': 'off',
@@ -538,6 +546,13 @@ export function createCoreConfig(options = {}) {
538
546
  '@typescript-eslint/return-await': 'off',
539
547
  },
540
548
  },
549
+ {
550
+ name: 'mui-base/ts',
551
+ files: [`**/*${EXTENSION_TS_ONLY}`],
552
+ rules: {
553
+ 'mui/no-constructor-assigned-field': 'error',
554
+ },
555
+ },
541
556
  {
542
557
  name: 'mui-base/dts',
543
558
  files: [`**/*${EXTENSION_DTS}`],
@@ -14,6 +14,7 @@ import addUndefToOptional from './rules/add-undef-to-optional.mjs';
14
14
  import flattenParentheses from './rules/flatten-parentheses.mjs';
15
15
  import noPresentationRole from './rules/no-presentation-role.mjs';
16
16
  import noFloatingCleanup from './rules/no-floating-cleanup.mjs';
17
+ import noConstructorAssignedField from './rules/no-constructor-assigned-field.mjs';
17
18
 
18
19
  /** @type {import('eslint').ESLint.Plugin} */
19
20
  const muiPlugin = {
@@ -39,6 +40,7 @@ const muiPlugin = {
39
40
  'flatten-parentheses': /** @type {any} */ (flattenParentheses),
40
41
  'no-presentation-role': noPresentationRole,
41
42
  'no-floating-cleanup': /** @type {any} */ (noFloatingCleanup),
43
+ 'no-constructor-assigned-field': /** @type {any} */ (noConstructorAssignedField),
42
44
  },
43
45
  };
44
46
 
@@ -47,7 +47,10 @@ export default /** @type {import('eslint').Rule.RuleModule} */ ({
47
47
  return null;
48
48
  }
49
49
 
50
- const firstToken = context.sourceCode.ast.body[0];
50
+ const firstToken = context.sourceCode.getFirstToken(context.sourceCode.ast);
51
+ if (!firstToken) {
52
+ return null;
53
+ }
51
54
  return fixer.insertTextBefore(firstToken, "'use client';\n");
52
55
  }
53
56