-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathcomputeResolverCacheFromLockfileAsync.ts
More file actions
287 lines (250 loc) · 9.28 KB
/
computeResolverCacheFromLockfileAsync.ts
File metadata and controls
287 lines (250 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import type { LookupByPath } from '@rushstack/rush-sdk';
import type { IPnpmShrinkwrapDependencyYaml } from '@rushstack/rush-sdk/lib/logic/pnpm/PnpmShrinkwrapFile';
import type {
ISerializedResolveContext,
IResolverCacheFile
} from '@rushstack/webpack-workspace-resolve-plugin';
import type { PnpmShrinkwrapFile } from './externals';
import {
getDescriptionFileRootFromKey,
resolveDependencies,
createContextSerializer,
extractNameAndVersionFromKey
} from './helpers';
import type { IResolverContext } from './types';
/**
* The only parts of a RushConfigurationProject needed by this tool.
* Reduced for unit test typings.
*/
export interface IPartialRushProject {
projectFolder: string;
packageJson: {
name: string;
};
}
export interface IPlatformInfo {
os: typeof process.platform;
cpu: typeof process.arch;
libc: 'glibc' | 'musl';
}
function isPackageCompatible(
pack: Pick<IPnpmShrinkwrapDependencyYaml, 'os' | 'cpu' | 'libc'>,
platformInfo: IPlatformInfo
): boolean {
if (pack.os?.every((value) => value.toLowerCase() !== platformInfo.os)) {
return false;
}
if (pack.cpu?.every((value) => value.toLowerCase() !== platformInfo.cpu)) {
return false;
}
if (pack.libc?.every((value) => value.toLowerCase() !== platformInfo.libc)) {
return false;
}
return true;
}
function extractBundledDependencies(
contexts: Map<string, IResolverContext>,
context: IResolverContext
): void {
let { nestedPackageDirs } = context;
if (!nestedPackageDirs) {
return;
}
let foundBundledDependencies: boolean = false;
for (let i: number = nestedPackageDirs.length - 1; i >= 0; i--) {
const nestedDir: string = nestedPackageDirs[i];
if (!nestedDir.startsWith('node_modules/')) {
continue;
}
const isScoped: boolean = nestedDir.charAt(/* 'node_modules/'.length */ 13) === '@';
let index: number = nestedDir.indexOf('/', 13);
if (isScoped) {
index = nestedDir.indexOf('/', index + 1);
}
const name: string = index === -1 ? nestedDir.slice(13) : nestedDir.slice(13, index);
if (name.startsWith('.')) {
continue;
}
if (!foundBundledDependencies) {
foundBundledDependencies = true;
// Make a copy of the nestedPackageDirs array so that we don't mutate the version being
// saved into the subpackage index cache.
context.nestedPackageDirs = nestedPackageDirs = nestedPackageDirs.slice(0);
}
// Remove this nested package from the list
nestedPackageDirs.splice(i, 1);
const remainder: string = index === -1 ? '' : nestedDir.slice(index + 1);
const nestedRoot: string = `${context.descriptionFileRoot}/node_modules/${name}`;
let nestedContext: IResolverContext | undefined = contexts.get(nestedRoot);
if (!nestedContext) {
nestedContext = {
descriptionFileRoot: nestedRoot,
descriptionFileHash: undefined,
isProject: false,
name,
deps: new Map(),
ordinal: -1
};
contexts.set(nestedRoot, nestedContext);
}
context.deps.set(name, nestedRoot);
if (remainder) {
nestedContext.nestedPackageDirs ??= [];
nestedContext.nestedPackageDirs.push(remainder);
}
}
}
/**
* Options for computing the resolver cache from a lockfile.
*/
export interface IComputeResolverCacheFromLockfileOptions {
/**
* The root folder of the workspace being installed
*/
workspaceRoot: string;
/**
* The common root path to trim from the description file roots for brevity
*/
commonPrefixToTrim: string;
/**
* Information about the platform Rush is running on
*/
platformInfo: IPlatformInfo;
/**
* A lookup of projects by their importer path
*/
projectByImporterPath: Pick<LookupByPath<IPartialRushProject>, 'findChildPath'>;
/**
* The lockfile to compute the cache from
*/
lockfile: PnpmShrinkwrapFile;
/**
* A callback to process external packages after they have been enumerated.
* Broken out as a separate function to facilitate testing without hitting the disk.
* @remarks This is useful for fetching additional data from the pnpm store
* @param contexts - The current context information per description file root
* @param missingOptionalDependencies - The set of optional dependencies that were not installed
* @returns A promise that resolves when the external packages have been processed
*/
afterExternalPackagesAsync?: (
contexts: Map<string, IResolverContext>,
missingOptionalDependencies: Set<string>
) => Promise<void>;
}
/**
* Copied from `@rushstack/node-core-library/src/Path.ts` to avoid expensive dependency
* @param path - Path using backslashes as path separators
* @returns The same string using forward slashes as path separators
*/
function convertToSlashes(path: string): string {
return path.replace(/\\/g, '/');
}
/**
* Given a lockfile and information about the workspace and platform, computes the resolver cache file.
* @param params - The options for computing the resolver cache
* @returns A promise that resolves with the resolver cache file
*/
export async function computeResolverCacheFromLockfileAsync(
params: IComputeResolverCacheFromLockfileOptions
): Promise<IResolverCacheFile> {
const { platformInfo, projectByImporterPath, lockfile, afterExternalPackagesAsync } = params;
// Needs to be normalized to `/` for path.posix.join to work correctly
const workspaceRoot: string = convertToSlashes(params.workspaceRoot);
// Needs to be normalized to `/` for path.posix.join to work correctly
const commonPrefixToTrim: string = convertToSlashes(params.commonPrefixToTrim);
const contexts: Map<string, IResolverContext> = new Map();
const missingOptionalDependencies: Set<string> = new Set();
// Enumerate external dependencies first, to simplify looping over them for store data
for (const [key, pack] of lockfile.packages) {
let name: string | undefined = pack.name;
const descriptionFileRoot: string = getDescriptionFileRootFromKey(workspaceRoot, key, name);
// Skip optional dependencies that are incompatible with the current environment
if (pack.optional && !isPackageCompatible(pack, platformInfo)) {
missingOptionalDependencies.add(descriptionFileRoot);
continue;
}
const integrity: string | undefined = pack.resolution?.integrity;
// Extract name and version from the key if not already provided
const parsed: { name: string; version: string } | undefined = extractNameAndVersionFromKey(key);
if (parsed) {
if (!name) {
name = parsed.name;
}
}
if (!name) {
throw new Error(`Missing name for ${key}`);
}
const context: IResolverContext = {
descriptionFileRoot,
descriptionFileHash: integrity,
isProject: false,
name,
version: parsed?.version,
deps: new Map(),
ordinal: -1,
optional: pack.optional
};
contexts.set(descriptionFileRoot, context);
if (pack.dependencies) {
resolveDependencies(workspaceRoot, pack.dependencies, context, lockfile.packages);
}
if (pack.optionalDependencies) {
resolveDependencies(workspaceRoot, pack.optionalDependencies, context, lockfile.packages);
}
}
if (afterExternalPackagesAsync) {
await afterExternalPackagesAsync(contexts, missingOptionalDependencies);
}
for (const context of contexts.values()) {
if (context.nestedPackageDirs) {
extractBundledDependencies(contexts, context);
}
}
// Add the data for workspace projects
for (const [importerPath, importer] of lockfile.importers) {
// Ignore the root project. This plugin assumes you don't have one.
// A non-empty root project results in global dependency hoisting, and that's bad for strictness.
if (importerPath === '.') {
continue;
}
const project: IPartialRushProject | undefined = projectByImporterPath.findChildPath(importerPath);
if (!project) {
throw new Error(`Missing project for importer ${importerPath}`);
}
const descriptionFileRoot: string = convertToSlashes(project.projectFolder);
const context: IResolverContext = {
descriptionFileRoot,
descriptionFileHash: undefined, // Not needed anymore
name: project.packageJson.name,
isProject: true,
deps: new Map(),
ordinal: -1
};
contexts.set(descriptionFileRoot, context);
if (importer.dependencies) {
resolveDependencies(workspaceRoot, importer.dependencies, context, lockfile.packages);
}
if (importer.devDependencies) {
resolveDependencies(workspaceRoot, importer.devDependencies, context, lockfile.packages);
}
if (importer.optionalDependencies) {
resolveDependencies(workspaceRoot, importer.optionalDependencies, context, lockfile.packages);
}
}
let ordinal: number = 0;
for (const context of contexts.values()) {
context.ordinal = ordinal++;
}
// Convert the intermediate representation to the final cache file
const serializedContexts: ISerializedResolveContext[] = Array.from(
contexts,
createContextSerializer(missingOptionalDependencies, contexts, commonPrefixToTrim)
);
const cacheFile: IResolverCacheFile = {
basePath: commonPrefixToTrim,
contexts: serializedContexts
};
return cacheFile;
}