@virmator/deps 14.22.0 → 14.23.1
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 +3 -0
- package/configs/deps-regen.config.base.ts +59 -13
- package/dist/deps.d.ts +8 -2
- package/dist/deps.js +68 -29
- package/dist/install-flags.d.ts +7 -0
- package/dist/install-flags.js +13 -0
- package/dist/regen-recent-deps.d.ts +191 -0
- package/dist/regen-recent-deps.js +474 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -47,5 +47,8 @@ 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
|
+
Reads 'configs/deps-regen.config.ts' for intelligently working around min-release-age for explicitly allowed packages.
|
|
51
|
+
|
|
50
52
|
- Examples
|
|
51
53
|
- `virmator deps regen`
|
|
54
|
+
- use a custom deps-regen allow list: `virmator deps regen --config ./configs/deps-regen.config.ts`
|
|
@@ -1,17 +1,63 @@
|
|
|
1
|
-
|
|
1
|
+
/** These packages bypass min-release-age when running `virmator deps regen`. */
|
|
2
|
+
export type RecentDepsAllowList = ReadonlyArray<string | RegExp>;
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
+
'indexed-vir',
|
|
25
|
+
'istanbul-smart-text-reporter',
|
|
26
|
+
'lit-css-vars',
|
|
27
|
+
'local-db-client',
|
|
28
|
+
'markdown-code-example-inserter',
|
|
29
|
+
'mock-vir',
|
|
30
|
+
'mono-vir',
|
|
31
|
+
'object-shape-tester',
|
|
32
|
+
'observavir',
|
|
33
|
+
'parse-email-address',
|
|
34
|
+
'pdf-vir',
|
|
35
|
+
'pglite-cli',
|
|
36
|
+
'prettier-plugin-interpolated-html-tags',
|
|
37
|
+
'prettier-plugin-multiline-arrays',
|
|
38
|
+
'prevent-navigation',
|
|
39
|
+
'prisma-pglite',
|
|
40
|
+
'prisma-vir',
|
|
41
|
+
'pull-request-vir',
|
|
42
|
+
'runstorm',
|
|
43
|
+
'schema-vir',
|
|
44
|
+
'sentry-vir',
|
|
45
|
+
'spa-router-vir',
|
|
46
|
+
'structured-render',
|
|
47
|
+
'theme-vir',
|
|
48
|
+
'tidy-tsc',
|
|
49
|
+
'typed-event-target',
|
|
50
|
+
'updating-secrets',
|
|
51
|
+
'url-vir',
|
|
52
|
+
'vira',
|
|
53
|
+
'virmator',
|
|
54
|
+
'web-snaps',
|
|
55
|
+
];
|
|
10
56
|
|
|
11
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* The default allow list: electrovir's own commonly-used packages. Each entry matches a package by
|
|
59
|
+
* exact name (string) or by pattern (RegExp tested against the package name).
|
|
60
|
+
*/
|
|
12
61
|
export const baseAllowedRecentDeps: RecentDepsAllowList = [
|
|
13
|
-
|
|
14
|
-
/** By default, allow my own packages. */
|
|
15
|
-
packageAuthorName: 'electrovir',
|
|
16
|
-
},
|
|
62
|
+
...electrovirPackages,
|
|
17
63
|
];
|
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 Reads 'configs/deps-regen.config.ts' for intelligently working\n around min-release-age for explicitly allowed packages.\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 Reads 'configs/deps-regen.config.ts' for intelligently working\n around min-release-age for explicitly allowed packages.\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,19 @@ 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
|
+
Reads 'configs/deps-regen.config.ts' for intelligently working
|
|
182
|
+
around min-release-age for explicitly allowed packages.
|
|
183
|
+
`,
|
|
185
184
|
],
|
|
186
185
|
examples: [
|
|
187
186
|
{
|
|
188
187
|
content: 'virmator deps regen',
|
|
189
188
|
},
|
|
189
|
+
{
|
|
190
|
+
title: 'use a custom deps-regen allow list',
|
|
191
|
+
content: 'virmator deps regen --config ./configs/deps-regen.config.ts',
|
|
192
|
+
},
|
|
190
193
|
],
|
|
191
194
|
},
|
|
192
195
|
},
|
|
@@ -334,29 +337,65 @@ export const virmatorDepsPlugin = defineVirmatorPlugin(import.meta.dirname, {
|
|
|
334
337
|
}
|
|
335
338
|
}
|
|
336
339
|
else if (usedCommands.deps?.subCommands.regen) {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
340
|
+
/** Strip '--config <path>' so it isn't forwarded to 'npm i'. */
|
|
341
|
+
const { configValue, passthroughArgs } = extractRegenConfigArg(filteredArgs);
|
|
342
|
+
/**
|
|
343
|
+
* Direct deps that match the allow list but pin a too-recent version are temporarily
|
|
344
|
+
* downgraded so the install below succeeds, then restored afterwards. When the repo has
|
|
345
|
+
* no 'min-release-age', this is a no-op.
|
|
346
|
+
*/
|
|
347
|
+
const recentDepViolators = await prepareRecentDepDowngrades({
|
|
348
|
+
monoRepoRootPath,
|
|
349
|
+
configPath: resolveRegenConfigPath({
|
|
350
|
+
configValue,
|
|
351
|
+
cwd,
|
|
352
|
+
monoRepoRootPath,
|
|
353
|
+
}),
|
|
354
|
+
configIsExplicit: check.isTruthy(configValue),
|
|
355
|
+
minReleaseAgeDays: await getMinReleaseAgeDays(monoRepoRootPath),
|
|
356
|
+
log,
|
|
357
|
+
});
|
|
358
|
+
try {
|
|
359
|
+
const allNodeModulesDirectories = [
|
|
360
|
+
...monoRepoPackages.map((monoPackage) => join(monoRepoRootPath, monoPackage.relativePath, 'node_modules')),
|
|
361
|
+
join(monoRepoRootPath, 'node_modules'),
|
|
362
|
+
];
|
|
363
|
+
await awaitedBlockingMap(allNodeModulesDirectories, async (path) => {
|
|
364
|
+
log.faint(`Removing ${relative(monoRepoRootPath, path)}...`);
|
|
365
|
+
await rm(path, {
|
|
366
|
+
force: true,
|
|
367
|
+
recursive: true,
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
log.faint('Removing package-lock.json...');
|
|
371
|
+
await rm(join(monoRepoRootPath, 'package-lock.json'), {
|
|
344
372
|
force: true,
|
|
345
|
-
recursive: true,
|
|
346
373
|
});
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
374
|
+
const installCommand = [
|
|
375
|
+
'npm',
|
|
376
|
+
'i',
|
|
377
|
+
...passthroughArgs,
|
|
378
|
+
].join(' ');
|
|
379
|
+
await runShellCommand(installCommand);
|
|
380
|
+
/** Run twice because npm needs this sometimes. */
|
|
381
|
+
await runShellCommand(installCommand);
|
|
382
|
+
/** A no-op when there were no too-recent matches. */
|
|
383
|
+
await reinstallOriginalDeps({
|
|
384
|
+
violators: recentDepViolators,
|
|
385
|
+
monoRepoRootPath,
|
|
386
|
+
runVirmatorShellCommand: runShellCommand,
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
/**
|
|
391
|
+
* Always restore the original `package.json` versions, even if regen failed
|
|
392
|
+
* partway, so a failed run never leaves dependencies silently downgraded. A no-op
|
|
393
|
+
* when there were no matches.
|
|
394
|
+
*/
|
|
395
|
+
await restoreOriginalPackageJsonVersions({
|
|
396
|
+
violators: recentDepViolators,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
360
399
|
}
|
|
361
400
|
else {
|
|
362
401
|
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,191 @@
|
|
|
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
|
+
/**
|
|
43
|
+
* The most recent published version that does _not_ violate min-release-age, to temporarily
|
|
44
|
+
* downgrade to. `undefined` when _no_ published version is old enough (e.g. a brand-new
|
|
45
|
+
* package); in that case the dep is temporarily removed for the regen install instead, then
|
|
46
|
+
* re-added by the bypass reinstall.
|
|
47
|
+
*/
|
|
48
|
+
safeVersion: string | undefined;
|
|
49
|
+
};
|
|
50
|
+
export type RegistryInfo = {
|
|
51
|
+
/** Map of published version (and `created`/`modified`) to ISO publish date. */
|
|
52
|
+
time: Record<string, string>;
|
|
53
|
+
};
|
|
54
|
+
/** A single `package.json` dependency change applied by {@link updatePackageJsonVersions}. */
|
|
55
|
+
export type VersionUpdate = {
|
|
56
|
+
dependencyKey: PackageJsonDependencyKey;
|
|
57
|
+
depName: string;
|
|
58
|
+
/** The new version range, or `undefined` to remove the dependency entry entirely. */
|
|
59
|
+
version: string | undefined;
|
|
60
|
+
};
|
|
61
|
+
/** A direct dependency name paired with its installable, non-workspace usages. */
|
|
62
|
+
export type CandidateDepUsage = {
|
|
63
|
+
depName: string;
|
|
64
|
+
usages: NpmDeps[string];
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Injectable IO used by {@link prepareRecentDepDowngrades}. Defaults to real implementations;
|
|
68
|
+
* overridden in tests so the orchestration can be exercised without touching the network or
|
|
69
|
+
* filesystem.
|
|
70
|
+
*/
|
|
71
|
+
export type RecentDepsIo = {
|
|
72
|
+
fileExists: (filePath: string) => Promise<boolean>;
|
|
73
|
+
loadAllowList: (configPath: string) => Promise<RecentDepsAllowList | undefined>;
|
|
74
|
+
listDirectDeps: (rootPath: string) => Promise<NpmDeps>;
|
|
75
|
+
queryRegistry: (depName: string, cwd: string) => Promise<RegistryInfo | undefined>;
|
|
76
|
+
/**
|
|
77
|
+
* Returns every published version satisfying the given range (ignoring min-release-age), or
|
|
78
|
+
* `undefined` if the range matches nothing. Used to decide whether a cooldown-respecting
|
|
79
|
+
* install could find an old-enough version.
|
|
80
|
+
*/
|
|
81
|
+
queryInRangeVersions: (depName: string, range: string, cwd: string) => Promise<string[] | undefined>;
|
|
82
|
+
updatePackageJsonVersions: (packageJsonPath: string, updates: ReadonlyArray<VersionUpdate>) => Promise<void>;
|
|
83
|
+
};
|
|
84
|
+
/** Parses the output of `npm config get min-release-age` into a positive day count, or `undefined`. */
|
|
85
|
+
export declare function parseMinReleaseAgeDays(rawValue: string): number | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Returns the effective `min-release-age` (in days) as resolved by npm across all config sources
|
|
88
|
+
* (project `.npmrc` overriding user, overriding global), or `undefined` if it is unset or
|
|
89
|
+
* non-positive.
|
|
90
|
+
*/
|
|
91
|
+
export declare function getMinReleaseAgeDays(monoRepoRootPath: string): Promise<number | undefined>;
|
|
92
|
+
export declare function fileExists(filePath: string): Promise<boolean>;
|
|
93
|
+
export declare function loadAllowList(configPath: string): Promise<RecentDepsAllowList | undefined>;
|
|
94
|
+
/** Parses the JSON time map output of `npm view <pkg> time --json` into a {@link RegistryInfo}. */
|
|
95
|
+
export declare function parseRegistryTime(stdout: string): RegistryInfo | undefined;
|
|
96
|
+
/**
|
|
97
|
+
* Parses the JSON output of `npm view <pkg>@<range> version --json` into the list of published
|
|
98
|
+
* versions that satisfy the range (npm returns a single string when only one matches, an array
|
|
99
|
+
* otherwise). `undefined` if nothing matched / the output was unusable.
|
|
100
|
+
*/
|
|
101
|
+
export declare function parseInRangeVersions(stdout: string): string[] | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Reads, applies the given dependency changes to, and re-writes a `package.json` file in place. A
|
|
104
|
+
* `string` version sets (or re-adds) the entry; an `undefined` version removes it. Sections that
|
|
105
|
+
* don't exist are left untouched.
|
|
106
|
+
*/
|
|
107
|
+
export declare function updatePackageJsonVersions(packageJsonPath: string, updates: ReadonlyArray<VersionUpdate>): Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Drops workspace-internal deps, non-installable sections (e.g. `overrides`), and any dependency
|
|
110
|
+
* whose name is not a safe npm package name (the latter both as a correctness guard and to prevent
|
|
111
|
+
* shell injection when the name is later passed to npm). Grouped by name.
|
|
112
|
+
*/
|
|
113
|
+
export declare function getCandidateDepUsages(allDirectDeps: Readonly<NpmDeps>): CandidateDepUsage[];
|
|
114
|
+
/** The lookup key for a specific dependency range (or version). */
|
|
115
|
+
export declare function depRangeKey(depName: string, range: string): string;
|
|
116
|
+
/**
|
|
117
|
+
* Returns the `{depName, range}` pairs whose in-range versions must be looked up (to decide whether
|
|
118
|
+
* a cooldown-respecting install could satisfy the range): only for allow-list-matched candidates
|
|
119
|
+
* with a parseable range. Deduped.
|
|
120
|
+
*/
|
|
121
|
+
export declare function getResolveTargets(candidateUsages: ReadonlyArray<CandidateDepUsage>, allowList: RecentDepsAllowList): {
|
|
122
|
+
depName: string;
|
|
123
|
+
range: string;
|
|
124
|
+
}[];
|
|
125
|
+
/**
|
|
126
|
+
* Pure detection of every direct dependency usage that both matches the allow list and whose range
|
|
127
|
+
* _cannot_ be satisfied by an old-enough version (so a cooldown-respecting `npm i` would fail),
|
|
128
|
+
* paired with the safe version it should be temporarily downgraded to (or `undefined` to remove).
|
|
129
|
+
* Deps whose range already has an old-enough version are left alone — `npm i` installs that
|
|
130
|
+
* itself.
|
|
131
|
+
*/
|
|
132
|
+
export declare function computeRecentDepViolators({ candidateUsages, allowList, registryByName, inRangeVersionsByRange, threshold, }: {
|
|
133
|
+
candidateUsages: ReadonlyArray<CandidateDepUsage>;
|
|
134
|
+
allowList: RecentDepsAllowList;
|
|
135
|
+
registryByName: ReadonlyMap<string, RegistryInfo | undefined>;
|
|
136
|
+
/** The published versions satisfying each `${depName}@${range}` (ignoring min-release-age). */
|
|
137
|
+
inRangeVersionsByRange: ReadonlyMap<string, string[] | undefined>;
|
|
138
|
+
/** The min-release-age cutoff: a version published after this is too recent. */
|
|
139
|
+
threshold: FullDate;
|
|
140
|
+
}): RecentDepViolator[];
|
|
141
|
+
/** The real IO (network and filesystem) used by {@link prepareRecentDepDowngrades}. */
|
|
142
|
+
export declare const defaultRecentDepsIo: RecentDepsIo;
|
|
143
|
+
/**
|
|
144
|
+
* Detects every direct dependency that both matches the deps-regen allow list and currently pins a
|
|
145
|
+
* version that violates the repo's min-release-age. Each such dependency is temporarily downgraded
|
|
146
|
+
* in its `package.json` to the most recent version that does _not_ violate min-release-age, so that
|
|
147
|
+
* the subsequent `npm i` succeeds. The original version values are returned so they can be restored
|
|
148
|
+
* via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
|
|
149
|
+
* regeneration.
|
|
150
|
+
*/
|
|
151
|
+
export declare function prepareRecentDepDowngrades({ monoRepoRootPath, configPath, configIsExplicit, minReleaseAgeDays, log, now, io, }: {
|
|
152
|
+
monoRepoRootPath: string;
|
|
153
|
+
configPath: string;
|
|
154
|
+
/**
|
|
155
|
+
* Whether `configPath` came from an explicit `--config` flag. A missing explicit config throws,
|
|
156
|
+
* while a missing default config is silently skipped.
|
|
157
|
+
*/
|
|
158
|
+
configIsExplicit: boolean;
|
|
159
|
+
/**
|
|
160
|
+
* The effective `min-release-age` in days. When unset, the whole feature is skipped without
|
|
161
|
+
* even reading the deps-regen config.
|
|
162
|
+
*/
|
|
163
|
+
minReleaseAgeDays: number | undefined;
|
|
164
|
+
log: Logger;
|
|
165
|
+
now?: FullDate | undefined;
|
|
166
|
+
io?: RecentDepsIo | undefined;
|
|
167
|
+
}): Promise<RecentDepViolator[]>;
|
|
168
|
+
/**
|
|
169
|
+
* Re-installs each downgraded dependency at its original version, bypassing min-release-age.
|
|
170
|
+
* Installs are grouped per package directory and per dependency type (`-D`, `--save-peer`, or none)
|
|
171
|
+
* so each `npm i` runs in the correct location (sub-packages and/or the mono-repo root). Each
|
|
172
|
+
* install spec is single-quoted; combined with the package-name and version validation done while
|
|
173
|
+
* detecting violators, this prevents shell injection from `package.json` values.
|
|
174
|
+
*/
|
|
175
|
+
export declare function reinstallOriginalDeps({ violators, monoRepoRootPath, runVirmatorShellCommand, }: {
|
|
176
|
+
violators: ReadonlyArray<RecentDepViolator>;
|
|
177
|
+
monoRepoRootPath: string;
|
|
178
|
+
runVirmatorShellCommand: (command: string, options: {
|
|
179
|
+
cwd: string;
|
|
180
|
+
}, extraOptions: Partial<ExtraRunShellCommandOptions>) => Promise<unknown>;
|
|
181
|
+
}): Promise<void>;
|
|
182
|
+
/**
|
|
183
|
+
* Restores the original `package.json` version strings for each violator. Safe to call after a
|
|
184
|
+
* successful regen (where `npm i` rewrote them to the resolved version) or in a `finally` after a
|
|
185
|
+
* failed one (to undo the temporary downgrade), so `package.json` is never left silently
|
|
186
|
+
* downgraded.
|
|
187
|
+
*/
|
|
188
|
+
export declare function restoreOriginalPackageJsonVersions({ violators, updateVersions, }: {
|
|
189
|
+
violators: ReadonlyArray<RecentDepViolator>;
|
|
190
|
+
updateVersions?: RecentDepsIo['updatePackageJsonVersions'] | undefined;
|
|
191
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,474 @@
|
|
|
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 list of published
|
|
125
|
+
* versions that satisfy the range (npm returns a single string when only one matches, an array
|
|
126
|
+
* otherwise). `undefined` if nothing matched / the output was unusable.
|
|
127
|
+
*/
|
|
128
|
+
export function parseInRangeVersions(stdout) {
|
|
129
|
+
const parsed = wrapInTry(() => JSON.parse(stdout), {
|
|
130
|
+
fallbackValue: undefined,
|
|
131
|
+
});
|
|
132
|
+
if (check.isString(parsed)) {
|
|
133
|
+
return [
|
|
134
|
+
parsed,
|
|
135
|
+
];
|
|
136
|
+
}
|
|
137
|
+
else if (check.isArray(parsed)) {
|
|
138
|
+
return parsed.filter(check.isString);
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
/* node:coverage disable -- thin network wrappers around the npm registry; parsing lives in the parse* helpers */
|
|
143
|
+
async function queryRegistry(depName, cwd) {
|
|
144
|
+
const result = await runShellCommand(`npm view '${depName}' time --json`, {
|
|
145
|
+
cwd,
|
|
146
|
+
});
|
|
147
|
+
if (result.exitCode) {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
return parseRegistryTime(result.stdout);
|
|
151
|
+
}
|
|
152
|
+
async function queryInRangeVersions(depName, range, cwd) {
|
|
153
|
+
const result = await runShellCommand(`npm view '${depName}@${range}' version --json`, {
|
|
154
|
+
cwd,
|
|
155
|
+
});
|
|
156
|
+
if (result.exitCode) {
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
return parseInRangeVersions(result.stdout);
|
|
160
|
+
}
|
|
161
|
+
/* node:coverage enable */
|
|
162
|
+
/** Whether a dependency name matches any allow-list entry (exact string or RegExp pattern). */
|
|
163
|
+
function matchesAllowList(allowList, depName) {
|
|
164
|
+
return allowList.some((entry) => entry instanceof RegExp ? entry.test(depName) : entry === depName);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Splits a version range value into its leading prefix and a clean `x.y.z` version, if possible.
|
|
168
|
+
* The prefix is restricted to known semver range operators so that values read out of an
|
|
169
|
+
* (untrusted) `package.json` cannot smuggle shell metacharacters through as a "prefix".
|
|
170
|
+
*/
|
|
171
|
+
function parseVersionValue(versionValue) {
|
|
172
|
+
const match = /^(>=|<=|>|<|\^|~|=|v)?(\d+\.\d+\.\d+)\s*$/i.exec(versionValue);
|
|
173
|
+
if (!match?.[2]) {
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
prefix: match[1] || '',
|
|
178
|
+
version: match[2],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Whether the given publish date is old enough to satisfy `threshold` (the min-release-age cutoff)
|
|
183
|
+
* — i.e. a cooldown-respecting `npm i` would be allowed to install it. Missing/invalid dates are
|
|
184
|
+
* treated as not old enough.
|
|
185
|
+
*/
|
|
186
|
+
function isVersionOldEnough(publishDateString, threshold) {
|
|
187
|
+
if (!publishDateString || !isValidIsoString(publishDateString)) {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
return !isDateAfter({
|
|
191
|
+
fullDate: createUtcFullDate(publishDateString),
|
|
192
|
+
relativeTo: threshold,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
/** Finds the most recently published stable version that is old enough to satisfy `threshold`. */
|
|
196
|
+
function findMostRecentSafeVersion(time, threshold) {
|
|
197
|
+
const safeVersions = getObjectTypedEntries(time)
|
|
198
|
+
.filter(([version, dateString,]) => /^\d+\.\d+\.\d+$/.test(version) && isVersionOldEnough(dateString, threshold))
|
|
199
|
+
.map(([version, dateString,]) => {
|
|
200
|
+
return {
|
|
201
|
+
version,
|
|
202
|
+
date: createUtcFullDate(dateString),
|
|
203
|
+
};
|
|
204
|
+
});
|
|
205
|
+
if (!safeVersions.length) {
|
|
206
|
+
return undefined;
|
|
207
|
+
}
|
|
208
|
+
return safeVersions.reduce((mostRecent, current) => isDateAfter({
|
|
209
|
+
fullDate: current.date,
|
|
210
|
+
relativeTo: mostRecent.date,
|
|
211
|
+
})
|
|
212
|
+
? current
|
|
213
|
+
: mostRecent).version;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Reads, applies the given dependency changes to, and re-writes a `package.json` file in place. A
|
|
217
|
+
* `string` version sets (or re-adds) the entry; an `undefined` version removes it. Sections that
|
|
218
|
+
* don't exist are left untouched.
|
|
219
|
+
*/
|
|
220
|
+
export async function updatePackageJsonVersions(packageJsonPath, updates) {
|
|
221
|
+
const originalContents = await readFile(packageJsonPath, 'utf8');
|
|
222
|
+
const indent = /\n([ \t]+)\S/.exec(originalContents)?.[1] || ' ';
|
|
223
|
+
const trailingNewLine = originalContents.endsWith('\n') ? '\n' : '';
|
|
224
|
+
const parsed = JSON.parse(originalContents);
|
|
225
|
+
updates.forEach(({ dependencyKey, depName, version }) => {
|
|
226
|
+
const section = parsed[dependencyKey];
|
|
227
|
+
if (!check.isObject(section)) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (version == undefined) {
|
|
231
|
+
delete section[depName];
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
section[depName] = version;
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
await writeFile(packageJsonPath, JSON.stringify(parsed, undefined, indent) + trailingNewLine);
|
|
238
|
+
}
|
|
239
|
+
/** Groups violators by their `package.json` path so each file is written exactly once. */
|
|
240
|
+
function groupByPackageJson(violators) {
|
|
241
|
+
return violators.reduce((accum, violator) => {
|
|
242
|
+
const existing = accum.get(violator.packageJsonPath) ?? [];
|
|
243
|
+
accum.set(violator.packageJsonPath, [
|
|
244
|
+
...existing,
|
|
245
|
+
violator,
|
|
246
|
+
]);
|
|
247
|
+
return accum;
|
|
248
|
+
}, new Map());
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Drops workspace-internal deps, non-installable sections (e.g. `overrides`), and any dependency
|
|
252
|
+
* whose name is not a safe npm package name (the latter both as a correctness guard and to prevent
|
|
253
|
+
* shell injection when the name is later passed to npm). Grouped by name.
|
|
254
|
+
*/
|
|
255
|
+
export function getCandidateDepUsages(allDirectDeps) {
|
|
256
|
+
return getObjectTypedEntries(allDirectDeps)
|
|
257
|
+
.filter(([depName]) => isSafePackageName(depName))
|
|
258
|
+
.map(([depName, usages,]) => {
|
|
259
|
+
return {
|
|
260
|
+
depName,
|
|
261
|
+
usages: usages.filter((usage) => !usage.isWorkspace &&
|
|
262
|
+
installFlagsByDepKey[usage.dependencyKey] != undefined),
|
|
263
|
+
};
|
|
264
|
+
})
|
|
265
|
+
.filter(({ usages }) => usages.length);
|
|
266
|
+
}
|
|
267
|
+
/** The lookup key for a specific dependency range (or version). */
|
|
268
|
+
export function depRangeKey(depName, range) {
|
|
269
|
+
return `${depName}@${range}`;
|
|
270
|
+
}
|
|
271
|
+
/** The simple range (prefix + `x.y.z`) reconstructed from a usage's version value, if parseable. */
|
|
272
|
+
function rangeOfUsage(versionValue) {
|
|
273
|
+
const parsedVersion = parseVersionValue(versionValue);
|
|
274
|
+
return parsedVersion ? `${parsedVersion.prefix}${parsedVersion.version}` : undefined;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Returns the `{depName, range}` pairs whose in-range versions must be looked up (to decide whether
|
|
278
|
+
* a cooldown-respecting install could satisfy the range): only for allow-list-matched candidates
|
|
279
|
+
* with a parseable range. Deduped.
|
|
280
|
+
*/
|
|
281
|
+
export function getResolveTargets(candidateUsages, allowList) {
|
|
282
|
+
const targets = new Map();
|
|
283
|
+
candidateUsages.forEach(({ depName, usages }) => {
|
|
284
|
+
if (!matchesAllowList(allowList, depName)) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
usages.forEach((usage) => {
|
|
288
|
+
const range = rangeOfUsage(usage.versionValue);
|
|
289
|
+
if (range != undefined) {
|
|
290
|
+
targets.set(depRangeKey(depName, range), {
|
|
291
|
+
depName,
|
|
292
|
+
range,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
return Array.from(targets.values());
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Pure detection of every direct dependency usage that both matches the allow list and whose range
|
|
301
|
+
* _cannot_ be satisfied by an old-enough version (so a cooldown-respecting `npm i` would fail),
|
|
302
|
+
* paired with the safe version it should be temporarily downgraded to (or `undefined` to remove).
|
|
303
|
+
* Deps whose range already has an old-enough version are left alone — `npm i` installs that
|
|
304
|
+
* itself.
|
|
305
|
+
*/
|
|
306
|
+
export function computeRecentDepViolators({ candidateUsages, allowList, registryByName, inRangeVersionsByRange, threshold, }) {
|
|
307
|
+
return candidateUsages.flatMap(({ depName, usages }) => {
|
|
308
|
+
const registry = registryByName.get(depName);
|
|
309
|
+
if (!registry || !matchesAllowList(allowList, depName)) {
|
|
310
|
+
return [];
|
|
311
|
+
}
|
|
312
|
+
return usages.flatMap((usage) => {
|
|
313
|
+
const parsedVersion = parseVersionValue(usage.versionValue);
|
|
314
|
+
if (!parsedVersion) {
|
|
315
|
+
return [];
|
|
316
|
+
}
|
|
317
|
+
const range = `${parsedVersion.prefix}${parsedVersion.version}`;
|
|
318
|
+
const inRangeVersions = inRangeVersionsByRange.get(depRangeKey(depName, range));
|
|
319
|
+
/**
|
|
320
|
+
* Leave the dep alone when its range matches nothing (a plain install would fail with a
|
|
321
|
+
* clear error of its own) or when some in-range version is old enough (a plain install
|
|
322
|
+
* resolves the range to that version on its own — no downgrade needed).
|
|
323
|
+
*/
|
|
324
|
+
if (!inRangeVersions?.length ||
|
|
325
|
+
inRangeVersions.some((version) => isVersionOldEnough(registry.time[version], threshold))) {
|
|
326
|
+
return [];
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* No in-range version is old enough, so a cooldown-respecting install can't satisfy the
|
|
330
|
+
* range. Downgrade to the most recent old-enough version overall, or — when there is no
|
|
331
|
+
* old-enough version at all (a brand-new package) — `undefined`, meaning the dep is
|
|
332
|
+
* temporarily removed for the regen install rather than downgraded.
|
|
333
|
+
*/
|
|
334
|
+
const safeVersion = findMostRecentSafeVersion(registry.time, threshold);
|
|
335
|
+
return [
|
|
336
|
+
{
|
|
337
|
+
packageJsonPath: usage.requiredBy,
|
|
338
|
+
packageDir: dirname(usage.requiredBy),
|
|
339
|
+
dependencyKey: usage.dependencyKey,
|
|
340
|
+
depName,
|
|
341
|
+
originalVersionValue: usage.versionValue,
|
|
342
|
+
versionPrefix: parsedVersion.prefix,
|
|
343
|
+
safeVersion,
|
|
344
|
+
},
|
|
345
|
+
];
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/** The real IO (network and filesystem) used by {@link prepareRecentDepDowngrades}. */
|
|
350
|
+
export const defaultRecentDepsIo = {
|
|
351
|
+
fileExists,
|
|
352
|
+
loadAllowList,
|
|
353
|
+
listDirectDeps: listAllDirectNpmDeps,
|
|
354
|
+
queryRegistry,
|
|
355
|
+
queryInRangeVersions,
|
|
356
|
+
updatePackageJsonVersions,
|
|
357
|
+
};
|
|
358
|
+
/**
|
|
359
|
+
* Detects every direct dependency that both matches the deps-regen allow list and currently pins a
|
|
360
|
+
* version that violates the repo's min-release-age. Each such dependency is temporarily downgraded
|
|
361
|
+
* in its `package.json` to the most recent version that does _not_ violate min-release-age, so that
|
|
362
|
+
* the subsequent `npm i` succeeds. The original version values are returned so they can be restored
|
|
363
|
+
* via {@link reinstallOriginalDeps} and {@link restoreOriginalPackageJsonVersions} after
|
|
364
|
+
* regeneration.
|
|
365
|
+
*/
|
|
366
|
+
export async function prepareRecentDepDowngrades({ monoRepoRootPath, configPath, configIsExplicit, minReleaseAgeDays, log, now = getNowInUtcTimezone(), io = defaultRecentDepsIo, }) {
|
|
367
|
+
if (!minReleaseAgeDays) {
|
|
368
|
+
return [];
|
|
369
|
+
}
|
|
370
|
+
else if (!(await io.fileExists(configPath))) {
|
|
371
|
+
if (configIsExplicit) {
|
|
372
|
+
throw new VirmatorNoTraceError(`deps-regen config file not found: ${configPath}`);
|
|
373
|
+
}
|
|
374
|
+
return [];
|
|
375
|
+
}
|
|
376
|
+
const allowList = await io.loadAllowList(configPath);
|
|
377
|
+
if (!allowList?.length) {
|
|
378
|
+
return [];
|
|
379
|
+
}
|
|
380
|
+
const threshold = calculateRelativeDate(now, {
|
|
381
|
+
days: -minReleaseAgeDays,
|
|
382
|
+
});
|
|
383
|
+
const candidateUsages = getCandidateDepUsages(await io.listDirectDeps(monoRepoRootPath));
|
|
384
|
+
const resolveTargets = getResolveTargets(candidateUsages, allowList);
|
|
385
|
+
/** The `time` map is only needed for deps that have a resolve target (a potential violator). */
|
|
386
|
+
const registryByName = new Map(await awaitedBlockingMap(removeDuplicates(resolveTargets.map(({ depName }) => depName)), async (depName) => [
|
|
387
|
+
depName,
|
|
388
|
+
await io.queryRegistry(depName, monoRepoRootPath),
|
|
389
|
+
]));
|
|
390
|
+
const inRangeVersionsByRange = new Map(await awaitedBlockingMap(resolveTargets, async ({ depName, range }) => [
|
|
391
|
+
depRangeKey(depName, range),
|
|
392
|
+
await io.queryInRangeVersions(depName, range, monoRepoRootPath),
|
|
393
|
+
]));
|
|
394
|
+
const violators = computeRecentDepViolators({
|
|
395
|
+
candidateUsages,
|
|
396
|
+
allowList,
|
|
397
|
+
registryByName,
|
|
398
|
+
inRangeVersionsByRange,
|
|
399
|
+
threshold,
|
|
400
|
+
});
|
|
401
|
+
await awaitedBlockingMap(Array.from(groupByPackageJson(violators).entries()), async ([packageJsonPath, packageViolators,]) => {
|
|
402
|
+
packageViolators.forEach((violator) => {
|
|
403
|
+
log.faint(violator.safeVersion == undefined
|
|
404
|
+
? `Temporarily removing ${violator.depName} (no version old enough) for regen.`
|
|
405
|
+
: `Temporarily downgrading ${violator.depName} from ${violator.originalVersionValue} to ${violator.versionPrefix}${violator.safeVersion} for regen.`);
|
|
406
|
+
});
|
|
407
|
+
await io.updatePackageJsonVersions(packageJsonPath, packageViolators.map((violator) => {
|
|
408
|
+
return {
|
|
409
|
+
dependencyKey: violator.dependencyKey,
|
|
410
|
+
depName: violator.depName,
|
|
411
|
+
version: violator.safeVersion == undefined
|
|
412
|
+
? undefined
|
|
413
|
+
: `${violator.versionPrefix}${violator.safeVersion}`,
|
|
414
|
+
};
|
|
415
|
+
}));
|
|
416
|
+
});
|
|
417
|
+
return violators;
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Re-installs each downgraded dependency at its original version, bypassing min-release-age.
|
|
421
|
+
* Installs are grouped per package directory and per dependency type (`-D`, `--save-peer`, or none)
|
|
422
|
+
* so each `npm i` runs in the correct location (sub-packages and/or the mono-repo root). Each
|
|
423
|
+
* install spec is single-quoted; combined with the package-name and version validation done while
|
|
424
|
+
* detecting violators, this prevents shell injection from `package.json` values.
|
|
425
|
+
*/
|
|
426
|
+
export async function reinstallOriginalDeps({ violators, monoRepoRootPath, runVirmatorShellCommand, }) {
|
|
427
|
+
const byPackageAndKey = violators.reduce((accum, violator) => {
|
|
428
|
+
const byKey = accum.get(violator.packageDir) ?? new Map();
|
|
429
|
+
const existing = byKey.get(violator.dependencyKey) ?? [];
|
|
430
|
+
byKey.set(violator.dependencyKey, [
|
|
431
|
+
...existing,
|
|
432
|
+
violator,
|
|
433
|
+
]);
|
|
434
|
+
accum.set(violator.packageDir, byKey);
|
|
435
|
+
return accum;
|
|
436
|
+
}, new Map());
|
|
437
|
+
await awaitedBlockingMap(Array.from(byPackageAndKey.entries()), async ([packageDir, byKey,]) => {
|
|
438
|
+
await awaitedBlockingMap(Array.from(byKey.entries()), async ([dependencyKey, keyViolators,]) => {
|
|
439
|
+
const flag = installFlagsByDepKey[dependencyKey];
|
|
440
|
+
const command = [
|
|
441
|
+
'npm',
|
|
442
|
+
'i',
|
|
443
|
+
flag,
|
|
444
|
+
...keyViolators.map((violator) => `'${violator.depName}@${violator.originalVersionValue.trim()}'`),
|
|
445
|
+
'--min-release-age=0',
|
|
446
|
+
]
|
|
447
|
+
.filter(check.isTruthy)
|
|
448
|
+
.join(' ');
|
|
449
|
+
await runVirmatorShellCommand(command, {
|
|
450
|
+
cwd: packageDir,
|
|
451
|
+
}, {
|
|
452
|
+
logPrefix: relative(monoRepoRootPath, packageDir) || '.',
|
|
453
|
+
prefixCommandOnly: true,
|
|
454
|
+
});
|
|
455
|
+
});
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Restores the original `package.json` version strings for each violator. Safe to call after a
|
|
460
|
+
* successful regen (where `npm i` rewrote them to the resolved version) or in a `finally` after a
|
|
461
|
+
* failed one (to undo the temporary downgrade), so `package.json` is never left silently
|
|
462
|
+
* downgraded.
|
|
463
|
+
*/
|
|
464
|
+
export async function restoreOriginalPackageJsonVersions({ violators, updateVersions = updatePackageJsonVersions, }) {
|
|
465
|
+
await awaitedBlockingMap(Array.from(groupByPackageJson(violators).entries()), async ([packageJsonPath, packageViolators,]) => {
|
|
466
|
+
await updateVersions(packageJsonPath, packageViolators.map((violator) => {
|
|
467
|
+
return {
|
|
468
|
+
dependencyKey: violator.dependencyKey,
|
|
469
|
+
depName: violator.depName,
|
|
470
|
+
version: violator.originalVersionValue,
|
|
471
|
+
};
|
|
472
|
+
}));
|
|
473
|
+
});
|
|
474
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@virmator/deps",
|
|
3
|
-
"version": "14.
|
|
3
|
+
"version": "14.23.1",
|
|
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.1",
|
|
42
|
+
"date-vir": "^8.3.2",
|
|
42
43
|
"mri": "^1.2.0"
|
|
43
44
|
},
|
|
44
45
|
"devDependencies": {
|