@virmator/deps 14.23.0 → 14.24.0
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 +1 -3
- package/configs/deps-regen.config.base.ts +12 -10
- package/dist/deps.d.ts +2 -2
- package/dist/deps.js +38 -132
- package/dist/regen-recent-deps.d.ts +36 -144
- package/dist/regen-recent-deps.js +41 -351
- package/dist/upgrade-deps.d.ts +59 -0
- package/dist/upgrade-deps.js +121 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -47,9 +47,7 @@ A default plugin for [virmator](https://www.npmjs.com/package/virmator).
|
|
|
47
47
|
|
|
48
48
|
Force regeneration of all all dependencies by deleting all node_modules directories and package-lock.json and then running 'npm i'.
|
|
49
49
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
The allow list defaults to 'configs/deps-regen.config.ts' (as placed by 'virmator init'); a missing default config is silently skipped. Override it with '--config <path>'; an explicitly-provided config that does not exist is an error.
|
|
50
|
+
Reads 'configs/deps-regen.config.ts' for a list of packages (exact names or globs) to exempt from min-release-age during the install, via npm's '--min-release-age-exclude' flag.
|
|
53
51
|
|
|
54
52
|
- Examples
|
|
55
53
|
- `virmator deps regen`
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
/** These packages bypass min-release-age when running `virmator deps regen`. */
|
|
2
|
-
export type RecentDepsAllowList = ReadonlyArray<string
|
|
2
|
+
export type RecentDepsAllowList = ReadonlyArray<string>;
|
|
3
3
|
|
|
4
4
|
const electrovirPackages: RecentDepsAllowList = [
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
'@augment-vir/*',
|
|
6
|
+
'@date-vir/*',
|
|
7
|
+
'@electrovir/*',
|
|
8
|
+
'@rest-vir/*',
|
|
9
|
+
'@review-vir/*',
|
|
10
|
+
'@updating-secrets/*',
|
|
11
|
+
'@virmator/*',
|
|
12
12
|
'auth-vir',
|
|
13
13
|
'catch-exit',
|
|
14
14
|
'cli-vir',
|
|
@@ -21,6 +21,7 @@ const electrovirPackages: RecentDepsAllowList = [
|
|
|
21
21
|
'element-vir',
|
|
22
22
|
'execute-in-browser',
|
|
23
23
|
'i18n-vir',
|
|
24
|
+
'indexed-vir',
|
|
24
25
|
'istanbul-smart-text-reporter',
|
|
25
26
|
'lit-css-vars',
|
|
26
27
|
'local-db-client',
|
|
@@ -54,8 +55,9 @@ const electrovirPackages: RecentDepsAllowList = [
|
|
|
54
55
|
];
|
|
55
56
|
|
|
56
57
|
/**
|
|
57
|
-
* The default allow list: electrovir's own commonly-used packages. Each entry
|
|
58
|
-
*
|
|
58
|
+
* The default allow list: electrovir's own commonly-used packages. Each entry is an exact package
|
|
59
|
+
* name or a `minimatch` glob pattern matched against the package name (forwarded to npm's
|
|
60
|
+
* `min-release-age-exclude`).
|
|
59
61
|
*/
|
|
60
62
|
export const baseAllowedRecentDeps: RecentDepsAllowList = [
|
|
61
63
|
...electrovirPackages,
|
package/dist/deps.d.ts
CHANGED
|
@@ -122,7 +122,7 @@ export declare const virmatorDepsPlugin: Readonly<Readonly<{
|
|
|
122
122
|
};
|
|
123
123
|
readonly regen: {
|
|
124
124
|
readonly doc: {
|
|
125
|
-
readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n ", "\n
|
|
125
|
+
readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n ", "\n Reads 'configs/deps-regen.config.ts' for a list of packages\n (exact names or globs) to exempt from min-release-age during the\n install, via npm's '--min-release-age-exclude' flag.\n "];
|
|
126
126
|
readonly examples: readonly [{
|
|
127
127
|
readonly content: "virmator deps regen";
|
|
128
128
|
}, {
|
|
@@ -256,7 +256,7 @@ export declare const virmatorDepsPlugin: Readonly<Readonly<{
|
|
|
256
256
|
};
|
|
257
257
|
readonly regen: {
|
|
258
258
|
readonly doc: {
|
|
259
|
-
readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n ", "\n
|
|
259
|
+
readonly sections: readonly ["\n Force regeneration of all all dependencies by deleting all\n node_modules directories and package-lock.json and then\n running 'npm i'.\n ", "\n Reads 'configs/deps-regen.config.ts' for a list of packages\n (exact names or globs) to exempt from min-release-age during the\n install, via npm's '--min-release-age-exclude' flag.\n "];
|
|
260
260
|
readonly examples: readonly [{
|
|
261
261
|
readonly content: "virmator deps regen";
|
|
262
262
|
}, {
|
package/dist/deps.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { check } from '@augment-vir/assert';
|
|
2
|
-
import { awaitedBlockingMap,
|
|
3
|
-
import {
|
|
2
|
+
import { awaitedBlockingMap, RuntimeEnv } from '@augment-vir/common';
|
|
3
|
+
import { toPosixPath } from '@augment-vir/node';
|
|
4
4
|
import { copyConfigFile, defineVirmatorPlugin, JsModuleType, NpmDepType, PackageType, VirmatorNoTraceError, withCompiledTsFile, withImportedTsFile, } from '@virmator/core';
|
|
5
5
|
import mri from 'mri';
|
|
6
6
|
import { rm } from 'node:fs/promises';
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
7
|
+
import { join, relative } from 'node:path';
|
|
8
|
+
import { buildMinReleaseAgeExcludeFlags, extractRegenConfigArg, listRegenNodeModulesDirs, resolveRegenConfigPath, resolveRegenExcludes, } from './regen-recent-deps.js';
|
|
9
|
+
import { runArgBasedUpgrade } from './upgrade-deps.js';
|
|
10
10
|
/** A virmator plugin for checking package TS dependencies. */
|
|
11
11
|
export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
12
12
|
name: 'Deps',
|
|
@@ -178,21 +178,9 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
|
178
178
|
running 'npm i'.
|
|
179
179
|
`,
|
|
180
180
|
`
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
version is temporarily downgraded to the most recent version that
|
|
185
|
-
satisfies 'min-release-age' so the install succeeds. After
|
|
186
|
-
regeneration, each such dependency is re-installed at its original
|
|
187
|
-
version with '--min-release-age=0' (in its own package, or the
|
|
188
|
-
mono-repo root) and its original 'package.json' version is
|
|
189
|
-
restored.
|
|
190
|
-
`,
|
|
191
|
-
`
|
|
192
|
-
The allow list defaults to 'configs/deps-regen.config.ts' (as
|
|
193
|
-
placed by 'virmator init'); a missing default config is silently
|
|
194
|
-
skipped. Override it with '--config <path>'; an explicitly-provided
|
|
195
|
-
config that does not exist is an error.
|
|
181
|
+
Reads 'configs/deps-regen.config.ts' for a list of packages
|
|
182
|
+
(exact names or globs) to exempt from min-release-age during the
|
|
183
|
+
install, via npm's '--min-release-age-exclude' flag.
|
|
196
184
|
`,
|
|
197
185
|
],
|
|
198
186
|
examples: [
|
|
@@ -260,72 +248,11 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
|
260
248
|
const upgradeArgs = mri(filteredArgs);
|
|
261
249
|
const depPattern = upgradeArgs._[0];
|
|
262
250
|
if (depPattern) {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
*/
|
|
269
|
-
const lastAtIndex = depPattern.lastIndexOf('@');
|
|
270
|
-
const namePattern = lastAtIndex > 0 ? depPattern.slice(0, lastAtIndex) : depPattern;
|
|
271
|
-
const versionSpecifier = lastAtIndex > 0 ? depPattern.slice(lastAtIndex + 1) : 'latest';
|
|
272
|
-
const allDirectDeps = await listAllDirectNpmDeps(monoRepoRootPath);
|
|
273
|
-
const matchedDepsByPackageAndKey = Object.entries(allDirectDeps).reduce((accum, [depName, usages,]) => {
|
|
274
|
-
if (!matchesGlob(depName, namePattern)) {
|
|
275
|
-
return accum;
|
|
276
|
-
}
|
|
277
|
-
return usages.reduce((innerAccumulator, usage) => {
|
|
278
|
-
if (usage.isWorkspace ||
|
|
279
|
-
installFlagsByDepKey[usage.dependencyKey] == undefined) {
|
|
280
|
-
return innerAccumulator;
|
|
281
|
-
}
|
|
282
|
-
const packageDir = dirname(usage.requiredBy);
|
|
283
|
-
const existingDepsByKey = innerAccumulator[packageDir] ?? {};
|
|
284
|
-
const existingDeps = existingDepsByKey[usage.dependencyKey] ?? [];
|
|
285
|
-
return {
|
|
286
|
-
...innerAccumulator,
|
|
287
|
-
[packageDir]: {
|
|
288
|
-
...existingDepsByKey,
|
|
289
|
-
[usage.dependencyKey]: [
|
|
290
|
-
...existingDeps,
|
|
291
|
-
depName,
|
|
292
|
-
],
|
|
293
|
-
},
|
|
294
|
-
};
|
|
295
|
-
}, accum);
|
|
296
|
-
}, {});
|
|
297
|
-
const matches = Object.entries(matchedDepsByPackageAndKey);
|
|
298
|
-
if (!matches.length) {
|
|
299
|
-
throw new VirmatorNoTraceError(`No direct dependencies matching '${depPattern}' found in any package.json.`);
|
|
300
|
-
}
|
|
301
|
-
await awaitedBlockingMap(matches, async ([packageDir, depsByKey,]) => {
|
|
302
|
-
await awaitedBlockingMap(getObjectTypedEntries(depsByKey), async ([dependencyKey, depNames,]) => {
|
|
303
|
-
const flag = installFlagsByDepKey[dependencyKey];
|
|
304
|
-
/**
|
|
305
|
-
* Defensive guard: upstream filter at 'matchedDepsByPackageAndKey'
|
|
306
|
-
* already drops entries whose dep key maps to an undefined flag, so
|
|
307
|
-
* this branch is unreachable in practice.
|
|
308
|
-
*/
|
|
309
|
-
/* node:coverage ignore next 3 */
|
|
310
|
-
if (flag == undefined) {
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
const command = [
|
|
314
|
-
'npm',
|
|
315
|
-
'i',
|
|
316
|
-
flag,
|
|
317
|
-
...passthroughArgs,
|
|
318
|
-
...depNames.map((depName) => `${depName}@${versionSpecifier}`),
|
|
319
|
-
]
|
|
320
|
-
.filter(check.isTruthy)
|
|
321
|
-
.join(' ');
|
|
322
|
-
await runShellCommand(command, {
|
|
323
|
-
cwd: packageDir,
|
|
324
|
-
}, {
|
|
325
|
-
logPrefix: relative(monoRepoRootPath, packageDir) || '.',
|
|
326
|
-
prefixCommandOnly: true,
|
|
327
|
-
});
|
|
328
|
-
});
|
|
251
|
+
await runArgBasedUpgrade({
|
|
252
|
+
depPattern,
|
|
253
|
+
filteredArgs,
|
|
254
|
+
monoRepoRootPath,
|
|
255
|
+
runShellCommand,
|
|
329
256
|
});
|
|
330
257
|
}
|
|
331
258
|
else {
|
|
@@ -353,62 +280,41 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
|
353
280
|
/** Strip '--config <path>' so it isn't forwarded to 'npm i'. */
|
|
354
281
|
const { configValue, passthroughArgs } = extractRegenConfigArg(filteredArgs);
|
|
355
282
|
/**
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
* no 'min-release-age', this is a no-op.
|
|
283
|
+
* Allow-listed packages (exact names or globs) that bypass min-release-age during the
|
|
284
|
+
* install via npm's '--min-release-age-exclude' flag. Empty when there is no config.
|
|
359
285
|
*/
|
|
360
|
-
const
|
|
361
|
-
monoRepoRootPath,
|
|
286
|
+
const regenExcludes = await resolveRegenExcludes({
|
|
362
287
|
configPath: resolveRegenConfigPath({
|
|
363
288
|
configValue,
|
|
364
289
|
cwd,
|
|
365
290
|
monoRepoRootPath,
|
|
366
291
|
}),
|
|
367
292
|
configIsExplicit: check.isTruthy(configValue),
|
|
368
|
-
minReleaseAgeDays: await getMinReleaseAgeDays(monoRepoRootPath),
|
|
369
|
-
log,
|
|
370
293
|
});
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
await rm(path, {
|
|
379
|
-
force: true,
|
|
380
|
-
recursive: true,
|
|
381
|
-
});
|
|
382
|
-
});
|
|
383
|
-
log.faint('Removing package-lock.json...');
|
|
384
|
-
await rm(join(monoRepoRootPath, 'package-lock.json'), {
|
|
294
|
+
const allNodeModulesDirectories = listRegenNodeModulesDirs({
|
|
295
|
+
monoRepoRootPath,
|
|
296
|
+
monoRepoPackages,
|
|
297
|
+
});
|
|
298
|
+
await awaitedBlockingMap(allNodeModulesDirectories, async (path) => {
|
|
299
|
+
log.faint(`Removing ${relative(monoRepoRootPath, path)}...`);
|
|
300
|
+
await rm(path, {
|
|
385
301
|
force: true,
|
|
302
|
+
recursive: true,
|
|
386
303
|
});
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
}
|
|
402
|
-
finally {
|
|
403
|
-
/**
|
|
404
|
-
* Always restore the original `package.json` versions, even if regen failed
|
|
405
|
-
* partway, so a failed run never leaves dependencies silently downgraded. A no-op
|
|
406
|
-
* when there were no matches.
|
|
407
|
-
*/
|
|
408
|
-
await restoreOriginalPackageJsonVersions({
|
|
409
|
-
violators: recentDepViolators,
|
|
410
|
-
});
|
|
411
|
-
}
|
|
304
|
+
});
|
|
305
|
+
log.faint('Removing package-lock.json...');
|
|
306
|
+
await rm(join(monoRepoRootPath, 'package-lock.json'), {
|
|
307
|
+
force: true,
|
|
308
|
+
});
|
|
309
|
+
const installCommand = [
|
|
310
|
+
'npm',
|
|
311
|
+
'i',
|
|
312
|
+
...passthroughArgs,
|
|
313
|
+
...buildMinReleaseAgeExcludeFlags(regenExcludes),
|
|
314
|
+
].join(' ');
|
|
315
|
+
await runShellCommand(installCommand);
|
|
316
|
+
/** Run twice because npm needs this sometimes. */
|
|
317
|
+
await runShellCommand(installCommand);
|
|
412
318
|
}
|
|
413
319
|
else {
|
|
414
320
|
throw new VirmatorNoTraceError("deps sub-command needed: 'virmator deps check', 'virmator deps upgrade', or 'virmator deps regen'");
|
|
@@ -1,9 +1,19 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import { type MonoRepoPackage } from '@virmator/core';
|
|
2
|
+
/**
|
|
3
|
+
* All `node_modules` directories deleted before a regen install: one per mono-repo package plus the
|
|
4
|
+
* mono-repo root. For a single (non-mono) package, `monoRepoPackages` is empty so only the root is
|
|
5
|
+
* returned.
|
|
6
|
+
*/
|
|
7
|
+
export declare function listRegenNodeModulesDirs({ monoRepoRootPath, monoRepoPackages, }: {
|
|
8
|
+
monoRepoRootPath: string;
|
|
9
|
+
monoRepoPackages: ReadonlyArray<Pick<MonoRepoPackage, 'relativePath'>>;
|
|
10
|
+
}): string[];
|
|
11
|
+
/**
|
|
12
|
+
* Whether an allow-list entry is safe to interpolate (single-quoted) into a shell command. Allows
|
|
13
|
+
* npm package names and `minimatch` glob patterns (the `*` wildcard) while rejecting anything that
|
|
14
|
+
* could smuggle shell metacharacters or quotes out of an (untrusted) config file.
|
|
15
|
+
*/
|
|
16
|
+
export declare function isSafeExcludePattern(pattern: string): boolean;
|
|
7
17
|
/**
|
|
8
18
|
* Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
|
|
9
19
|
* returning the config value and the remaining args to forward to `npm i`.
|
|
@@ -24,159 +34,41 @@ export declare function resolveRegenConfigPath({ configValue, cwd, monoRepoRootP
|
|
|
24
34
|
/**
|
|
25
35
|
* Structural copy of the allow list type defined in `configs/deps-regen.config.base.ts`. It is
|
|
26
36
|
* re-declared here because `configs` lives outside this package's compiled `src` root, so it cannot
|
|
27
|
-
* be type-imported. Each entry
|
|
37
|
+
* be type-imported. Each entry is an exact npm package name or a `minimatch` glob pattern matched
|
|
38
|
+
* against the package name (forwarded directly to npm's `min-release-age-exclude`).
|
|
28
39
|
*/
|
|
29
|
-
export type RecentDepsAllowList = ReadonlyArray<string
|
|
30
|
-
/** A direct dependency whose currently-pinned version is too recent for the repo's min-release-age. */
|
|
31
|
-
export type RecentDepViolator = {
|
|
32
|
-
/** Absolute path to the `package.json` that pins this dependency. */
|
|
33
|
-
packageJsonPath: string;
|
|
34
|
-
/** Directory containing {@link RecentDepViolator.packageJsonPath}. */
|
|
35
|
-
packageDir: string;
|
|
36
|
-
dependencyKey: PackageJsonDependencyKey;
|
|
37
|
-
depName: string;
|
|
38
|
-
/** The original version range string from `package.json`, including any prefix (e.g. `^1.2.3`). */
|
|
39
|
-
originalVersionValue: string;
|
|
40
|
-
/** The leading non-numeric prefix of the original version (e.g. `^` or `~` or `''`). */
|
|
41
|
-
versionPrefix: string;
|
|
42
|
-
/** The most recent published version that does _not_ violate min-release-age. */
|
|
43
|
-
safeVersion: string;
|
|
44
|
-
};
|
|
45
|
-
export type RegistryInfo = {
|
|
46
|
-
/** Map of published version (and `created`/`modified`) to ISO publish date. */
|
|
47
|
-
time: Record<string, string>;
|
|
48
|
-
};
|
|
49
|
-
/** A single `package.json` dependency version change applied by {@link updatePackageJsonVersions}. */
|
|
50
|
-
export type VersionUpdate = {
|
|
51
|
-
dependencyKey: PackageJsonDependencyKey;
|
|
52
|
-
depName: string;
|
|
53
|
-
version: string;
|
|
54
|
-
};
|
|
55
|
-
/** A direct dependency name paired with its installable, non-workspace usages. */
|
|
56
|
-
export type CandidateDepUsage = {
|
|
57
|
-
depName: string;
|
|
58
|
-
usages: NpmDeps[string];
|
|
59
|
-
};
|
|
40
|
+
export type RecentDepsAllowList = ReadonlyArray<string>;
|
|
60
41
|
/**
|
|
61
|
-
* Injectable IO used by {@link
|
|
62
|
-
*
|
|
63
|
-
* filesystem.
|
|
42
|
+
* Injectable IO used by {@link resolveRegenExcludes}. Defaults to real implementations; overridden
|
|
43
|
+
* in tests so the orchestration can be exercised without touching the filesystem.
|
|
64
44
|
*/
|
|
65
|
-
export type
|
|
45
|
+
export type RegenExcludesIo = {
|
|
66
46
|
fileExists: (filePath: string) => Promise<boolean>;
|
|
67
47
|
loadAllowList: (configPath: string) => Promise<RecentDepsAllowList | undefined>;
|
|
68
|
-
listDirectDeps: (rootPath: string) => Promise<NpmDeps>;
|
|
69
|
-
queryRegistry: (depName: string, cwd: string) => Promise<RegistryInfo | undefined>;
|
|
70
|
-
/**
|
|
71
|
-
* Resolves the given range to the newest published version satisfying it (ignoring
|
|
72
|
-
* min-release-age) — i.e. what gets installed once min-release-age is bypassed — or `undefined`
|
|
73
|
-
* if the range matches nothing.
|
|
74
|
-
*/
|
|
75
|
-
queryResolvedVersion: (depName: string, range: string, cwd: string) => Promise<string | undefined>;
|
|
76
|
-
updatePackageJsonVersions: (packageJsonPath: string, updates: ReadonlyArray<VersionUpdate>) => Promise<void>;
|
|
77
48
|
};
|
|
78
|
-
/** Parses the output of `npm config get min-release-age` into a positive day count, or `undefined`. */
|
|
79
|
-
export declare function parseMinReleaseAgeDays(rawValue: string): number | undefined;
|
|
80
|
-
/**
|
|
81
|
-
* Returns the effective `min-release-age` (in days) as resolved by npm across all config sources
|
|
82
|
-
* (project `.npmrc` overriding user, overriding global), or `undefined` if it is unset or
|
|
83
|
-
* non-positive.
|
|
84
|
-
*/
|
|
85
|
-
export declare function getMinReleaseAgeDays(monoRepoRootPath: string): Promise<number | undefined>;
|
|
86
49
|
export declare function fileExists(filePath: string): Promise<boolean>;
|
|
87
50
|
export declare function loadAllowList(configPath: string): Promise<RecentDepsAllowList | undefined>;
|
|
88
|
-
/**
|
|
89
|
-
export declare
|
|
90
|
-
/**
|
|
91
|
-
* Parses the JSON output of `npm view <pkg>@<range> version --json` into the newest matching
|
|
92
|
-
* version (the last entry, since npm sorts ascending), or `undefined` if nothing matched / the
|
|
93
|
-
* output was unusable.
|
|
94
|
-
*/
|
|
95
|
-
export declare function parseResolvedVersion(stdout: string): string | undefined;
|
|
96
|
-
/** Reads, mutates the given dependency versions in, and re-writes a `package.json` file in place. */
|
|
97
|
-
export declare function updatePackageJsonVersions(packageJsonPath: string, updates: ReadonlyArray<VersionUpdate>): Promise<void>;
|
|
51
|
+
/** The real (filesystem) IO used by {@link resolveRegenExcludes}. */
|
|
52
|
+
export declare const defaultRegenExcludesIo: RegenExcludesIo;
|
|
98
53
|
/**
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
54
|
+
* Loads the deps-regen allow list and returns the deduped package names / glob patterns that should
|
|
55
|
+
* bypass `min-release-age` during the regen install. A missing explicit config (from `--config`)
|
|
56
|
+
* throws; a missing default config is silently skipped (returns `[]`). Unsafe entries (which can't
|
|
57
|
+
* be safely interpolated into a shell command) throw rather than being silently dropped.
|
|
102
58
|
*/
|
|
103
|
-
export declare function
|
|
104
|
-
/** The lookup key for a specific dependency range (or version). */
|
|
105
|
-
export declare function depRangeKey(depName: string, range: string): string;
|
|
106
|
-
/**
|
|
107
|
-
* Returns the `{depName, range}` pairs whose newest-in-range version must be resolved (to check
|
|
108
|
-
* recency against the version that will actually be installed): only for allow-list-matched
|
|
109
|
-
* candidates with a parseable range. Deduped.
|
|
110
|
-
*/
|
|
111
|
-
export declare function getResolveTargets(candidateUsages: ReadonlyArray<CandidateDepUsage>, allowList: RecentDepsAllowList): {
|
|
112
|
-
depName: string;
|
|
113
|
-
range: string;
|
|
114
|
-
}[];
|
|
115
|
-
/**
|
|
116
|
-
* Pure detection of every direct dependency usage that both matches the allow list and pins a
|
|
117
|
-
* version too recent for the min-release-age threshold, paired with the safe version it should be
|
|
118
|
-
* temporarily downgraded to.
|
|
119
|
-
*/
|
|
120
|
-
export declare function computeRecentDepViolators({ candidateUsages, allowList, registryByName, resolvedByRange, threshold, }: {
|
|
121
|
-
candidateUsages: ReadonlyArray<CandidateDepUsage>;
|
|
122
|
-
allowList: RecentDepsAllowList;
|
|
123
|
-
registryByName: ReadonlyMap<string, RegistryInfo | undefined>;
|
|
124
|
-
/**
|
|
125
|
-
* The resolved newest-in-range version per `${depName}@${range}`. Recency is checked against
|
|
126
|
-
* this (the version that will actually be installed), not the pinned floor.
|
|
127
|
-
*/
|
|
128
|
-
resolvedByRange: ReadonlyMap<string, string | undefined>;
|
|
129
|
-
/** The min-release-age cutoff: a version published after this is too recent. */
|
|
130
|
-
threshold: FullDate;
|
|
131
|
-
}): RecentDepViolator[];
|
|
132
|
-
/** The real IO (network and filesystem) used by {@link prepareRecentDepDowngrades}. */
|
|
133
|
-
export declare const defaultRecentDepsIo: RecentDepsIo;
|
|
134
|
-
/**
|
|
135
|
-
* Detects every direct dependency that both matches the deps-regen allow list and currently pins a
|
|
136
|
-
* version that violates the repo's min-release-age. Each such dependency is temporarily downgraded
|
|
137
|
-
* in its `package.json` to the most recent version that does _not_ violate min-release-age, so that
|
|
138
|
-
* the subsequent `npm i` succeeds. The original version values are returned so they can be restored
|
|
139
|
-
* via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
|
|
140
|
-
* regeneration.
|
|
141
|
-
*/
|
|
142
|
-
export declare function prepareRecentDepDowngrades({ monoRepoRootPath, configPath, configIsExplicit, minReleaseAgeDays, log, now, io, }: {
|
|
143
|
-
monoRepoRootPath: string;
|
|
59
|
+
export declare function resolveRegenExcludes({ configPath, configIsExplicit, io, }: {
|
|
144
60
|
configPath: string;
|
|
145
61
|
/**
|
|
146
62
|
* Whether `configPath` came from an explicit `--config` flag. A missing explicit config throws,
|
|
147
63
|
* while a missing default config is silently skipped.
|
|
148
64
|
*/
|
|
149
65
|
configIsExplicit: boolean;
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
* even reading the deps-regen config.
|
|
153
|
-
*/
|
|
154
|
-
minReleaseAgeDays: number | undefined;
|
|
155
|
-
log: Logger;
|
|
156
|
-
now?: FullDate | undefined;
|
|
157
|
-
io?: RecentDepsIo | undefined;
|
|
158
|
-
}): Promise<RecentDepViolator[]>;
|
|
159
|
-
/**
|
|
160
|
-
* Re-installs each downgraded dependency at its original version, bypassing min-release-age.
|
|
161
|
-
* Installs are grouped per package directory and per dependency type (`-D`, `--save-peer`, or none)
|
|
162
|
-
* so each `npm i` runs in the correct location (sub-packages and/or the mono-repo root). Each
|
|
163
|
-
* install spec is single-quoted; combined with the package-name and version validation done while
|
|
164
|
-
* detecting violators, this prevents shell injection from `package.json` values.
|
|
165
|
-
*/
|
|
166
|
-
export declare function reinstallOriginalDeps({ violators, monoRepoRootPath, runVirmatorShellCommand, }: {
|
|
167
|
-
violators: ReadonlyArray<RecentDepViolator>;
|
|
168
|
-
monoRepoRootPath: string;
|
|
169
|
-
runVirmatorShellCommand: (command: string, options: {
|
|
170
|
-
cwd: string;
|
|
171
|
-
}, extraOptions: Partial<ExtraRunShellCommandOptions>) => Promise<unknown>;
|
|
172
|
-
}): Promise<void>;
|
|
66
|
+
io?: RegenExcludesIo | undefined;
|
|
67
|
+
}): Promise<string[]>;
|
|
173
68
|
/**
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
69
|
+
* Builds the `--min-release-age-exclude='<pattern>'` flags appended to the regen `npm i` so the
|
|
70
|
+
* allow-listed packages can install their newest versions even while a release-age window is set.
|
|
71
|
+
* Each pattern is single-quoted; combined with {@link isSafeExcludePattern} validation, this
|
|
72
|
+
* prevents shell injection from config values.
|
|
178
73
|
*/
|
|
179
|
-
export declare function
|
|
180
|
-
violators: ReadonlyArray<RecentDepViolator>;
|
|
181
|
-
updateVersions?: RecentDepsIo['updatePackageJsonVersions'] | undefined;
|
|
182
|
-
}): Promise<void>;
|
|
74
|
+
export declare function buildMinReleaseAgeExcludeFlags(patterns: ReadonlyArray<string>): string[];
|
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
import { check } from '@augment-vir/assert';
|
|
2
|
-
import {
|
|
3
|
-
import { listAllDirectNpmDeps, runShellCommand, } from '@augment-vir/node';
|
|
2
|
+
import { removeDuplicates, wrapInTry } from '@augment-vir/common';
|
|
4
3
|
import { JsModuleType, VirmatorNoTraceError, withImportedTsFile, } from '@virmator/core';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { dirname, join, relative, resolve } from 'node:path';
|
|
8
|
-
import { installFlagsByDepKey } from './install-flags.js';
|
|
4
|
+
import { stat } from 'node:fs/promises';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
9
6
|
const defaultDepsRegenConfigRelativePath = join('configs', 'deps-regen.config.ts');
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
7
|
+
/**
|
|
8
|
+
* All `node_modules` directories deleted before a regen install: one per mono-repo package plus the
|
|
9
|
+
* mono-repo root. For a single (non-mono) package, `monoRepoPackages` is empty so only the root is
|
|
10
|
+
* returned.
|
|
11
|
+
*/
|
|
12
|
+
export function listRegenNodeModulesDirs({ monoRepoRootPath, monoRepoPackages, }) {
|
|
13
|
+
return [
|
|
14
|
+
...monoRepoPackages.map((monoPackage) => join(monoRepoRootPath, monoPackage.relativePath, 'node_modules')),
|
|
15
|
+
join(monoRepoRootPath, 'node_modules'),
|
|
16
|
+
];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Whether an allow-list entry is safe to interpolate (single-quoted) into a shell command. Allows
|
|
20
|
+
* npm package names and `minimatch` glob patterns (the `*` wildcard) while rejecting anything that
|
|
21
|
+
* could smuggle shell metacharacters or quotes out of an (untrusted) config file.
|
|
22
|
+
*/
|
|
23
|
+
export function isSafeExcludePattern(pattern) {
|
|
24
|
+
return /^@?[a-z0-9*][a-z0-9._*-]*(\/[a-z0-9*][a-z0-9._*-]*)?$/i.test(pattern);
|
|
18
25
|
}
|
|
19
26
|
/**
|
|
20
27
|
* Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
|
|
@@ -71,27 +78,6 @@ export function resolveRegenConfigPath({ configValue, cwd, monoRepoRootPath, })
|
|
|
71
78
|
? resolve(cwd, configValue)
|
|
72
79
|
: join(monoRepoRootPath, defaultDepsRegenConfigRelativePath);
|
|
73
80
|
}
|
|
74
|
-
/** Parses the output of `npm config get min-release-age` into a positive day count, or `undefined`. */
|
|
75
|
-
export function parseMinReleaseAgeDays(rawValue) {
|
|
76
|
-
const days = Number(rawValue.trim());
|
|
77
|
-
return Number.isFinite(days) && days > 0 ? days : undefined;
|
|
78
|
-
}
|
|
79
|
-
/* node:coverage disable -- thin wrapper around the npm CLI; parsing lives in parseMinReleaseAgeDays */
|
|
80
|
-
/**
|
|
81
|
-
* Returns the effective `min-release-age` (in days) as resolved by npm across all config sources
|
|
82
|
-
* (project `.npmrc` overriding user, overriding global), or `undefined` if it is unset or
|
|
83
|
-
* non-positive.
|
|
84
|
-
*/
|
|
85
|
-
export async function getMinReleaseAgeDays(monoRepoRootPath) {
|
|
86
|
-
const result = await runShellCommand('npm config get min-release-age', {
|
|
87
|
-
cwd: monoRepoRootPath,
|
|
88
|
-
});
|
|
89
|
-
if (result.exitCode) {
|
|
90
|
-
return undefined;
|
|
91
|
-
}
|
|
92
|
-
return parseMinReleaseAgeDays(result.stdout);
|
|
93
|
-
}
|
|
94
|
-
/* node:coverage enable */
|
|
95
81
|
export async function fileExists(filePath) {
|
|
96
82
|
return await wrapInTry(async () => {
|
|
97
83
|
await stat(filePath);
|
|
@@ -105,242 +91,22 @@ export async function loadAllowList(configPath) {
|
|
|
105
91
|
inputPath: configPath,
|
|
106
92
|
}, JsModuleType.Esm, (loadedConfig) => {
|
|
107
93
|
const list = loadedConfig.depsRegenAllowList ?? loadedConfig.default;
|
|
108
|
-
return check.isArray(list) ? list : undefined;
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
/** Parses the JSON time map output of `npm view <pkg> time --json` into a {@link RegistryInfo}. */
|
|
112
|
-
export function parseRegistryTime(stdout) {
|
|
113
|
-
const parsed = wrapInTry(() => JSON.parse(stdout), {
|
|
114
|
-
fallbackValue: undefined,
|
|
115
|
-
});
|
|
116
|
-
if (!check.isObject(parsed)) {
|
|
117
|
-
return undefined;
|
|
118
|
-
}
|
|
119
|
-
return {
|
|
120
|
-
time: parsed,
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Parses the JSON output of `npm view <pkg>@<range> version --json` into the newest matching
|
|
125
|
-
* version (the last entry, since npm sorts ascending), or `undefined` if nothing matched / the
|
|
126
|
-
* output was unusable.
|
|
127
|
-
*/
|
|
128
|
-
export function parseResolvedVersion(stdout) {
|
|
129
|
-
const parsed = wrapInTry(() => JSON.parse(stdout), {
|
|
130
|
-
fallbackValue: undefined,
|
|
131
|
-
});
|
|
132
|
-
const newest = check.isArray(parsed) ? parsed[parsed.length - 1] : parsed;
|
|
133
|
-
return check.isString(newest) ? newest : undefined;
|
|
134
|
-
}
|
|
135
|
-
/* node:coverage disable -- thin network wrappers around the npm registry; parsing lives in the parse* helpers */
|
|
136
|
-
async function queryRegistry(depName, cwd) {
|
|
137
|
-
const result = await runShellCommand(`npm view '${depName}' time --json`, {
|
|
138
|
-
cwd,
|
|
139
|
-
});
|
|
140
|
-
if (result.exitCode) {
|
|
141
|
-
return undefined;
|
|
142
|
-
}
|
|
143
|
-
return parseRegistryTime(result.stdout);
|
|
144
|
-
}
|
|
145
|
-
async function queryResolvedVersion(depName, range, cwd) {
|
|
146
|
-
const result = await runShellCommand(`npm view '${depName}@${range}' version --json`, {
|
|
147
|
-
cwd,
|
|
148
|
-
});
|
|
149
|
-
if (result.exitCode) {
|
|
150
|
-
return undefined;
|
|
151
|
-
}
|
|
152
|
-
return parseResolvedVersion(result.stdout);
|
|
153
|
-
}
|
|
154
|
-
/* node:coverage enable */
|
|
155
|
-
/** Whether a dependency name matches any allow-list entry (exact string or RegExp pattern). */
|
|
156
|
-
function matchesAllowList(allowList, depName) {
|
|
157
|
-
return allowList.some((entry) => entry instanceof RegExp ? entry.test(depName) : entry === depName);
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Splits a version range value into its leading prefix and a clean `x.y.z` version, if possible.
|
|
161
|
-
* The prefix is restricted to known semver range operators so that values read out of an
|
|
162
|
-
* (untrusted) `package.json` cannot smuggle shell metacharacters through as a "prefix".
|
|
163
|
-
*/
|
|
164
|
-
function parseVersionValue(versionValue) {
|
|
165
|
-
const match = /^(>=|<=|>|<|\^|~|=|v)?(\d+\.\d+\.\d+)\s*$/i.exec(versionValue);
|
|
166
|
-
if (!match?.[2]) {
|
|
167
|
-
return undefined;
|
|
168
|
-
}
|
|
169
|
-
return {
|
|
170
|
-
prefix: match[1] || '',
|
|
171
|
-
version: match[2],
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
/** Whether the given publish date is more recent than `threshold` (the min-release-age cutoff). */
|
|
175
|
-
function isVersionTooRecent(publishDateString, threshold) {
|
|
176
|
-
if (!publishDateString || !isValidIsoString(publishDateString)) {
|
|
177
|
-
return false;
|
|
178
|
-
}
|
|
179
|
-
return isDateAfter({
|
|
180
|
-
fullDate: createUtcFullDate(publishDateString),
|
|
181
|
-
relativeTo: threshold,
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
/** Finds the most recently published stable version that is no newer than `threshold`. */
|
|
185
|
-
function findMostRecentSafeVersion(time, threshold) {
|
|
186
|
-
const safeVersions = getObjectTypedEntries(time)
|
|
187
|
-
.filter(([version, dateString,]) => /^\d+\.\d+\.\d+$/.test(version) && isValidIsoString(dateString))
|
|
188
|
-
.map(([version, dateString,]) => {
|
|
189
|
-
return {
|
|
190
|
-
version,
|
|
191
|
-
date: createUtcFullDate(dateString),
|
|
192
|
-
};
|
|
193
|
-
})
|
|
194
|
-
.filter(({ date }) => !isDateAfter({
|
|
195
|
-
fullDate: date,
|
|
196
|
-
relativeTo: threshold,
|
|
197
|
-
}));
|
|
198
|
-
if (!safeVersions.length) {
|
|
199
|
-
return undefined;
|
|
200
|
-
}
|
|
201
|
-
return safeVersions.reduce((mostRecent, current) => isDateAfter({
|
|
202
|
-
fullDate: current.date,
|
|
203
|
-
relativeTo: mostRecent.date,
|
|
204
|
-
})
|
|
205
|
-
? current
|
|
206
|
-
: mostRecent).version;
|
|
207
|
-
}
|
|
208
|
-
/** Reads, mutates the given dependency versions in, and re-writes a `package.json` file in place. */
|
|
209
|
-
export async function updatePackageJsonVersions(packageJsonPath, updates) {
|
|
210
|
-
const originalContents = await readFile(packageJsonPath, 'utf8');
|
|
211
|
-
const indent = /\n([ \t]+)\S/.exec(originalContents)?.[1] || ' ';
|
|
212
|
-
const trailingNewLine = originalContents.endsWith('\n') ? '\n' : '';
|
|
213
|
-
const parsed = JSON.parse(originalContents);
|
|
214
|
-
updates.forEach(({ dependencyKey, depName, version }) => {
|
|
215
|
-
const section = parsed[dependencyKey];
|
|
216
|
-
if (check.isObject(section) && depName in section) {
|
|
217
|
-
section[depName] = version;
|
|
218
|
-
}
|
|
219
|
-
});
|
|
220
|
-
await writeFile(packageJsonPath, JSON.stringify(parsed, undefined, indent) + trailingNewLine);
|
|
221
|
-
}
|
|
222
|
-
/** Groups violators by their `package.json` path so each file is written exactly once. */
|
|
223
|
-
function groupByPackageJson(violators) {
|
|
224
|
-
return violators.reduce((accum, violator) => {
|
|
225
|
-
const existing = accum.get(violator.packageJsonPath) ?? [];
|
|
226
|
-
accum.set(violator.packageJsonPath, [
|
|
227
|
-
...existing,
|
|
228
|
-
violator,
|
|
229
|
-
]);
|
|
230
|
-
return accum;
|
|
231
|
-
}, new Map());
|
|
232
|
-
}
|
|
233
|
-
/**
|
|
234
|
-
* Drops workspace-internal deps, non-installable sections (e.g. `overrides`), and any dependency
|
|
235
|
-
* whose name is not a safe npm package name (the latter both as a correctness guard and to prevent
|
|
236
|
-
* shell injection when the name is later passed to npm). Grouped by name.
|
|
237
|
-
*/
|
|
238
|
-
export function getCandidateDepUsages(allDirectDeps) {
|
|
239
|
-
return getObjectTypedEntries(allDirectDeps)
|
|
240
|
-
.filter(([depName]) => isSafePackageName(depName))
|
|
241
|
-
.map(([depName, usages,]) => {
|
|
242
|
-
return {
|
|
243
|
-
depName,
|
|
244
|
-
usages: usages.filter((usage) => !usage.isWorkspace &&
|
|
245
|
-
installFlagsByDepKey[usage.dependencyKey] != undefined),
|
|
246
|
-
};
|
|
247
|
-
})
|
|
248
|
-
.filter(({ usages }) => usages.length);
|
|
249
|
-
}
|
|
250
|
-
/** The lookup key for a specific dependency range (or version). */
|
|
251
|
-
export function depRangeKey(depName, range) {
|
|
252
|
-
return `${depName}@${range}`;
|
|
253
|
-
}
|
|
254
|
-
/** The simple range (prefix + `x.y.z`) reconstructed from a usage's version value, if parseable. */
|
|
255
|
-
function rangeOfUsage(versionValue) {
|
|
256
|
-
const parsedVersion = parseVersionValue(versionValue);
|
|
257
|
-
return parsedVersion ? `${parsedVersion.prefix}${parsedVersion.version}` : undefined;
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Returns the `{depName, range}` pairs whose newest-in-range version must be resolved (to check
|
|
261
|
-
* recency against the version that will actually be installed): only for allow-list-matched
|
|
262
|
-
* candidates with a parseable range. Deduped.
|
|
263
|
-
*/
|
|
264
|
-
export function getResolveTargets(candidateUsages, allowList) {
|
|
265
|
-
const targets = new Map();
|
|
266
|
-
candidateUsages.forEach(({ depName, usages }) => {
|
|
267
|
-
if (!matchesAllowList(allowList, depName)) {
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
usages.forEach((usage) => {
|
|
271
|
-
const range = rangeOfUsage(usage.versionValue);
|
|
272
|
-
if (range != undefined) {
|
|
273
|
-
targets.set(depRangeKey(depName, range), {
|
|
274
|
-
depName,
|
|
275
|
-
range,
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
});
|
|
279
|
-
});
|
|
280
|
-
return Array.from(targets.values());
|
|
281
|
-
}
|
|
282
|
-
/**
|
|
283
|
-
* Pure detection of every direct dependency usage that both matches the allow list and pins a
|
|
284
|
-
* version too recent for the min-release-age threshold, paired with the safe version it should be
|
|
285
|
-
* temporarily downgraded to.
|
|
286
|
-
*/
|
|
287
|
-
export function computeRecentDepViolators({ candidateUsages, allowList, registryByName, resolvedByRange, threshold, }) {
|
|
288
|
-
return candidateUsages.flatMap(({ depName, usages }) => {
|
|
289
|
-
const registry = registryByName.get(depName);
|
|
290
|
-
if (!registry || !matchesAllowList(allowList, depName)) {
|
|
291
|
-
return [];
|
|
292
|
-
}
|
|
293
|
-
return usages.flatMap((usage) => {
|
|
294
|
-
const parsedVersion = parseVersionValue(usage.versionValue);
|
|
295
|
-
if (!parsedVersion) {
|
|
296
|
-
return [];
|
|
297
|
-
}
|
|
298
|
-
const range = `${parsedVersion.prefix}${parsedVersion.version}`;
|
|
299
|
-
const resolvedVersion = resolvedByRange.get(depRangeKey(depName, range));
|
|
300
|
-
if (!resolvedVersion ||
|
|
301
|
-
!isVersionTooRecent(registry.time[resolvedVersion], threshold)) {
|
|
302
|
-
return [];
|
|
303
|
-
}
|
|
304
|
-
const safeVersion = findMostRecentSafeVersion(registry.time, threshold);
|
|
305
|
-
if (!safeVersion) {
|
|
306
|
-
return [];
|
|
307
|
-
}
|
|
308
|
-
return [
|
|
309
|
-
{
|
|
310
|
-
packageJsonPath: usage.requiredBy,
|
|
311
|
-
packageDir: dirname(usage.requiredBy),
|
|
312
|
-
dependencyKey: usage.dependencyKey,
|
|
313
|
-
depName,
|
|
314
|
-
originalVersionValue: usage.versionValue,
|
|
315
|
-
versionPrefix: parsedVersion.prefix,
|
|
316
|
-
safeVersion,
|
|
317
|
-
},
|
|
318
|
-
];
|
|
319
|
-
});
|
|
94
|
+
return check.isArray(list) ? list.filter(check.isString) : undefined;
|
|
320
95
|
});
|
|
321
96
|
}
|
|
322
|
-
/** The real
|
|
323
|
-
export const
|
|
97
|
+
/** The real (filesystem) IO used by {@link resolveRegenExcludes}. */
|
|
98
|
+
export const defaultRegenExcludesIo = {
|
|
324
99
|
fileExists,
|
|
325
100
|
loadAllowList,
|
|
326
|
-
listDirectDeps: listAllDirectNpmDeps,
|
|
327
|
-
queryRegistry,
|
|
328
|
-
queryResolvedVersion,
|
|
329
|
-
updatePackageJsonVersions,
|
|
330
101
|
};
|
|
331
102
|
/**
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
336
|
-
* via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
|
|
337
|
-
* regeneration.
|
|
103
|
+
* Loads the deps-regen allow list and returns the deduped package names / glob patterns that should
|
|
104
|
+
* bypass `min-release-age` during the regen install. A missing explicit config (from `--config`)
|
|
105
|
+
* throws; a missing default config is silently skipped (returns `[]`). Unsafe entries (which can't
|
|
106
|
+
* be safely interpolated into a shell command) throw rather than being silently dropped.
|
|
338
107
|
*/
|
|
339
|
-
export async function
|
|
340
|
-
if (!
|
|
341
|
-
return [];
|
|
342
|
-
}
|
|
343
|
-
else if (!(await io.fileExists(configPath))) {
|
|
108
|
+
export async function resolveRegenExcludes({ configPath, configIsExplicit, io = defaultRegenExcludesIo, }) {
|
|
109
|
+
if (!(await io.fileExists(configPath))) {
|
|
344
110
|
if (configIsExplicit) {
|
|
345
111
|
throw new VirmatorNoTraceError(`deps-regen config file not found: ${configPath}`);
|
|
346
112
|
}
|
|
@@ -350,94 +116,18 @@ export async function prepareRecentDepDowngrades({ monoRepoRootPath, configPath,
|
|
|
350
116
|
if (!allowList?.length) {
|
|
351
117
|
return [];
|
|
352
118
|
}
|
|
353
|
-
const
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
/** The `time` map is only needed for deps that have a resolve target (a potential violator). */
|
|
359
|
-
const registryByName = new Map(await awaitedBlockingMap(removeDuplicates(resolveTargets.map(({ depName }) => depName)), async (depName) => [
|
|
360
|
-
depName,
|
|
361
|
-
await io.queryRegistry(depName, monoRepoRootPath),
|
|
362
|
-
]));
|
|
363
|
-
const resolvedByRange = new Map(await awaitedBlockingMap(resolveTargets, async ({ depName, range }) => [
|
|
364
|
-
depRangeKey(depName, range),
|
|
365
|
-
await io.queryResolvedVersion(depName, range, monoRepoRootPath),
|
|
366
|
-
]));
|
|
367
|
-
const violators = computeRecentDepViolators({
|
|
368
|
-
candidateUsages,
|
|
369
|
-
allowList,
|
|
370
|
-
registryByName,
|
|
371
|
-
resolvedByRange,
|
|
372
|
-
threshold,
|
|
373
|
-
});
|
|
374
|
-
await awaitedBlockingMap(Array.from(groupByPackageJson(violators).entries()), async ([packageJsonPath, packageViolators,]) => {
|
|
375
|
-
packageViolators.forEach((violator) => {
|
|
376
|
-
log.faint(`Temporarily downgrading ${violator.depName} from ${violator.originalVersionValue} to ${violator.versionPrefix}${violator.safeVersion} for regen.`);
|
|
377
|
-
});
|
|
378
|
-
await io.updatePackageJsonVersions(packageJsonPath, packageViolators.map((violator) => {
|
|
379
|
-
return {
|
|
380
|
-
dependencyKey: violator.dependencyKey,
|
|
381
|
-
depName: violator.depName,
|
|
382
|
-
version: `${violator.versionPrefix}${violator.safeVersion}`,
|
|
383
|
-
};
|
|
384
|
-
}));
|
|
385
|
-
});
|
|
386
|
-
return violators;
|
|
387
|
-
}
|
|
388
|
-
/**
|
|
389
|
-
* Re-installs each downgraded dependency at its original version, bypassing min-release-age.
|
|
390
|
-
* Installs are grouped per package directory and per dependency type (`-D`, `--save-peer`, or none)
|
|
391
|
-
* so each `npm i` runs in the correct location (sub-packages and/or the mono-repo root). Each
|
|
392
|
-
* install spec is single-quoted; combined with the package-name and version validation done while
|
|
393
|
-
* detecting violators, this prevents shell injection from `package.json` values.
|
|
394
|
-
*/
|
|
395
|
-
export async function reinstallOriginalDeps({ violators, monoRepoRootPath, runVirmatorShellCommand, }) {
|
|
396
|
-
const byPackageAndKey = violators.reduce((accum, violator) => {
|
|
397
|
-
const byKey = accum.get(violator.packageDir) ?? new Map();
|
|
398
|
-
const existing = byKey.get(violator.dependencyKey) ?? [];
|
|
399
|
-
byKey.set(violator.dependencyKey, [
|
|
400
|
-
...existing,
|
|
401
|
-
violator,
|
|
402
|
-
]);
|
|
403
|
-
accum.set(violator.packageDir, byKey);
|
|
404
|
-
return accum;
|
|
405
|
-
}, new Map());
|
|
406
|
-
await awaitedBlockingMap(Array.from(byPackageAndKey.entries()), async ([packageDir, byKey,]) => {
|
|
407
|
-
await awaitedBlockingMap(Array.from(byKey.entries()), async ([dependencyKey, keyViolators,]) => {
|
|
408
|
-
const flag = installFlagsByDepKey[dependencyKey];
|
|
409
|
-
const command = [
|
|
410
|
-
'npm',
|
|
411
|
-
'i',
|
|
412
|
-
flag,
|
|
413
|
-
...keyViolators.map((violator) => `'${violator.depName}@${violator.originalVersionValue.trim()}'`),
|
|
414
|
-
'--min-release-age=0',
|
|
415
|
-
]
|
|
416
|
-
.filter(check.isTruthy)
|
|
417
|
-
.join(' ');
|
|
418
|
-
await runVirmatorShellCommand(command, {
|
|
419
|
-
cwd: packageDir,
|
|
420
|
-
}, {
|
|
421
|
-
logPrefix: relative(monoRepoRootPath, packageDir) || '.',
|
|
422
|
-
prefixCommandOnly: true,
|
|
423
|
-
});
|
|
424
|
-
});
|
|
425
|
-
});
|
|
119
|
+
const unsafePatterns = allowList.filter((pattern) => !isSafeExcludePattern(pattern));
|
|
120
|
+
if (unsafePatterns.length) {
|
|
121
|
+
throw new VirmatorNoTraceError(`deps-regen allow list contains unsafe package patterns: ${unsafePatterns.join(', ')}`);
|
|
122
|
+
}
|
|
123
|
+
return removeDuplicates([...allowList]);
|
|
426
124
|
}
|
|
427
125
|
/**
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
126
|
+
* Builds the `--min-release-age-exclude='<pattern>'` flags appended to the regen `npm i` so the
|
|
127
|
+
* allow-listed packages can install their newest versions even while a release-age window is set.
|
|
128
|
+
* Each pattern is single-quoted; combined with {@link isSafeExcludePattern} validation, this
|
|
129
|
+
* prevents shell injection from config values.
|
|
432
130
|
*/
|
|
433
|
-
export
|
|
434
|
-
|
|
435
|
-
await updateVersions(packageJsonPath, packageViolators.map((violator) => {
|
|
436
|
-
return {
|
|
437
|
-
dependencyKey: violator.dependencyKey,
|
|
438
|
-
depName: violator.depName,
|
|
439
|
-
version: violator.originalVersionValue,
|
|
440
|
-
};
|
|
441
|
-
}));
|
|
442
|
-
});
|
|
131
|
+
export function buildMinReleaseAgeExcludeFlags(patterns) {
|
|
132
|
+
return patterns.map((pattern) => `--min-release-age-exclude='${pattern}'`);
|
|
443
133
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type NpmDeps, type PackageJsonDependencyKey } from '@augment-vir/node';
|
|
2
|
+
import { type ExtraRunShellCommandOptions } from '@virmator/core';
|
|
3
|
+
/** The matched, installable direct deps to upgrade, grouped by package directory and dep section. */
|
|
4
|
+
export type UpgradeMatches = Record<string, Partial<Record<PackageJsonDependencyKey, string[]>>>;
|
|
5
|
+
/**
|
|
6
|
+
* Whether a dependency name is a safe npm package name to interpolate (single-quoted) into a shell
|
|
7
|
+
* command. Restricting names read out of an (untrusted) `package.json` to this shape guarantees
|
|
8
|
+
* they cannot contain shell metacharacters or quotes.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isSafePackageName(depName: string): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* The subset of a plugin's `runShellCommand` used to run upgrade installs. Loosely typed so the
|
|
13
|
+
* plugin-provided implementation is assignable.
|
|
14
|
+
*/
|
|
15
|
+
export type RunUpgradeShellCommand = (command: string, options: {
|
|
16
|
+
cwd: string;
|
|
17
|
+
}, extraOptions: Partial<ExtraRunShellCommandOptions>) => Promise<unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* Splits a `deps upgrade` pattern into its name pattern and version specifier. The first `@` in a
|
|
20
|
+
* scoped name like `@augment-vir/*` is part of the name, so only a non-leading `@` separates the
|
|
21
|
+
* name from the version. A missing version defaults to `latest`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function splitUpgradePattern(depPattern: string): {
|
|
24
|
+
namePattern: string;
|
|
25
|
+
versionSpecifier: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Finds every direct dependency usage whose name matches `namePattern` and which is installable
|
|
29
|
+
* (not a workspace dep, not a non-installable section like `overrides`), grouped by the
|
|
30
|
+
* `package.json` directory and dependency section so each install runs in the right place.
|
|
31
|
+
*/
|
|
32
|
+
export declare function buildUpgradeMatches({ allDirectDeps, namePattern, }: {
|
|
33
|
+
allDirectDeps: Readonly<NpmDeps>;
|
|
34
|
+
namePattern: string;
|
|
35
|
+
}): UpgradeMatches;
|
|
36
|
+
/**
|
|
37
|
+
* Builds the `npm i` command that installs the given deps at the requested version. Each
|
|
38
|
+
* `<name>@<version>` spec is single-quoted; combined with the {@link isSafePackageName} validation
|
|
39
|
+
* done while matching and the version-specifier validation in {@link runArgBasedUpgrade}, this
|
|
40
|
+
* prevents shell injection from `package.json` names or the CLI version argument.
|
|
41
|
+
*/
|
|
42
|
+
export declare function buildUpgradeInstallCommand({ flag, passthroughArgs, depNames, versionSpecifier, }: {
|
|
43
|
+
flag: string;
|
|
44
|
+
passthroughArgs: ReadonlyArray<string>;
|
|
45
|
+
depNames: ReadonlyArray<string>;
|
|
46
|
+
versionSpecifier: string;
|
|
47
|
+
}): string;
|
|
48
|
+
/**
|
|
49
|
+
* Runs the argument-based `deps upgrade` path: matches direct deps against `depPattern` across the
|
|
50
|
+
* mono-repo (or single package), then installs each matched group at the requested version in its
|
|
51
|
+
* own package directory. Throws when nothing matches.
|
|
52
|
+
*/
|
|
53
|
+
export declare function runArgBasedUpgrade({ depPattern, filteredArgs, monoRepoRootPath, runShellCommand, listDirectDeps, }: {
|
|
54
|
+
depPattern: string;
|
|
55
|
+
filteredArgs: ReadonlyArray<string>;
|
|
56
|
+
monoRepoRootPath: string;
|
|
57
|
+
runShellCommand: RunUpgradeShellCommand;
|
|
58
|
+
listDirectDeps?: ((rootPath: string) => Promise<NpmDeps>) | undefined;
|
|
59
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { awaitedBlockingMap, getObjectTypedEntries } from '@augment-vir/common';
|
|
3
|
+
import { listAllDirectNpmDeps } from '@augment-vir/node';
|
|
4
|
+
import { VirmatorNoTraceError } from '@virmator/core';
|
|
5
|
+
import { dirname, matchesGlob, relative } from 'node:path';
|
|
6
|
+
import { installFlagsByDepKey } from './install-flags.js';
|
|
7
|
+
/**
|
|
8
|
+
* Whether a dependency name is a safe npm package name to interpolate (single-quoted) into a shell
|
|
9
|
+
* command. Restricting names read out of an (untrusted) `package.json` to this shape guarantees
|
|
10
|
+
* they cannot contain shell metacharacters or quotes.
|
|
11
|
+
*/
|
|
12
|
+
export function isSafePackageName(depName) {
|
|
13
|
+
return /^@?[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)?$/i.test(depName);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Splits a `deps upgrade` pattern into its name pattern and version specifier. The first `@` in a
|
|
17
|
+
* scoped name like `@augment-vir/*` is part of the name, so only a non-leading `@` separates the
|
|
18
|
+
* name from the version. A missing version defaults to `latest`.
|
|
19
|
+
*/
|
|
20
|
+
export function splitUpgradePattern(depPattern) {
|
|
21
|
+
const lastAtIndex = depPattern.lastIndexOf('@');
|
|
22
|
+
return {
|
|
23
|
+
namePattern: lastAtIndex > 0 ? depPattern.slice(0, lastAtIndex) : depPattern,
|
|
24
|
+
versionSpecifier: lastAtIndex > 0 ? depPattern.slice(lastAtIndex + 1) : 'latest',
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Finds every direct dependency usage whose name matches `namePattern` and which is installable
|
|
29
|
+
* (not a workspace dep, not a non-installable section like `overrides`), grouped by the
|
|
30
|
+
* `package.json` directory and dependency section so each install runs in the right place.
|
|
31
|
+
*/
|
|
32
|
+
export function buildUpgradeMatches({ allDirectDeps, namePattern, }) {
|
|
33
|
+
return getObjectTypedEntries(allDirectDeps).reduce((accum, [depName, usages,]) => {
|
|
34
|
+
if (!isSafePackageName(depName) || !matchesGlob(depName, namePattern)) {
|
|
35
|
+
return accum;
|
|
36
|
+
}
|
|
37
|
+
return usages.reduce((innerAccumulator, usage) => {
|
|
38
|
+
if (usage.isWorkspace || installFlagsByDepKey[usage.dependencyKey] == undefined) {
|
|
39
|
+
return innerAccumulator;
|
|
40
|
+
}
|
|
41
|
+
const packageDir = dirname(usage.requiredBy);
|
|
42
|
+
const existingDepsByKey = innerAccumulator[packageDir] ?? {};
|
|
43
|
+
const existingDeps = existingDepsByKey[usage.dependencyKey] ?? [];
|
|
44
|
+
return {
|
|
45
|
+
...innerAccumulator,
|
|
46
|
+
[packageDir]: {
|
|
47
|
+
...existingDepsByKey,
|
|
48
|
+
[usage.dependencyKey]: [
|
|
49
|
+
...existingDeps,
|
|
50
|
+
depName,
|
|
51
|
+
],
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}, accum);
|
|
55
|
+
}, {});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Builds the `npm i` command that installs the given deps at the requested version. Each
|
|
59
|
+
* `<name>@<version>` spec is single-quoted; combined with the {@link isSafePackageName} validation
|
|
60
|
+
* done while matching and the version-specifier validation in {@link runArgBasedUpgrade}, this
|
|
61
|
+
* prevents shell injection from `package.json` names or the CLI version argument.
|
|
62
|
+
*/
|
|
63
|
+
export function buildUpgradeInstallCommand({ flag, passthroughArgs, depNames, versionSpecifier, }) {
|
|
64
|
+
return [
|
|
65
|
+
'npm',
|
|
66
|
+
'i',
|
|
67
|
+
flag,
|
|
68
|
+
...passthroughArgs,
|
|
69
|
+
...depNames.map((depName) => `'${depName}@${versionSpecifier}'`),
|
|
70
|
+
]
|
|
71
|
+
.filter(check.isTruthy)
|
|
72
|
+
.join(' ');
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Runs the argument-based `deps upgrade` path: matches direct deps against `depPattern` across the
|
|
76
|
+
* mono-repo (or single package), then installs each matched group at the requested version in its
|
|
77
|
+
* own package directory. Throws when nothing matches.
|
|
78
|
+
*/
|
|
79
|
+
export async function runArgBasedUpgrade({ depPattern, filteredArgs, monoRepoRootPath, runShellCommand, listDirectDeps = listAllDirectNpmDeps, }) {
|
|
80
|
+
const passthroughArgs = filteredArgs.toSpliced(filteredArgs.indexOf(depPattern), 1);
|
|
81
|
+
const { namePattern, versionSpecifier } = splitUpgradePattern(depPattern);
|
|
82
|
+
/**
|
|
83
|
+
* The version is interpolated single-quoted into the install command, so a literal single quote
|
|
84
|
+
* is the only character that could break out of the quoting. Reject it rather than risk shell
|
|
85
|
+
* injection from the CLI argument.
|
|
86
|
+
*/
|
|
87
|
+
if (versionSpecifier.includes("'")) {
|
|
88
|
+
throw new VirmatorNoTraceError(`Invalid version specifier in upgrade target '${depPattern}'.`);
|
|
89
|
+
}
|
|
90
|
+
const matches = getObjectTypedEntries(buildUpgradeMatches({
|
|
91
|
+
allDirectDeps: await listDirectDeps(monoRepoRootPath),
|
|
92
|
+
namePattern,
|
|
93
|
+
}));
|
|
94
|
+
if (!matches.length) {
|
|
95
|
+
throw new VirmatorNoTraceError(`No direct dependencies matching '${depPattern}' found in any package.json.`);
|
|
96
|
+
}
|
|
97
|
+
await awaitedBlockingMap(matches, async ([packageDir, depsByKey,]) => {
|
|
98
|
+
await awaitedBlockingMap(getObjectTypedEntries(depsByKey), async ([dependencyKey, depNames,]) => {
|
|
99
|
+
const flag = installFlagsByDepKey[dependencyKey];
|
|
100
|
+
/**
|
|
101
|
+
* Defensive guard: `buildUpgradeMatches` already drops entries whose dep key
|
|
102
|
+
* maps to an undefined flag, so this branch is unreachable in practice.
|
|
103
|
+
*/
|
|
104
|
+
/* node:coverage ignore next 3 */
|
|
105
|
+
if (flag == undefined) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
await runShellCommand(buildUpgradeInstallCommand({
|
|
109
|
+
flag,
|
|
110
|
+
passthroughArgs,
|
|
111
|
+
depNames,
|
|
112
|
+
versionSpecifier,
|
|
113
|
+
}), {
|
|
114
|
+
cwd: packageDir,
|
|
115
|
+
}, {
|
|
116
|
+
logPrefix: relative(monoRepoRootPath, packageDir) || '.',
|
|
117
|
+
prefixCommandOnly: true,
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@virmator/deps",
|
|
3
|
-
"version": "14.
|
|
3
|
+
"version": "14.24.0",
|
|
4
4
|
"description": "Default TS deps plugin for virmator.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"virmator",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"@augment-vir/common": "^31.71.3",
|
|
39
39
|
"@augment-vir/node": "^31.71.3",
|
|
40
40
|
"@npm/types": "^2.1.0",
|
|
41
|
-
"@virmator/core": "^14.
|
|
41
|
+
"@virmator/core": "^14.24.0",
|
|
42
42
|
"date-vir": "^8.3.2",
|
|
43
43
|
"mri": "^1.2.0"
|
|
44
44
|
},
|