@virmator/deps 14.21.3 → 14.23.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 +5 -0
- package/configs/deps-regen.config.base.ts +62 -0
- package/dist/deps.d.ts +8 -2
- package/dist/deps.js +81 -29
- package/dist/install-flags.d.ts +7 -0
- package/dist/install-flags.js +13 -0
- package/dist/regen-recent-deps.d.ts +182 -0
- package/dist/regen-recent-deps.js +443 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -47,5 +47,10 @@ 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
|
+
If npm's effective 'min-release-age' is set (resolved across project, user, and global config), any direct dependency that matches the deps-regen allow list but currently pins a too-recent version is temporarily downgraded to the most recent version that satisfies 'min-release-age' so the install succeeds. After regeneration, each such dependency is re-installed at its original version with '--min-release-age=0' (in its own package, or the mono-repo root) and its original 'package.json' version is restored.
|
|
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.
|
|
53
|
+
|
|
50
54
|
- Examples
|
|
51
55
|
- `virmator deps regen`
|
|
56
|
+
- use a custom deps-regen allow list: `virmator deps regen --config ./configs/deps-regen.config.ts`
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** These packages bypass min-release-age when running `virmator deps regen`. */
|
|
2
|
+
export type RecentDepsAllowList = ReadonlyArray<string | RegExp>;
|
|
3
|
+
|
|
4
|
+
const electrovirPackages: RecentDepsAllowList = [
|
|
5
|
+
/^@augment-vir\//,
|
|
6
|
+
/^@date-vir\//,
|
|
7
|
+
/^@electrovir\//,
|
|
8
|
+
/^@rest-vir\//,
|
|
9
|
+
/^@review-vir\//,
|
|
10
|
+
/^@updating-secrets\//,
|
|
11
|
+
/^@virmator\//,
|
|
12
|
+
'auth-vir',
|
|
13
|
+
'catch-exit',
|
|
14
|
+
'cli-vir',
|
|
15
|
+
'cron-vir',
|
|
16
|
+
'date-vir',
|
|
17
|
+
'deploy-vir',
|
|
18
|
+
'detect-activity',
|
|
19
|
+
'docker-vir',
|
|
20
|
+
'element-book',
|
|
21
|
+
'element-vir',
|
|
22
|
+
'execute-in-browser',
|
|
23
|
+
'i18n-vir',
|
|
24
|
+
'istanbul-smart-text-reporter',
|
|
25
|
+
'lit-css-vars',
|
|
26
|
+
'local-db-client',
|
|
27
|
+
'markdown-code-example-inserter',
|
|
28
|
+
'mock-vir',
|
|
29
|
+
'mono-vir',
|
|
30
|
+
'object-shape-tester',
|
|
31
|
+
'observavir',
|
|
32
|
+
'parse-email-address',
|
|
33
|
+
'pdf-vir',
|
|
34
|
+
'pglite-cli',
|
|
35
|
+
'prettier-plugin-interpolated-html-tags',
|
|
36
|
+
'prettier-plugin-multiline-arrays',
|
|
37
|
+
'prevent-navigation',
|
|
38
|
+
'prisma-pglite',
|
|
39
|
+
'prisma-vir',
|
|
40
|
+
'pull-request-vir',
|
|
41
|
+
'runstorm',
|
|
42
|
+
'schema-vir',
|
|
43
|
+
'sentry-vir',
|
|
44
|
+
'spa-router-vir',
|
|
45
|
+
'structured-render',
|
|
46
|
+
'theme-vir',
|
|
47
|
+
'tidy-tsc',
|
|
48
|
+
'typed-event-target',
|
|
49
|
+
'updating-secrets',
|
|
50
|
+
'url-vir',
|
|
51
|
+
'vira',
|
|
52
|
+
'virmator',
|
|
53
|
+
'web-snaps',
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The default allow list: electrovir's own commonly-used packages. Each entry matches a package by
|
|
58
|
+
* exact name (string) or by pattern (RegExp tested against the package name).
|
|
59
|
+
*/
|
|
60
|
+
export const baseAllowedRecentDeps: RecentDepsAllowList = [
|
|
61
|
+
...electrovirPackages,
|
|
62
|
+
];
|
package/dist/deps.d.ts
CHANGED
|
@@ -122,9 +122,12 @@ 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 "];
|
|
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 If npm's effective 'min-release-age' is set (resolved across\n project, user, and global config), any direct dependency that\n matches the deps-regen allow list but currently pins a too-recent\n version is temporarily downgraded to the most recent version that\n satisfies 'min-release-age' so the install succeeds. After\n regeneration, each such dependency is re-installed at its original\n version with '--min-release-age=0' (in its own package, or the\n mono-repo root) and its original 'package.json' version is\n restored.\n ", "\n The allow list defaults to 'configs/deps-regen.config.ts' (as\n placed by 'virmator init'); a missing default config is silently\n skipped. Override it with '--config <path>'; an explicitly-provided\n config that does not exist is an error.\n "];
|
|
126
126
|
readonly examples: readonly [{
|
|
127
127
|
readonly content: "virmator deps regen";
|
|
128
|
+
}, {
|
|
129
|
+
readonly title: "use a custom deps-regen allow list";
|
|
130
|
+
readonly content: "virmator deps regen --config ./configs/deps-regen.config.ts";
|
|
128
131
|
}];
|
|
129
132
|
};
|
|
130
133
|
};
|
|
@@ -253,9 +256,12 @@ export declare const virmatorDepsPlugin: Readonly<Readonly<{
|
|
|
253
256
|
};
|
|
254
257
|
readonly regen: {
|
|
255
258
|
readonly doc: {
|
|
256
|
-
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 "];
|
|
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 If npm's effective 'min-release-age' is set (resolved across\n project, user, and global config), any direct dependency that\n matches the deps-regen allow list but currently pins a too-recent\n version is temporarily downgraded to the most recent version that\n satisfies 'min-release-age' so the install succeeds. After\n regeneration, each such dependency is re-installed at its original\n version with '--min-release-age=0' (in its own package, or the\n mono-repo root) and its original 'package.json' version is\n restored.\n ", "\n The allow list defaults to 'configs/deps-regen.config.ts' (as\n placed by 'virmator init'); a missing default config is silently\n skipped. Override it with '--config <path>'; an explicitly-provided\n config that does not exist is an error.\n "];
|
|
257
260
|
readonly examples: readonly [{
|
|
258
261
|
readonly content: "virmator deps regen";
|
|
262
|
+
}, {
|
|
263
|
+
readonly title: "use a custom deps-regen allow list";
|
|
264
|
+
readonly content: "virmator deps regen --config ./configs/deps-regen.config.ts";
|
|
259
265
|
}];
|
|
260
266
|
};
|
|
261
267
|
};
|
package/dist/deps.js
CHANGED
|
@@ -1,17 +1,12 @@
|
|
|
1
1
|
import { check } from '@augment-vir/assert';
|
|
2
2
|
import { awaitedBlockingMap, getObjectTypedEntries, RuntimeEnv } from '@augment-vir/common';
|
|
3
|
-
import { listAllDirectNpmDeps,
|
|
3
|
+
import { listAllDirectNpmDeps, 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
7
|
import { dirname, join, matchesGlob, relative } from 'node:path';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
[PackageJsonDependencyKey.DevDependencies]: '-D',
|
|
11
|
-
[PackageJsonDependencyKey.PeerDependencies]: '--save-peer',
|
|
12
|
-
/** Not a real installable dep, just a resolution override. */
|
|
13
|
-
[PackageJsonDependencyKey.Overrides]: undefined,
|
|
14
|
-
};
|
|
8
|
+
import { installFlagsByDepKey } from './install-flags.js';
|
|
9
|
+
import { extractRegenConfigArg, getMinReleaseAgeDays, prepareRecentDepDowngrades, reinstallOriginalDeps, resolveRegenConfigPath, restoreOriginalPackageJsonVersions, } from './regen-recent-deps.js';
|
|
15
10
|
/** A virmator plugin for checking package TS dependencies. */
|
|
16
11
|
export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
17
12
|
name: 'Deps',
|
|
@@ -182,11 +177,32 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
|
182
177
|
node_modules directories and package-lock.json and then
|
|
183
178
|
running 'npm i'.
|
|
184
179
|
`,
|
|
180
|
+
`
|
|
181
|
+
If npm's effective 'min-release-age' is set (resolved across
|
|
182
|
+
project, user, and global config), any direct dependency that
|
|
183
|
+
matches the deps-regen allow list but currently pins a too-recent
|
|
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.
|
|
196
|
+
`,
|
|
185
197
|
],
|
|
186
198
|
examples: [
|
|
187
199
|
{
|
|
188
200
|
content: 'virmator deps regen',
|
|
189
201
|
},
|
|
202
|
+
{
|
|
203
|
+
title: 'use a custom deps-regen allow list',
|
|
204
|
+
content: 'virmator deps regen --config ./configs/deps-regen.config.ts',
|
|
205
|
+
},
|
|
190
206
|
],
|
|
191
207
|
},
|
|
192
208
|
},
|
|
@@ -334,29 +350,65 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
|
334
350
|
}
|
|
335
351
|
}
|
|
336
352
|
else if (usedCommands.deps?.subCommands.regen) {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
353
|
+
/** Strip '--config <path>' so it isn't forwarded to 'npm i'. */
|
|
354
|
+
const { configValue, passthroughArgs } = extractRegenConfigArg(filteredArgs);
|
|
355
|
+
/**
|
|
356
|
+
* Direct deps that match the allow list but pin a too-recent version are temporarily
|
|
357
|
+
* downgraded so the install below succeeds, then restored afterwards. When the repo has
|
|
358
|
+
* no 'min-release-age', this is a no-op.
|
|
359
|
+
*/
|
|
360
|
+
const recentDepViolators = await prepareRecentDepDowngrades({
|
|
361
|
+
monoRepoRootPath,
|
|
362
|
+
configPath: resolveRegenConfigPath({
|
|
363
|
+
configValue,
|
|
364
|
+
cwd,
|
|
365
|
+
monoRepoRootPath,
|
|
366
|
+
}),
|
|
367
|
+
configIsExplicit: check.isTruthy(configValue),
|
|
368
|
+
minReleaseAgeDays: await getMinReleaseAgeDays(monoRepoRootPath),
|
|
369
|
+
log,
|
|
370
|
+
});
|
|
371
|
+
try {
|
|
372
|
+
const allNodeModulesDirectories = [
|
|
373
|
+
...monoRepoPackages.map((monoPackage) => join(monoRepoRootPath, monoPackage.relativePath, 'node_modules')),
|
|
374
|
+
join(monoRepoRootPath, 'node_modules'),
|
|
375
|
+
];
|
|
376
|
+
await awaitedBlockingMap(allNodeModulesDirectories, async (path) => {
|
|
377
|
+
log.faint(`Removing ${relative(monoRepoRootPath, path)}...`);
|
|
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'), {
|
|
344
385
|
force: true,
|
|
345
|
-
recursive: true,
|
|
346
386
|
});
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
387
|
+
const installCommand = [
|
|
388
|
+
'npm',
|
|
389
|
+
'i',
|
|
390
|
+
...passthroughArgs,
|
|
391
|
+
].join(' ');
|
|
392
|
+
await runShellCommand(installCommand);
|
|
393
|
+
/** Run twice because npm needs this sometimes. */
|
|
394
|
+
await runShellCommand(installCommand);
|
|
395
|
+
/** A no-op when there were no too-recent matches. */
|
|
396
|
+
await reinstallOriginalDeps({
|
|
397
|
+
violators: recentDepViolators,
|
|
398
|
+
monoRepoRootPath,
|
|
399
|
+
runVirmatorShellCommand: runShellCommand,
|
|
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
|
+
}
|
|
360
412
|
}
|
|
361
413
|
else {
|
|
362
414
|
throw new VirmatorNoTraceError("deps sub-command needed: 'virmator deps check', 'virmator deps upgrade', or 'virmator deps regen'");
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { PackageJsonDependencyKey } from '@augment-vir/node';
|
|
2
|
+
/**
|
|
3
|
+
* Maps each `package.json` dependency key to the `npm i` flag needed to install into that section.
|
|
4
|
+
* An `undefined` value indicates the section is not directly installable (e.g. `overrides`, which
|
|
5
|
+
* is just a resolution override).
|
|
6
|
+
*/
|
|
7
|
+
export declare const installFlagsByDepKey: Readonly<Record<PackageJsonDependencyKey, string | undefined>>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { PackageJsonDependencyKey } from '@augment-vir/node';
|
|
2
|
+
/**
|
|
3
|
+
* Maps each `package.json` dependency key to the `npm i` flag needed to install into that section.
|
|
4
|
+
* An `undefined` value indicates the section is not directly installable (e.g. `overrides`, which
|
|
5
|
+
* is just a resolution override).
|
|
6
|
+
*/
|
|
7
|
+
export const installFlagsByDepKey = {
|
|
8
|
+
[PackageJsonDependencyKey.Dependencies]: '',
|
|
9
|
+
[PackageJsonDependencyKey.DevDependencies]: '-D',
|
|
10
|
+
[PackageJsonDependencyKey.PeerDependencies]: '--save-peer',
|
|
11
|
+
/** Not a real installable dep, just a resolution override. */
|
|
12
|
+
[PackageJsonDependencyKey.Overrides]: undefined,
|
|
13
|
+
};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { type Logger } from '@augment-vir/common';
|
|
2
|
+
import { type NpmDeps, type PackageJsonDependencyKey } from '@augment-vir/node';
|
|
3
|
+
import { type ExtraRunShellCommandOptions } from '@virmator/core';
|
|
4
|
+
import { type FullDate } from 'date-vir';
|
|
5
|
+
/** Returns whether a dependency name is safe to use in a shell command. */
|
|
6
|
+
export declare function isSafePackageName(depName: string): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
|
|
9
|
+
* returning the config value and the remaining args to forward to `npm i`.
|
|
10
|
+
*/
|
|
11
|
+
export declare function extractRegenConfigArg(filteredArgs: ReadonlyArray<string>): {
|
|
12
|
+
configValue: string | undefined;
|
|
13
|
+
passthroughArgs: string[];
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Resolves the deps-regen config path: the explicit `--config` value relative to the cwd, or the
|
|
17
|
+
* default `configs/deps-regen.config.ts` at the mono-repo root (as placed by `virmator init`).
|
|
18
|
+
*/
|
|
19
|
+
export declare function resolveRegenConfigPath({ configValue, cwd, monoRepoRootPath, }: {
|
|
20
|
+
configValue: string | undefined;
|
|
21
|
+
cwd: string;
|
|
22
|
+
monoRepoRootPath: string;
|
|
23
|
+
}): string;
|
|
24
|
+
/**
|
|
25
|
+
* Structural copy of the allow list type defined in `configs/deps-regen.config.base.ts`. It is
|
|
26
|
+
* re-declared here because `configs` lives outside this package's compiled `src` root, so it cannot
|
|
27
|
+
* be type-imported. Each entry matches a package by exact name (string) or pattern (RegExp).
|
|
28
|
+
*/
|
|
29
|
+
export type RecentDepsAllowList = ReadonlyArray<string | RegExp>;
|
|
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
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Injectable IO used by {@link prepareRecentDepDowngrades}. Defaults to real implementations;
|
|
62
|
+
* overridden in tests so the orchestration can be exercised without touching the network or
|
|
63
|
+
* filesystem.
|
|
64
|
+
*/
|
|
65
|
+
export type RecentDepsIo = {
|
|
66
|
+
fileExists: (filePath: string) => Promise<boolean>;
|
|
67
|
+
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
|
+
};
|
|
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
|
+
export declare function fileExists(filePath: string): Promise<boolean>;
|
|
87
|
+
export declare function loadAllowList(configPath: string): Promise<RecentDepsAllowList | undefined>;
|
|
88
|
+
/** Parses the JSON time map output of `npm view <pkg> time --json` into a {@link RegistryInfo}. */
|
|
89
|
+
export declare function parseRegistryTime(stdout: string): RegistryInfo | undefined;
|
|
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>;
|
|
98
|
+
/**
|
|
99
|
+
* Drops workspace-internal deps, non-installable sections (e.g. `overrides`), and any dependency
|
|
100
|
+
* whose name is not a safe npm package name (the latter both as a correctness guard and to prevent
|
|
101
|
+
* shell injection when the name is later passed to npm). Grouped by name.
|
|
102
|
+
*/
|
|
103
|
+
export declare function getCandidateDepUsages(allDirectDeps: Readonly<NpmDeps>): CandidateDepUsage[];
|
|
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;
|
|
144
|
+
configPath: string;
|
|
145
|
+
/**
|
|
146
|
+
* Whether `configPath` came from an explicit `--config` flag. A missing explicit config throws,
|
|
147
|
+
* while a missing default config is silently skipped.
|
|
148
|
+
*/
|
|
149
|
+
configIsExplicit: boolean;
|
|
150
|
+
/**
|
|
151
|
+
* The effective `min-release-age` in days. When unset, the whole feature is skipped without
|
|
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>;
|
|
173
|
+
/**
|
|
174
|
+
* Restores the original `package.json` version strings for each violator. Safe to call after a
|
|
175
|
+
* successful regen (where `npm i` rewrote them to the resolved version) or in a `finally` after a
|
|
176
|
+
* failed one (to undo the temporary downgrade), so `package.json` is never left silently
|
|
177
|
+
* downgraded.
|
|
178
|
+
*/
|
|
179
|
+
export declare function restoreOriginalPackageJsonVersions({ violators, updateVersions, }: {
|
|
180
|
+
violators: ReadonlyArray<RecentDepViolator>;
|
|
181
|
+
updateVersions?: RecentDepsIo['updatePackageJsonVersions'] | undefined;
|
|
182
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { awaitedBlockingMap, getObjectTypedEntries, removeDuplicates, wrapInTry, } from '@augment-vir/common';
|
|
3
|
+
import { listAllDirectNpmDeps, runShellCommand, } from '@augment-vir/node';
|
|
4
|
+
import { JsModuleType, VirmatorNoTraceError, withImportedTsFile, } from '@virmator/core';
|
|
5
|
+
import { calculateRelativeDate, createUtcFullDate, getNowInUtcTimezone, isDateAfter, isValidIsoString, } from 'date-vir';
|
|
6
|
+
import { readFile, stat, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
8
|
+
import { installFlagsByDepKey } from './install-flags.js';
|
|
9
|
+
const defaultDepsRegenConfigRelativePath = join('configs', 'deps-regen.config.ts');
|
|
10
|
+
/** Returns whether a dependency name is safe to use in a shell command. */
|
|
11
|
+
export function isSafePackageName(depName) {
|
|
12
|
+
/**
|
|
13
|
+
* Conservative npm package-name shape. Restricting names to these characters guarantees that
|
|
14
|
+
* values read out of an (untrusted) `package.json` and interpolated into shell commands cannot
|
|
15
|
+
* contain shell metacharacters or quotes.
|
|
16
|
+
*/
|
|
17
|
+
return /^@?[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)?$/i.test(depName);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Pulls an optional `--config <path>` (or `--config=<path>`) flag out of the raw `deps regen` args,
|
|
21
|
+
* returning the config value and the remaining args to forward to `npm i`.
|
|
22
|
+
*/
|
|
23
|
+
export function extractRegenConfigArg(filteredArgs) {
|
|
24
|
+
const { configValue, passthroughArgs, skipNext } = filteredArgs.reduce((accum, arg) => {
|
|
25
|
+
if (accum.skipNext) {
|
|
26
|
+
return {
|
|
27
|
+
configValue: arg,
|
|
28
|
+
skipNext: false,
|
|
29
|
+
passthroughArgs: accum.passthroughArgs,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
else if (arg === '--config') {
|
|
33
|
+
return {
|
|
34
|
+
...accum,
|
|
35
|
+
skipNext: true,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
else if (arg.startsWith('--config=')) {
|
|
39
|
+
return {
|
|
40
|
+
...accum,
|
|
41
|
+
configValue: arg.slice('--config='.length),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
...accum,
|
|
46
|
+
passthroughArgs: [
|
|
47
|
+
...accum.passthroughArgs,
|
|
48
|
+
arg,
|
|
49
|
+
],
|
|
50
|
+
};
|
|
51
|
+
}, {
|
|
52
|
+
configValue: undefined,
|
|
53
|
+
skipNext: false,
|
|
54
|
+
passthroughArgs: [],
|
|
55
|
+
});
|
|
56
|
+
/** A dangling '--config' (skipNext) or an empty '--config='/'--config ""' value is an error. */
|
|
57
|
+
if (skipNext || configValue === '') {
|
|
58
|
+
throw new VirmatorNoTraceError('The --config flag requires a file path value.');
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
configValue,
|
|
62
|
+
passthroughArgs,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Resolves the deps-regen config path: the explicit `--config` value relative to the cwd, or the
|
|
67
|
+
* default `configs/deps-regen.config.ts` at the mono-repo root (as placed by `virmator init`).
|
|
68
|
+
*/
|
|
69
|
+
export function resolveRegenConfigPath({ configValue, cwd, monoRepoRootPath, }) {
|
|
70
|
+
return configValue
|
|
71
|
+
? resolve(cwd, configValue)
|
|
72
|
+
: join(monoRepoRootPath, defaultDepsRegenConfigRelativePath);
|
|
73
|
+
}
|
|
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
|
+
export async function fileExists(filePath) {
|
|
96
|
+
return await wrapInTry(async () => {
|
|
97
|
+
await stat(filePath);
|
|
98
|
+
return true;
|
|
99
|
+
}, {
|
|
100
|
+
fallbackValue: false,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
export async function loadAllowList(configPath) {
|
|
104
|
+
return await withImportedTsFile({
|
|
105
|
+
inputPath: configPath,
|
|
106
|
+
}, JsModuleType.Esm, (loadedConfig) => {
|
|
107
|
+
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
|
+
});
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
/** The real IO (network and filesystem) used by {@link prepareRecentDepDowngrades}. */
|
|
323
|
+
export const defaultRecentDepsIo = {
|
|
324
|
+
fileExists,
|
|
325
|
+
loadAllowList,
|
|
326
|
+
listDirectDeps: listAllDirectNpmDeps,
|
|
327
|
+
queryRegistry,
|
|
328
|
+
queryResolvedVersion,
|
|
329
|
+
updatePackageJsonVersions,
|
|
330
|
+
};
|
|
331
|
+
/**
|
|
332
|
+
* Detects every direct dependency that both matches the deps-regen allow list and currently pins a
|
|
333
|
+
* version that violates the repo's min-release-age. Each such dependency is temporarily downgraded
|
|
334
|
+
* in its `package.json` to the most recent version that does _not_ violate min-release-age, so that
|
|
335
|
+
* the subsequent `npm i` succeeds. The original version values are returned so they can be restored
|
|
336
|
+
* via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
|
|
337
|
+
* regeneration.
|
|
338
|
+
*/
|
|
339
|
+
export async function prepareRecentDepDowngrades({ monoRepoRootPath, configPath, configIsExplicit, minReleaseAgeDays, log, now = getNowInUtcTimezone(), io = defaultRecentDepsIo, }) {
|
|
340
|
+
if (!minReleaseAgeDays) {
|
|
341
|
+
return [];
|
|
342
|
+
}
|
|
343
|
+
else if (!(await io.fileExists(configPath))) {
|
|
344
|
+
if (configIsExplicit) {
|
|
345
|
+
throw new VirmatorNoTraceError(`deps-regen config file not found: ${configPath}`);
|
|
346
|
+
}
|
|
347
|
+
return [];
|
|
348
|
+
}
|
|
349
|
+
const allowList = await io.loadAllowList(configPath);
|
|
350
|
+
if (!allowList?.length) {
|
|
351
|
+
return [];
|
|
352
|
+
}
|
|
353
|
+
const threshold = calculateRelativeDate(now, {
|
|
354
|
+
days: -minReleaseAgeDays,
|
|
355
|
+
});
|
|
356
|
+
const candidateUsages = getCandidateDepUsages(await io.listDirectDeps(monoRepoRootPath));
|
|
357
|
+
const resolveTargets = getResolveTargets(candidateUsages, allowList);
|
|
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
|
+
});
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Restores the original `package.json` version strings for each violator. Safe to call after a
|
|
429
|
+
* successful regen (where `npm i` rewrote them to the resolved version) or in a `finally` after a
|
|
430
|
+
* failed one (to undo the temporary downgrade), so `package.json` is never left silently
|
|
431
|
+
* downgraded.
|
|
432
|
+
*/
|
|
433
|
+
export async function restoreOriginalPackageJsonVersions({ violators, updateVersions = updatePackageJsonVersions, }) {
|
|
434
|
+
await awaitedBlockingMap(Array.from(groupByPackageJson(violators).entries()), async ([packageJsonPath, packageViolators,]) => {
|
|
435
|
+
await updateVersions(packageJsonPath, packageViolators.map((violator) => {
|
|
436
|
+
return {
|
|
437
|
+
dependencyKey: violator.dependencyKey,
|
|
438
|
+
depName: violator.depName,
|
|
439
|
+
version: violator.originalVersionValue,
|
|
440
|
+
};
|
|
441
|
+
}));
|
|
442
|
+
});
|
|
443
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@virmator/deps",
|
|
3
|
-
"version": "14.
|
|
3
|
+
"version": "14.23.0",
|
|
4
4
|
"description": "Default TS deps plugin for virmator.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"virmator",
|
|
@@ -38,7 +38,8 @@
|
|
|
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.23.0",
|
|
42
|
+
"date-vir": "^8.3.2",
|
|
42
43
|
"mri": "^1.2.0"
|
|
43
44
|
},
|
|
44
45
|
"devDependencies": {
|