@mui/internal-code-infra 0.0.4-canary.10 → 0.0.4-canary.101

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 (145) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +21 -7
  3. package/build/babel-config.d.mts +5 -1
  4. package/build/brokenLinksChecker/crawlWorker.d.mts +1 -0
  5. package/build/brokenLinksChecker/index.d.mts +192 -2
  6. package/build/changelog/fetchChangelogs.d.mts +3 -0
  7. package/build/changelog/types.d.ts +3 -1
  8. package/build/cli/cmdArgosPush.d.mts +8 -2
  9. package/build/cli/cmdBuild.d.mts +48 -2
  10. package/build/cli/cmdCopyFiles.d.mts +14 -2
  11. package/build/cli/cmdExtractErrorCodes.d.mts +2 -2
  12. package/build/cli/cmdGenerateChangelog.d.mts +17 -2
  13. package/build/cli/cmdGithubAuth.d.mts +2 -2
  14. package/build/cli/cmdListWorkspaces.d.mts +14 -2
  15. package/build/cli/cmdNetlifyIgnore.d.mts +12 -2
  16. package/build/cli/cmdPublish.d.mts +23 -4
  17. package/build/cli/cmdPublishCanary.d.mts +20 -2
  18. package/build/cli/cmdPublishNewPackage.d.mts +10 -2
  19. package/build/cli/cmdRenameScope.d.mts +18 -0
  20. package/build/cli/cmdSetVersionOverrides.d.mts +5 -2
  21. package/build/cli/cmdVale.d.mts +46 -0
  22. package/build/cli/cmdValidateBuiltTypes.d.mts +2 -2
  23. package/build/eslint/baseConfig.d.mts +3 -1
  24. package/build/eslint/mui/rules/disallow-react-api-in-server-components.d.mts +2 -2
  25. package/build/eslint/mui/rules/docgen-ignore-before-comment.d.mts +2 -2
  26. package/build/eslint/mui/rules/no-floating-cleanup.d.mts +5 -0
  27. package/build/eslint/mui/rules/no-guarded-throw.d.mts +31 -0
  28. package/build/eslint/mui/rules/no-presentation-role.d.mts +5 -0
  29. package/build/eslint/mui/rules/no-restricted-resolved-imports.d.mts +8 -2
  30. package/build/eslint/mui/rules/nodeEnvUtils.d.mts +18 -0
  31. package/build/remark/config.d.mts +43 -0
  32. package/build/remark/createLintTester.d.mts +10 -0
  33. package/build/remark/firstBlockHeading.d.mts +4 -0
  34. package/build/remark/gitDiff.d.mts +2 -0
  35. package/build/remark/noSpaceInLinks.d.mts +2 -0
  36. package/build/remark/straightQuotes.d.mts +2 -0
  37. package/build/remark/tableAlignment.d.mts +2 -0
  38. package/build/remark/terminalLanguage.d.mts +2 -0
  39. package/build/utils/babel.d.mts +7 -1
  40. package/build/utils/build.d.mts +59 -37
  41. package/build/utils/extractErrorCodes.d.mts +9 -0
  42. package/build/utils/git.d.mts +16 -0
  43. package/build/utils/github.d.mts +13 -1
  44. package/build/utils/pnpm.d.mts +226 -20
  45. package/build/utils/testUtils.d.mts +28 -0
  46. package/build/utils/typescript.d.mts +6 -16
  47. package/package.json +79 -53
  48. package/src/babel-config.mjs +3 -1
  49. package/src/brokenLinksChecker/crawlWorker.mjs +240 -0
  50. package/src/brokenLinksChecker/index.mjs +263 -188
  51. package/src/changelog/fetchChangelogs.mjs +8 -2
  52. package/src/changelog/renderChangelog.mjs +1 -1
  53. package/src/changelog/types.ts +3 -1
  54. package/src/cli/cmdBuild.mjs +53 -88
  55. package/src/cli/cmdListWorkspaces.mjs +7 -1
  56. package/src/cli/cmdNetlifyIgnore.mjs +30 -5
  57. package/src/cli/cmdPublish.mjs +79 -37
  58. package/src/cli/cmdPublishCanary.mjs +96 -24
  59. package/src/cli/cmdPublishNewPackage.mjs +31 -8
  60. package/src/cli/cmdRenameScope.mjs +76 -0
  61. package/src/cli/cmdSetVersionOverrides.mjs +40 -34
  62. package/src/cli/cmdVale.mjs +513 -0
  63. package/src/cli/index.mjs +4 -0
  64. package/src/cli/packageJson.d.ts +2 -3
  65. package/src/eslint/baseConfig.mjs +51 -19
  66. package/src/eslint/docsConfig.mjs +2 -1
  67. package/src/eslint/mui/config.mjs +24 -4
  68. package/src/eslint/mui/index.mjs +6 -0
  69. package/src/eslint/mui/rules/no-floating-cleanup.mjs +187 -0
  70. package/src/eslint/mui/rules/no-guarded-throw.mjs +115 -0
  71. package/src/eslint/mui/rules/no-presentation-role.mjs +60 -0
  72. package/src/eslint/mui/rules/nodeEnvUtils.mjs +52 -0
  73. package/src/eslint/mui/rules/require-dev-wrapper.mjs +25 -40
  74. package/src/estree-typescript.d.ts +1 -1
  75. package/src/remark/config.mjs +157 -0
  76. package/src/remark/createLintTester.mjs +19 -0
  77. package/src/remark/firstBlockHeading.mjs +87 -0
  78. package/src/remark/gitDiff.mjs +43 -0
  79. package/src/remark/noSpaceInLinks.mjs +42 -0
  80. package/src/remark/straightQuotes.mjs +31 -0
  81. package/src/remark/tableAlignment.mjs +23 -0
  82. package/src/remark/terminalLanguage.mjs +19 -0
  83. package/src/stylelint/index.mjs +2 -2
  84. package/src/untyped-plugins.d.ts +14 -14
  85. package/src/utils/build.mjs +604 -270
  86. package/src/utils/git.mjs +27 -7
  87. package/src/utils/pnpm.mjs +636 -60
  88. package/src/utils/testUtils.mjs +53 -0
  89. package/src/utils/typescript.mjs +23 -42
  90. package/vale/.vale.ini +1 -0
  91. package/vale/styles/MUI/CorrectReferenceAllCases.yml +42 -0
  92. package/vale/styles/MUI/CorrectRererenceCased.yml +14 -0
  93. package/vale/styles/MUI/GoogleLatin.yml +11 -0
  94. package/vale/styles/MUI/MuiBrandName.yml +22 -0
  95. package/vale/styles/MUI/NoBritish.yml +112 -0
  96. package/vale/styles/MUI/NoCompanyName.yml +17 -0
  97. package/build/markdownlint/duplicate-h1.d.mts +0 -56
  98. package/build/markdownlint/git-diff.d.mts +0 -11
  99. package/build/markdownlint/index.d.mts +0 -52
  100. package/build/markdownlint/straight-quotes.d.mts +0 -11
  101. package/build/markdownlint/table-alignment.d.mts +0 -11
  102. package/build/markdownlint/terminal-language.d.mts +0 -11
  103. package/src/brokenLinksChecker/__fixtures__/static-site/broken-links.html +0 -20
  104. package/src/brokenLinksChecker/__fixtures__/static-site/broken-targets.html +0 -22
  105. package/src/brokenLinksChecker/__fixtures__/static-site/example.md +0 -20
  106. package/src/brokenLinksChecker/__fixtures__/static-site/external-links.html +0 -21
  107. package/src/brokenLinksChecker/__fixtures__/static-site/ignored-page.html +0 -17
  108. package/src/brokenLinksChecker/__fixtures__/static-site/index.html +0 -28
  109. package/src/brokenLinksChecker/__fixtures__/static-site/known-targets.json +0 -5
  110. package/src/brokenLinksChecker/__fixtures__/static-site/nested/page.html +0 -21
  111. package/src/brokenLinksChecker/__fixtures__/static-site/orphaned-page.html +0 -20
  112. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-api-links.html +0 -20
  113. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-custom-targets.html +0 -24
  114. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-ignored-content.html +0 -28
  115. package/src/brokenLinksChecker/__fixtures__/static-site/page-with-known-target-links.html +0 -19
  116. package/src/brokenLinksChecker/__fixtures__/static-site/unclosed-tags.html +0 -1
  117. package/src/brokenLinksChecker/__fixtures__/static-site/valid.html +0 -20
  118. package/src/brokenLinksChecker/__fixtures__/static-site/with-anchors.html +0 -31
  119. package/src/brokenLinksChecker/index.test.ts +0 -261
  120. package/src/changelog/categorizeCommits.test.ts +0 -319
  121. package/src/changelog/filterCommits.test.ts +0 -363
  122. package/src/changelog/parseCommitLabels.test.ts +0 -509
  123. package/src/changelog/renderChangelog.test.ts +0 -378
  124. package/src/changelog/sortSections.test.ts +0 -199
  125. package/src/eslint/mui/rules/add-undef-to-optional.test.mjs +0 -361
  126. package/src/eslint/mui/rules/consistent-production-guard.test.mjs +0 -162
  127. package/src/eslint/mui/rules/disallow-active-elements-as-key-event-target.test.mjs +0 -66
  128. package/src/eslint/mui/rules/disallow-react-api-in-server-components.test.mjs +0 -305
  129. package/src/eslint/mui/rules/docgen-ignore-before-comment.test.mjs +0 -52
  130. package/src/eslint/mui/rules/flatten-parentheses.test.mjs +0 -245
  131. package/src/eslint/mui/rules/mui-name-matches-component-name.test.mjs +0 -247
  132. package/src/eslint/mui/rules/no-empty-box.test.mjs +0 -40
  133. package/src/eslint/mui/rules/no-styled-box.test.mjs +0 -73
  134. package/src/eslint/mui/rules/require-dev-wrapper.test.mjs +0 -265
  135. package/src/eslint/mui/rules/rules-of-use-theme-variants.test.mjs +0 -149
  136. package/src/eslint/mui/rules/straight-quotes.test.mjs +0 -67
  137. package/src/markdownlint/duplicate-h1.mjs +0 -69
  138. package/src/markdownlint/git-diff.mjs +0 -31
  139. package/src/markdownlint/index.mjs +0 -62
  140. package/src/markdownlint/straight-quotes.mjs +0 -26
  141. package/src/markdownlint/table-alignment.mjs +0 -42
  142. package/src/markdownlint/terminal-language.mjs +0 -19
  143. package/src/utils/build.test.mjs +0 -705
  144. package/src/utils/template.test.mjs +0 -133
  145. package/src/utils/typescript.test.mjs +0 -380
@@ -1,9 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { getPublishedByPolicy } from '@pnpm/config.version-policy';
4
+ import { parseWantedDependency } from '@pnpm/parse-wanted-dependency';
5
+ import { findWorkspaceDir } from '@pnpm/find-workspace-dir';
3
6
  import { $ } from 'execa';
4
7
  import * as fs from 'node:fs/promises';
5
8
  import * as path from 'node:path';
6
9
  import * as semver from 'semver';
10
+ import { parseDocument, isMap } from 'yaml';
11
+
12
+ /** Canonical npm registry URL, in the form `getPublishRegistry` returns. */
13
+ const NPMJS_REGISTRY = 'https://registry.npmjs.org/';
7
14
 
8
15
  /**
9
16
  * @typedef {Object} PrivatePackage
@@ -46,7 +53,6 @@ import * as semver from 'semver';
46
53
  * @typedef {Object} GetWorkspacePackagesOptions
47
54
  * @property {string|null} [sinceRef] - Git reference to filter changes since
48
55
  * @property {boolean} [publicOnly=false] - Whether to filter to only public packages
49
- * @property {boolean} [nonPublishedOnly=false] - Whether to filter to only non-published packages. It by default means public packages yet to be published.
50
56
  * @property {string} [cwd] - Current working directory to run pnpm command in
51
57
  * @property {string[]} [filter] - Same as filtering packages with --filter in pnpm. Only include packages matching the filter. See https://pnpm.io/filtering.
52
58
  */
@@ -59,10 +65,6 @@ import * as semver from 'semver';
59
65
  * @returns {Promise<PublicPackage[]>} Array of packages
60
66
  *
61
67
  * @overload
62
- * @param {{ nonPublishedOnly: true } & GetWorkspacePackagesOptions} [options={}] - Options for filtering packages
63
- * @returns {Promise<PublicPackage[]>} Array of packages
64
- *
65
- * @overload
66
68
  * @param {{ publicOnly?: false | undefined } & GetWorkspacePackagesOptions} [options={}] - Options for filtering packages
67
69
  * @returns {Promise<PrivatePackage[]>} Array of packages
68
70
  *
@@ -74,20 +76,38 @@ import * as semver from 'semver';
74
76
  * @returns {Promise<(PrivatePackage | PublicPackage)[]>} Array of packages
75
77
  */
76
78
  export async function getWorkspacePackages(options = {}) {
77
- const { sinceRef = null, publicOnly = false, nonPublishedOnly = false, filter = [] } = options;
79
+ const { sinceRef = null, publicOnly = false, filter = [] } = options;
78
80
 
79
- // Build command with conditional filter
80
- const filterArg = sinceRef ? ['--filter', `...[${sinceRef}]`] : [];
81
- if (filter.length > 0) {
82
- filter.forEach((f) => {
83
- filterArg.push('--filter', f);
84
- });
81
+ /**
82
+ * Run `pnpm ls` with the given --filter args and return the parsed list.
83
+ * @param {string[]} filterArg
84
+ * @returns {Promise<PnpmListResultItem[]>}
85
+ */
86
+ const listPackages = async (filterArg) => {
87
+ const result = await $({ cwd: options.cwd })`pnpm ls -r --json --depth -1 ${filterArg}`;
88
+ return JSON.parse(result.stdout);
89
+ };
90
+
91
+ // pnpm ORs --filter args, so intersect "matches filter" with "changed since ref"
92
+ // in JS. The `...[ref]` selector includes dependents of changed packages, so a
93
+ // package whose `workspace:*` dependency changed is treated as changed too. This
94
+ // keeps consumers from getting duplicate copies when only a leaf package is
95
+ // republished but its dependents still pin the previous version.
96
+ const patternFilterArg = filter.flatMap((f) => ['--filter', f]);
97
+ const [candidatePackages, changedPackages] = await Promise.all([
98
+ listPackages(patternFilterArg),
99
+ // null when no sinceRef (skip the constraint); [] when nothing changed.
100
+ sinceRef ? listPackages(['--filter', `...[${sinceRef}]`]) : Promise.resolve(null),
101
+ ]);
102
+ let packageData = candidatePackages;
103
+ if (changedPackages) {
104
+ // sinceRef given but nothing changed → no packages, regardless of filter.
105
+ if (changedPackages.length === 0) {
106
+ return [];
107
+ }
108
+ const changedPaths = new Set(changedPackages.map((pkg) => pkg.path));
109
+ packageData = packageData.filter((pkg) => changedPaths.has(pkg.path));
85
110
  }
86
- const result = options.cwd
87
- ? await $({ cwd: options.cwd })`pnpm ls -r --json --depth -1 ${filterArg}`
88
- : await $`pnpm ls -r --json --depth -1 ${filterArg}`;
89
- /** @type {PnpmListResultItem[]} */
90
- const packageData = JSON.parse(result.stdout);
91
111
 
92
112
  // Filter packages based on options
93
113
  const filteredPackages = packageData.flatMap((pkg) => {
@@ -105,24 +125,115 @@ export async function getWorkspacePackages(options = {}) {
105
125
  ];
106
126
  });
107
127
 
108
- if (nonPublishedOnly) {
109
- // Check if any of the packages are new/need manual publishing first.
110
- const filteredPublicPackages = filteredPackages.filter((pkg) => !pkg.isPrivate);
128
+ return filteredPackages;
129
+ }
111
130
 
112
- const results = await Promise.all(
113
- filteredPublicPackages.map(async (pkg) => {
114
- const url = `${process.env.npm_config_registry || 'https://registry.npmjs.org'}/${pkg.name}`;
115
- return fetch(url).then((res) => res.status === 404);
116
- }),
131
+ /**
132
+ * Resolve the registry a package will be published to.
133
+ *
134
+ * Only `publishConfig.registry` and the ambient `npm_config_registry` are
135
+ * consulted — `.npmrc` layering and `@scope:registry` entries are not.
136
+ *
137
+ * @param {string} packagePath - Path to the package directory
138
+ * @returns {Promise<string>} Normalized registry URL, ending in a slash
139
+ */
140
+ export async function getPublishRegistry(packagePath) {
141
+ const packageJson = await readPackageJson(packagePath);
142
+ const registry =
143
+ packageJson.publishConfig?.registry || process.env.npm_config_registry || NPMJS_REGISTRY;
144
+
145
+ // Normalizing through the URL parser keeps host casing and default ports from
146
+ // defeating the equality check in `requiresTrustedPublisherBootstrap`. The
147
+ // trailing slash is required because `new URL(name, base)` replaces the last
148
+ // path segment of a base that lacks one, mangling registries served under a
149
+ // path prefix such as Artifactory's `/api/npm/<repo>`.
150
+ let registryUrl;
151
+ try {
152
+ registryUrl = new URL(registry);
153
+ } catch (error) {
154
+ // Node's own message names neither the offending value nor where it came
155
+ // from, leaving the operator to bisect package.json files mid-release.
156
+ throw new Error(
157
+ `Invalid publish registry ${JSON.stringify(registry)} for the package at ${packagePath}`,
158
+ { cause: error },
117
159
  );
118
- return filteredPublicPackages.filter((_pkg, index) => !!results[index]);
119
160
  }
161
+ registryUrl.pathname = `${registryUrl.pathname.replace(/\/+$/, '')}/`;
162
+ return registryUrl.href;
163
+ }
120
164
 
121
- return filteredPackages;
165
+ /**
166
+ * Get the version to release from the workspace-root package.json.
167
+ *
168
+ * Resolves the workspace root so the version is the monorepo's regardless of
169
+ * which directory publish runs from.
170
+ *
171
+ * @param {string} [cwd] - Directory to resolve the workspace root from
172
+ * @returns {Promise<string | null>} Version string, or null when absent/invalid
173
+ */
174
+ export async function getReleaseVersion(cwd = process.cwd()) {
175
+ const workspaceDir = (await findWorkspaceDir(cwd)) ?? cwd;
176
+ const { version } = await readPackageJson(workspaceDir);
177
+ return version ? semver.valid(version) : null;
122
178
  }
123
179
 
124
180
  /**
125
- * Get package version info from registry
181
+ * Whether a registry requires a package to exist before CI can publish to it.
182
+ * @param {string} registry - Normalized registry URL
183
+ * @returns {boolean}
184
+ */
185
+ function requiresTrustedPublisherBootstrap(registry) {
186
+ // npm won't attach a Trusted Publisher to a name that doesn't exist yet. No
187
+ // other registry we publish to has an equivalent step.
188
+ return registry === NPMJS_REGISTRY;
189
+ }
190
+
191
+ /**
192
+ * Filter to the packages that must be published by hand before CI can take over.
193
+ *
194
+ * A brand new package has to be pushed once manually (see
195
+ * `code-infra publish-new-package`) before the OIDC-based workflow can publish
196
+ * it, so the release fails with a clear message instead of a confusing 404
197
+ * midway through. See {@link getPackageVersionInfo} for the version-level check.
198
+ *
199
+ * @param {PublicPackage[]} packages - Packages to check
200
+ * @returns {Promise<PublicPackage[]>} The subset needing a manual first publish
201
+ */
202
+ export async function getPackagesNeedingManualPublish(packages) {
203
+ const results = await Promise.all(
204
+ packages.map(async (pkg) => {
205
+ const registry = await getPublishRegistry(pkg.path);
206
+ if (!requiresTrustedPublisherBootstrap(registry)) {
207
+ return false;
208
+ }
209
+
210
+ // HEAD, because only the status matters — a packument runs to megabytes.
211
+ const res = await fetch(new URL(pkg.name, registry), { method: 'HEAD' });
212
+ if (res.status === 404) {
213
+ return true;
214
+ }
215
+ if (!res.ok) {
216
+ // Anything else (401, 5xx, a proxy hiccup) tells us nothing about
217
+ // whether the package exists. Treating it as "already published" would
218
+ // silently disable the check, so fail loudly instead.
219
+ throw new Error(
220
+ `Failed to check whether ${pkg.name} exists on ${registry}: HTTP ${res.status}`,
221
+ );
222
+ }
223
+ return false;
224
+ }),
225
+ );
226
+
227
+ return packages.filter((_pkg, index) => results[index]);
228
+ }
229
+
230
+ /**
231
+ * Get package version info from registry.
232
+ *
233
+ * Resolves through `pnpm view`, which reports a lookup failure the same way it
234
+ * reports a missing version. Use {@link getPackagesNeedingManualPublish} where
235
+ * absence has to be told apart from an error.
236
+ *
126
237
  * @param {string} packageName - Name of the package
127
238
  * @param {string} baseVersion - Base version to check
128
239
  * @returns {Promise<VersionInfo>} Version information
@@ -154,11 +265,17 @@ export async function getPackageVersionInfo(packageName, baseVersion) {
154
265
  }
155
266
  }
156
267
 
268
+ /**
269
+ * @typedef {Object} PublishSummaryEntry
270
+ * @property {string} name
271
+ * @property {string} version
272
+ */
273
+
157
274
  /**
158
275
  * Publish packages with the given options
159
276
  * @param {PublicPackage[]} packages - Packages to publish
160
277
  * @param {PublishOptions} [options={}] - Publishing options
161
- * @returns {Promise<void>}
278
+ * @returns {Promise<PublishSummaryEntry[]>}
162
279
  */
163
280
  export async function publishPackages(packages, options = {}) {
164
281
  const args = [];
@@ -178,7 +295,23 @@ export async function publishPackages(packages, options = {}) {
178
295
  args.push('--no-git-checks');
179
296
  }
180
297
 
181
- await $({ stdio: 'inherit' })`pnpm -r publish --access public --tag=${tag} ${args}`;
298
+ const workspaceDir = await findWorkspaceDir(process.cwd());
299
+ if (!workspaceDir) {
300
+ throw new Error('Could not find pnpm workspace root');
301
+ }
302
+ const summaryPath = path.join(workspaceDir, 'pnpm-publish-summary.json');
303
+
304
+ // Clean up any leftover summary file from a previous run
305
+ await fs.rm(summaryPath, { force: true });
306
+
307
+ await $({
308
+ stdio: 'inherit',
309
+ env: { npm_config_loglevel: 'warn' },
310
+ })`pnpm -r publish --access public --tag=${tag} --report-summary ${args}`;
311
+
312
+ const summary = JSON.parse(await fs.readFile(summaryPath, 'utf-8'));
313
+ await fs.rm(summaryPath, { force: true });
314
+ return /** @type {PublishSummaryEntry[]} */ (summary.publishedPackages);
182
315
  }
183
316
 
184
317
  /**
@@ -187,13 +320,33 @@ export async function publishPackages(packages, options = {}) {
187
320
  * @property {boolean} [includeDev=true] - Whether to include devDependencies in the traversal
188
321
  */
189
322
 
323
+ /**
324
+ * The package a `workspace:` alias spec resolves to, if it is one.
325
+ *
326
+ * @param {string} spec - Dependency spec
327
+ * @returns {string | null} The aliased package name, or null for a plain spec
328
+ */
329
+ function aliasTarget(spec) {
330
+ if (!spec.startsWith('workspace:')) {
331
+ return null;
332
+ }
333
+ const { alias, bareSpecifier } = parseWantedDependency(spec.slice('workspace:'.length));
334
+ // A plain range parses as one half or the other (`*` as an alias, `^1.0.0` as a
335
+ // specifier); only an aliased spec carries both.
336
+ return bareSpecifier === undefined ? null : (alias ?? null);
337
+ }
338
+
190
339
  /**
191
340
  * Get all transitive workspace dependencies for a set of packages.
192
341
  *
193
- * Traverses `dependencies`, `peerDependencies`, and optionally `devDependencies`,
194
- * following only packages that exist in `workspacePathByName`. Results are cached
195
- * per package so each package is read from disk at most once regardless of how many
196
- * roots depend on it.
342
+ * Only follows deps whose version spec starts with `workspace:` (e.g. `workspace:*`
343
+ * or `workspace:^`), meaning they are sourced directly from the monorepo. An
344
+ * alias spec (`workspace:@scope/name@range`) is followed to the package it
345
+ * targets, which need not match the dependency key. Pinned
346
+ * external versions (e.g. `^1.0.0`) are ignored even when the package name exists
347
+ * in the workspace. Traverses `dependencies` and optionally `devDependencies`.
348
+ * Results are cached per package so each package is read from disk at most once
349
+ * regardless of how many roots depend on it.
197
350
  *
198
351
  * @param {string[]} packageNames - Package names to start the traversal from
199
352
  * @param {GetTransitiveDependenciesOptions} [options]
@@ -222,12 +375,19 @@ export async function getTransitiveDependencies(packageNames, options = {}) {
222
375
  }
223
376
 
224
377
  const pkgJson = await readPackageJson(packagePath);
225
- const allDeps = new Set([
226
- ...Object.keys(pkgJson.dependencies ?? {}),
227
- ...(includeDev ? Object.keys(pkgJson.devDependencies ?? {}) : []),
228
- ...Object.keys(pkgJson.peerDependencies ?? {}),
229
- ]);
230
- const workspaceDeps = [...allDeps].filter((dep) => workspacePathByName.has(dep));
378
+ const allDepEntries = [
379
+ ...Object.entries(pkgJson.dependencies ?? {}),
380
+ ...(includeDev ? Object.entries(pkgJson.devDependencies ?? {}) : []),
381
+ ];
382
+ const workspaceDeps = allDepEntries.flatMap(([dep, spec]) => {
383
+ if (typeof spec !== 'string' || !spec.startsWith('workspace:')) {
384
+ return [];
385
+ }
386
+ // An aliased spec (`workspace:@scope/name@range`) names the workspace
387
+ // package it resolves to, which need not match the dependency key.
388
+ const name = aliasTarget(spec) ?? dep;
389
+ return workspacePathByName.has(name) ? [name] : [];
390
+ });
231
391
 
232
392
  const recursiveResults = await Promise.all(workspaceDeps.map(collectDeps));
233
393
  return new Set([...workspaceDeps, ...recursiveResults.flatMap((s) => [...s])]);
@@ -248,25 +408,30 @@ export async function getTransitiveDependencies(packageNames, options = {}) {
248
408
  }
249
409
 
250
410
  /**
251
- * Validate that a set of packages covers all of their transitive workspace dependencies,
252
- * and that none of those dependencies are private (which would make them unpublishable).
411
+ * Pure validation logic: given a publish set and workspace maps, checks that all
412
+ * transitive hard workspace dependencies are covered and none are private.
413
+ *
414
+ * A hard dependency is one listed in `dependencies` (not `peerDependencies` or
415
+ * `devDependencies`) using a `workspace:` version specifier (e.g. `workspace:*` or
416
+ * `workspace:^`). Peer dependencies are never bundled and dev dependencies are not installed
417
+ * on consumer devices - both are excluded regardless of version specifier. Pinned-version
418
+ * references in `dependencies` are also excluded - they resolve from the registry and do
419
+ * not need to be co-published.
253
420
  *
254
421
  * @param {PublicPackage[]} packages - The packages intended for publishing
422
+ * @param {Map<string, PublicPackage | PrivatePackage>} workspacePackageByName - All workspace packages by name
423
+ * @param {Map<string, string>} workspacePathByName - Map of workspace package name to directory path
255
424
  * @returns {Promise<{issues: string[]}>}
256
425
  * List of human-readable issue strings. Empty when the dependency set is valid.
426
+ * @internal
257
427
  */
258
- export async function validatePublishDependencies(packages) {
259
- const allWorkspacePackages = await getWorkspacePackages();
260
-
261
- /** @type {Map<string, PublicPackage | PrivatePackage>} */
262
- const workspacePackageByName = new Map(
263
- allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg]] : [])),
264
- );
265
- const workspacePathByName = new Map(
266
- allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg.path]] : [])),
267
- );
268
-
428
+ export async function checkPublishDependencies(
429
+ packages,
430
+ workspacePackageByName,
431
+ workspacePathByName,
432
+ ) {
269
433
  const publishedNames = new Set(packages.map((pkg) => pkg.name));
434
+
270
435
  const transitiveDeps = await getTransitiveDependencies(
271
436
  packages.map((pkg) => pkg.name),
272
437
  { includeDev: false, workspacePathByName },
@@ -307,6 +472,27 @@ export async function validatePublishDependencies(packages) {
307
472
  return { issues };
308
473
  }
309
474
 
475
+ /**
476
+ * Validate that a set of packages covers all of their transitive hard workspace dependencies,
477
+ * and that none of those dependencies are private (which would make them unpublishable).
478
+ *
479
+ * @param {PublicPackage[]} packages - The packages intended for publishing
480
+ * @returns {Promise<{issues: string[]}>}
481
+ * List of human-readable issue strings. Empty when the dependency set is valid.
482
+ */
483
+ export async function validatePublishDependencies(packages) {
484
+ const allWorkspacePackages = await getWorkspacePackages();
485
+
486
+ const workspacePackageByName = /** @type {Map<string, PublicPackage | PrivatePackage>} */ (
487
+ new Map(allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg]] : [])))
488
+ );
489
+ const workspacePathByName = new Map(
490
+ allWorkspacePackages.flatMap((pkg) => (pkg.name ? [[pkg.name, pkg.path]] : [])),
491
+ );
492
+
493
+ return checkPublishDependencies(packages, workspacePackageByName, workspacePathByName);
494
+ }
495
+
310
496
  /**
311
497
  * Read package.json from a directory
312
498
  * @param {string} packagePath - Path to package directory
@@ -329,26 +515,416 @@ export async function writePackageJson(packagePath, packageJson) {
329
515
  }
330
516
 
331
517
  /**
332
- * Resolve a package@version specifier to an exact version
518
+ * Write the computed overrides into whichever manifest already defines
519
+ * overrides — preferring pnpm-workspace.yaml, falling back to package.json
520
+ * `pnpm.overrides`, defaulting to pnpm-workspace.yaml — and persist the result.
521
+ * A missing pnpm-workspace.yaml is treated as empty, so a fresh file is created
522
+ * with just the `overrides:` block. Rejects a `resolutions` field in
523
+ * package.json because pnpm 11 silently ignores it.
524
+ *
525
+ * @param {string} workspaceDir - Workspace root directory
526
+ * @param {Record<string, string>} overrides - Overrides to apply
527
+ * @returns {Promise<void>}
528
+ */
529
+ export async function writeOverridesToWorkspace(workspaceDir, overrides) {
530
+ const workspaceYamlPath = path.join(workspaceDir, 'pnpm-workspace.yaml');
531
+ const yamlPromise = fs.readFile(workspaceYamlPath, { encoding: 'utf8' }).catch((error) => {
532
+ if (/** @type {NodeJS.ErrnoException} */ (error).code !== 'ENOENT') {
533
+ throw error;
534
+ }
535
+ return '';
536
+ });
537
+ const [rootPackageJson, yamlSource] = await Promise.all([
538
+ readPackageJson(workspaceDir),
539
+ yamlPromise,
540
+ ]);
541
+
542
+ const { resolutions } = rootPackageJson;
543
+ if (resolutions && Object.keys(resolutions).length > 0) {
544
+ throw new Error(
545
+ 'Found a "resolutions" field in package.json. pnpm 11 ignores it silently. ' +
546
+ 'Move those entries into the "overrides:" key of pnpm-workspace.yaml.',
547
+ );
548
+ }
549
+
550
+ // Parsed once, reused for both the read (does it have overrides?) and the write.
551
+ const doc = parseDocument(yamlSource);
552
+ const existing = doc.get('overrides');
553
+ const workspaceHasOverrides = isMap(existing) && existing.items.length > 0;
554
+
555
+ const pnpm = /** @type {{ overrides?: Record<string, string> } | undefined} */ (
556
+ rootPackageJson.pnpm
557
+ );
558
+ const packageJsonOverrides = pnpm?.overrides;
559
+
560
+ // Write where overrides already live; default to the workspace file.
561
+ if (
562
+ !workspaceHasOverrides &&
563
+ packageJsonOverrides &&
564
+ Object.keys(packageJsonOverrides).length > 0
565
+ ) {
566
+ await writePackageJson(workspaceDir, {
567
+ ...rootPackageJson,
568
+ pnpm: { ...pnpm, overrides: { ...packageJsonOverrides, ...overrides } },
569
+ });
570
+ return;
571
+ }
572
+
573
+ for (const [name, version] of Object.entries(overrides)) {
574
+ doc.setIn(['overrides', name], version);
575
+ }
576
+ await fs.writeFile(workspaceYamlPath, doc.toString());
577
+ }
578
+
579
+ /**
580
+ * Map a package name onto a different npm scope.
581
+ * @param {string} name - Package name, e.g. `@base-ui/mosaic`
582
+ * @param {string} fromScope - Scope to replace, e.g. `@base-ui`
583
+ * @param {string} toScope - Replacement scope, e.g. `@base-ui-private`
584
+ * @returns {string | null} The renamed package, or null when the scope doesn't match
585
+ */
586
+ function renameScope(name, fromScope, toScope) {
587
+ const prefix = `${fromScope}/`;
588
+ return name.startsWith(prefix) ? `${toScope}/${name.slice(prefix.length)}` : null;
589
+ }
590
+
591
+ /**
592
+ * Move the publishable workspace packages in one scope to another.
593
+ *
594
+ * Only packages that are part of the workspace are touched, so dependencies
595
+ * that merely share the scope but come from the registry (say `@base-ui/react`
596
+ * alongside a workspace `@base-ui/mosaic`) are left alone. Dependents keep the
597
+ * original dependency name and gain a `workspace:` alias, so imports in the
598
+ * repo resolve exactly as before.
599
+ *
600
+ * @param {(PublicPackage | PrivatePackage)[]} packages - All workspace packages
601
+ * @param {string} fromScope - Scope to move away from
602
+ * @param {string} toScope - Scope to move to
603
+ * @returns {Promise<Map<string, string>>} Old package name to new package name
604
+ */
605
+ export async function renameWorkspaceScope(packages, fromScope, toScope) {
606
+ // Renaming a scope onto itself only rewrites every manifest to itself. The
607
+ // CLI rejects this earlier, but the guard belongs with the operation so a
608
+ // direct caller cannot trip the silent churn either.
609
+ if (fromScope === toScope) {
610
+ throw new Error(`Cannot rename ${fromScope} to itself.`);
611
+ }
612
+
613
+ /** @type {Map<string, string>} */
614
+ const renamed = new Map();
615
+
616
+ for (const pkg of packages) {
617
+ if (pkg.isPrivate) {
618
+ continue;
619
+ }
620
+ const newName = renameScope(pkg.name, fromScope, toScope);
621
+ if (newName) {
622
+ renamed.set(pkg.name, newName);
623
+ }
624
+ }
625
+
626
+ // A rename that lands on a name another package keeps would leave the
627
+ // workspace with two packages sharing a name. Catch it up front, before any
628
+ // manifest is written.
629
+ /** @type {Map<string, string>} */
630
+ const finalNames = new Map();
631
+ for (const pkg of packages) {
632
+ if (!pkg.name) {
633
+ continue;
634
+ }
635
+ const finalName = renamed.get(pkg.name) ?? pkg.name;
636
+ const owner = finalNames.get(finalName);
637
+ if (owner) {
638
+ throw new Error(
639
+ `Cannot rename ${fromScope} to ${toScope}: ${pkg.name} and ${owner} would both be named ${finalName}.`,
640
+ );
641
+ }
642
+ finalNames.set(finalName, pkg.name);
643
+ }
644
+
645
+ // Rewrite in memory first. A dependency that cannot be pointed at its renamed
646
+ // package has to fail before anything is written, or the workspace is left
647
+ // half renamed with nothing to restore it.
648
+ const rewritten = await Promise.all(
649
+ packages.map(async (pkg) => {
650
+ const packageJson = await readPackageJson(pkg.path);
651
+ const label = pkg.name ?? pkg.path;
652
+ /** @type {string[]} */
653
+ const problems = [];
654
+ let changed = false;
655
+
656
+ const newName = pkg.name ? renamed.get(pkg.name) : undefined;
657
+ if (newName) {
658
+ packageJson.name = newName;
659
+ changed = true;
660
+ }
661
+
662
+ // peerDependencies are deliberately absent: a peer is supplied by the
663
+ // consumer, who installs the package under its original name. An alias
664
+ // range would be unsatisfiable for them.
665
+ for (const deps of [
666
+ packageJson.dependencies,
667
+ packageJson.devDependencies,
668
+ packageJson.optionalDependencies,
669
+ ]) {
670
+ if (!deps) {
671
+ continue;
672
+ }
673
+ for (const [depName, spec] of Object.entries(deps)) {
674
+ if (!spec) {
675
+ continue;
676
+ }
677
+
678
+ const existingTarget = aliasTarget(spec);
679
+ if (existingTarget) {
680
+ if (renamed.has(existingTarget)) {
681
+ problems.push(
682
+ `"${depName}" in ${label} already aliases ${existingTarget}, which is being renamed. Point it at the package directly so it can be rewritten.`,
683
+ );
684
+ }
685
+ // Otherwise it already aliases what it should, as a re-run does.
686
+ continue;
687
+ }
688
+
689
+ const target = renamed.get(depName);
690
+ if (!target) {
691
+ continue;
692
+ }
693
+ if (!spec.startsWith('workspace:')) {
694
+ // Only `workspace:` specs can be aliased. Anything else would keep
695
+ // resolving the original name from the registry after the rename.
696
+ problems.push(
697
+ `"${depName}" in ${label} is required as "${spec}" rather than a workspace: dependency, so it cannot be pointed at ${target}.`,
698
+ );
699
+ continue;
700
+ }
701
+ deps[depName] = `workspace:${target}@${spec.slice('workspace:'.length)}`;
702
+ changed = true;
703
+ }
704
+ }
705
+
706
+ return { path: pkg.path, packageJson, changed, problems };
707
+ }),
708
+ );
709
+
710
+ const problems = rewritten.flatMap((entry) => entry.problems);
711
+ if (problems.length > 0) {
712
+ throw new Error(`Cannot rename ${fromScope} to ${toScope}:\n ${problems.join('\n ')}`);
713
+ }
714
+
715
+ await Promise.all(
716
+ rewritten
717
+ .filter((entry) => entry.changed)
718
+ .map((entry) => writePackageJson(entry.path, entry.packageJson)),
719
+ );
720
+
721
+ return renamed;
722
+ }
723
+
724
+ /**
725
+ * The versions a `minimumReleaseAgeExclude` policy exempts from the cooldown. A
726
+ * policy answers `true` for a package that is exempt at any version, or the list
727
+ * of versions exempted individually.
728
+ *
729
+ * @param {import('@pnpm/config.version-policy').PublishedByPolicy} policy - Policy from {@link getMinimumReleaseAgePolicy}
730
+ * @param {string} name - Package name
731
+ * @returns {true | string[]} `true` when every version is exempt, otherwise the exempt versions
732
+ */
733
+ function cooldownExemptions(policy, name) {
734
+ const exemption = policy.publishedByExclude?.(name);
735
+ if (exemption === true) {
736
+ return true;
737
+ }
738
+ return Array.isArray(exemption) ? exemption : [];
739
+ }
740
+
741
+ /**
742
+ * Pick the version to pin for a specifier whose newest match is too recent to
743
+ * satisfy a `minimumReleaseAge` cooldown.
744
+ *
745
+ * Only the three specifier shapes this tool is given are handled. An exact
746
+ * version is not a choice, so it stands and the install reports it. A range
747
+ * resolves within itself. A dist-tag repoints to the highest aged-in version
748
+ * sharing the major and prerelease-ness — except `latest`, which pnpm allows to
749
+ * cross majors. Unlike pnpm, a deprecated version is not passed over: `pnpm info`
750
+ * lists bare version strings, so that flag would cost a request per candidate.
751
+ *
752
+ * @param {string} requested - The specifier as given: a dist-tag, range or exact version
753
+ * @param {string} resolvedVersion - Version the specifier resolves to today
754
+ * @param {string[]} versions - Every published version, from `pnpm info <pkg> versions`
755
+ * @param {Record<string, string>} publishTimes - Version to ISO publish date, from `pnpm info <pkg> time`
756
+ * @param {number} cutoff - Epoch ms; versions published after this are too recent
757
+ * @param {string[]} [exemptVersions] - Versions `minimumReleaseAgeExclude` installs regardless of age
758
+ * @returns {string | null} Version to pin, or null when nothing qualifies
759
+ * @internal exported for unit tests
760
+ */
761
+ export function selectAgedVersion(
762
+ requested,
763
+ resolvedVersion,
764
+ versions,
765
+ publishTimes,
766
+ cutoff,
767
+ exemptVersions = [],
768
+ ) {
769
+ const exempt = new Set(exemptVersions);
770
+
771
+ /**
772
+ * Whether the install would accept this version: old enough, or excluded from
773
+ * the cooldown altogether.
774
+ *
775
+ * @param {string} version
776
+ * @returns {boolean}
777
+ */
778
+ const isInstallable = (version) => {
779
+ if (exempt.has(version)) {
780
+ return true;
781
+ }
782
+ const published = Date.parse(publishTimes[version]);
783
+ return Number.isFinite(published) && published <= cutoff;
784
+ };
785
+
786
+ // An unknown publish date leaves nothing to compare against, so the
787
+ // resolution stands rather than being swapped for another build.
788
+ if (!Object.hasOwn(publishTimes, resolvedVersion) || isInstallable(resolvedVersion)) {
789
+ return resolvedVersion;
790
+ }
791
+
792
+ if (semver.valid(requested)) {
793
+ return resolvedVersion;
794
+ }
795
+
796
+ // `time` keeps an entry for a version after it is unpublished, so candidates
797
+ // come from the version list rather than from the dates.
798
+ const candidates = versions.filter(isInstallable);
799
+
800
+ if (semver.validRange(requested)) {
801
+ return semver.maxSatisfying(candidates, requested, true);
802
+ }
803
+
804
+ const resolved = semver.parse(resolvedVersion, true);
805
+ if (!resolved) {
806
+ return resolvedVersion;
807
+ }
808
+ const resolvedIsPrerelease = resolved.prerelease.length > 0;
809
+
810
+ let best = null;
811
+ for (const version of candidates) {
812
+ const parsed = semver.parse(version, true);
813
+ if (
814
+ !parsed ||
815
+ (requested !== 'latest' && parsed.major !== resolved.major) ||
816
+ parsed.prerelease.length > 0 !== resolvedIsPrerelease
817
+ ) {
818
+ continue;
819
+ }
820
+ if (!best || semver.gt(version, best, true)) {
821
+ best = version;
822
+ }
823
+ }
824
+ return best;
825
+ }
826
+
827
+ /**
828
+ * Read the effective pnpm configuration, including everything resolved from
829
+ * pnpm-workspace.yaml. `config list` types the values and omits unset keys,
830
+ * where `config get` stringifies everything and prints `undefined`.
831
+ *
832
+ * @returns {Promise<Record<string, any>>} Parsed configuration
833
+ */
834
+ export async function readPnpmConfig() {
835
+ const result = await $`pnpm config list --json`;
836
+ return JSON.parse(result.stdout);
837
+ }
838
+
839
+ /**
840
+ * Read the registry cooldown from pnpm config, so resolution stays in step with
841
+ * what the subsequent install will enforce.
842
+ *
843
+ * @returns {Promise<import('@pnpm/config.version-policy').PublishedByPolicy>} Cutoff date and exemption policy, both undefined when no cooldown is configured
844
+ */
845
+ export async function getMinimumReleaseAgePolicy() {
846
+ const config = await readPnpmConfig();
847
+ // pnpm's own parser, so exclude entries keep their full grammar — wildcards,
848
+ // version unions (`pkg@1.0.0 || 2.0.0`) and `!` negation.
849
+ return getPublishedByPolicy({
850
+ minimumReleaseAge: config.minimumReleaseAge,
851
+ minimumReleaseAgeExclude: config.minimumReleaseAgeExclude,
852
+ });
853
+ }
854
+
855
+ /**
856
+ * Resolve a package@version specifier to an exact version.
857
+ *
858
+ * Given a cooldown policy, the result is the newest version the install will
859
+ * actually accept — a dist-tag on a daily channel always points at a build too
860
+ * recent to install under one. See {@link selectAgedVersion}.
861
+ *
333
862
  * @param {string} packageSpec - Package specifier in format "package@version"
863
+ * @param {import('@pnpm/config.version-policy').PublishedByPolicy} policy - Cooldown from {@link getMinimumReleaseAgePolicy}
334
864
  * @returns {Promise<string>} Exact version string
335
865
  */
336
- export async function resolveVersion(packageSpec) {
337
- const result = await $`pnpm info ${packageSpec} version --json`;
338
- const versions = JSON.parse(result.stdout);
339
- return typeof versions === 'string' ? versions : versions[versions.length - 1];
866
+ export async function resolveVersion(packageSpec, policy) {
867
+ // The unprojected document carries both the resolved version and every
868
+ // publish date, so honouring the cooldown costs no extra round-trip.
869
+ const info = JSON.parse((await $`pnpm info ${packageSpec} --json`).stdout);
870
+ const manifest = Array.isArray(info) ? info[info.length - 1] : info;
871
+ const { name, version: exactVersion, time: publishTimes = {}, versions = [] } = manifest;
872
+
873
+ if (!policy.publishedBy) {
874
+ return exactVersion;
875
+ }
876
+
877
+ const exemptVersions = cooldownExemptions(policy, name);
878
+ if (exemptVersions === true || exemptVersions.includes(exactVersion)) {
879
+ return exactVersion;
880
+ }
881
+
882
+ const cutoff = policy.publishedBy.toISOString();
883
+ const { bareSpecifier: requested } = parseWantedDependency(packageSpec);
884
+ const agedVersion = selectAgedVersion(
885
+ requested ?? '',
886
+ exactVersion,
887
+ versions,
888
+ publishTimes,
889
+ policy.publishedBy.getTime(),
890
+ exemptVersions,
891
+ );
892
+
893
+ if (!agedVersion) {
894
+ throw new Error(
895
+ `No version matching ${packageSpec} was published before the minimumReleaseAge cutoff ` +
896
+ `(${cutoff}). The newest match, ${exactVersion}, was published at ` +
897
+ `${publishTimes[exactVersion]}, and no earlier match qualifies. Lower ` +
898
+ `minimumReleaseAge, add ${name} to minimumReleaseAgeExclude, or wait for ${exactVersion} ` +
899
+ `to age in.`,
900
+ );
901
+ }
902
+
903
+ if (agedVersion !== exactVersion) {
904
+ // eslint-disable-next-line no-console
905
+ console.log(
906
+ `Resolved ${packageSpec} to ${agedVersion} rather than ${exactVersion}, which was published after the minimumReleaseAge cutoff (${cutoff}).`,
907
+ );
908
+ }
909
+
910
+ return agedVersion;
340
911
  }
341
912
 
342
913
  /**
343
914
  * Find the version of a dependency for a specific package@version
915
+ *
916
+ * The parent's spec is often a range, so the cooldown applies here too. Stepping
917
+ * back stays within that range and so never contradicts the parent.
918
+ *
344
919
  * @param {string} packageSpec - Package specifier in format "package@version"
345
920
  * @param {string} dependency - Dependency name to look up
921
+ * @param {import('@pnpm/config.version-policy').PublishedByPolicy} policy - Registry cooldown to resolve within
346
922
  * @returns {Promise<string>} Exact version string of the dependency
347
923
  */
348
- export async function findDependencyVersionFromSpec(packageSpec, dependency) {
924
+ export async function findDependencyVersionFromSpec(packageSpec, dependency, policy) {
349
925
  const result = await $`pnpm info ${packageSpec} dependencies.${dependency}`;
350
926
  const spec = result.stdout.trim();
351
- return resolveVersion(`${dependency}@${spec}`);
927
+ return resolveVersion(`${dependency}@${spec}`, policy);
352
928
  }
353
929
 
354
930
  /**