-
Notifications
You must be signed in to change notification settings - Fork 965
Expand file tree
/
Copy pathpnpm.package-manager.ts
More file actions
501 lines (474 loc) · 19.9 KB
/
Copy pathpnpm.package-manager.ts
File metadata and controls
501 lines (474 loc) · 19.9 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import type { CloudMain } from '@teambit/cloud';
import { extendWithComponentsFromDir, BIT_CLOUD_REGISTRY } from '@teambit/dependency-resolver';
import type {
DependencyResolverMain,
InstallationContext,
PackageManager,
PackageManagerInstallOptions,
PackageManagerResolveRemoteVersionOptions,
ResolvedPackageVersion,
PackageManagerProxyConfig,
PackageManagerNetworkConfig,
CalcDepsGraphOptions,
} from '@teambit/dependency-resolver';
import { Registries, Registry } from '@teambit/pkg.entities.registry';
import { DEPS_GRAPH, isFeatureEnabled } from '@teambit/harmony.modules.feature-toggle';
import type { Logger } from '@teambit/logger';
import { type LockfileFile } from '@pnpm/lockfile.types';
import fs from 'fs';
import { memoize, omit } from 'lodash';
import type { PeerDependencyIssuesByProjects } from '@pnpm/core';
import { filterLockfileByImporters } from '@pnpm/lockfile.filtering';
import type { Config } from '@pnpm/config';
import { type ProjectId, type ProjectManifest, type DepPath } from '@pnpm/types';
import type { Modules } from '@pnpm/modules-yaml';
import { readModulesManifest } from '@pnpm/modules-yaml';
import type { ImporterInfo } from '@pnpm/reviewing.dependencies-hierarchy';
import { buildDependentsTree } from '@pnpm/reviewing.dependencies-hierarchy';
import { renderDependentsTree } from '@pnpm/list';
import {
readWantedLockfile,
writeLockfileFile,
convertToLockfileFile as convertLockfileObjectToLockfileFile,
} from '@pnpm/lockfile.fs';
import { BIT_ROOTS_DIR } from '@teambit/legacy.constants';
import { ServerSendOutStream } from '@teambit/legacy.logger';
import { join } from 'path';
import { convertLockfileToGraph, convertGraphToLockfile } from './lockfile-deps-graph-converter';
import { readConfig } from './read-config';
import { pnpmPruneModules } from './pnpm-prune-modules';
import type { RebuildFn } from './lynx';
import { generateResolverAndFetcher } from './lynx';
import { type DependenciesGraph } from '@teambit/objects';
export type { RebuildFn };
export interface InstallResult {
dependenciesChanged: boolean;
rebuild: RebuildFn;
storeDir: string;
depsRequiringBuild?: DepPath[];
}
type ReadConfigResult = Promise<{ config: Config; warnings: string[] }>;
export class PnpmPackageManager implements PackageManager {
readonly name = 'pnpm';
readonly modulesManifestCache: Map<string, Modules> = new Map();
private username: string;
private _readConfig = async (dir?: string): ReadConfigResult => {
const { config, warnings } = await readConfig(dir);
if (config?.fetchRetries && config?.fetchRetries < 5) {
config.fetchRetries = 5;
return { config, warnings };
}
return { config, warnings };
};
public readConfig: (dir?: string) => ReadConfigResult = memoize(this._readConfig);
constructor(
private depResolver: DependencyResolverMain,
private logger: Logger,
private cloud: CloudMain
) {}
async dependenciesGraphToLockfile(
dependenciesGraph: DependenciesGraph,
opts: {
cacheDir: string;
manifests: Record<string, ProjectManifest>;
rootDir: string;
registries?: Registries;
proxyConfig?: PackageManagerProxyConfig;
networkConfig?: PackageManagerNetworkConfig;
}
) {
const registries = opts.registries ?? new Registries(new Registry('https://node-registry.bit.cloud', false), {});
const { resolve } = await generateResolverAndFetcher({
...opts,
registries,
});
const lockfile: LockfileFile = await convertGraphToLockfile(dependenciesGraph, {
...opts,
resolve,
});
Object.assign(lockfile, {
bit: {
restoredFromModel: true,
},
});
const lockfilePath = join(opts.rootDir, 'pnpm-lock.yaml');
await writeLockfileFile(lockfilePath, lockfile);
this.logger.debug(`generated a lockfile from dependencies graph at ${lockfilePath}`);
if (process.env.DEPS_GRAPH_LOG) {
// eslint-disable-next-line no-console
console.log(`generated a lockfile from dependencies graph at ${lockfilePath}`);
}
}
async install(
{ rootDir, manifests }: InstallationContext,
installOptions: PackageManagerInstallOptions = {}
): Promise<InstallResult> {
// require it dynamically for performance purpose. the pnpm package require many files - do not move to static import
// eslint-disable-next-line global-require, import/no-dynamic-require
const { install } = require('./lynx');
const registries = await this.depResolver.getRegistries();
const proxyConfig = await this.depResolver.getProxyConfig();
const networkConfig = await this.depResolver.getNetworkConfig();
const { config } = await this.readConfig(installOptions.packageManagerConfigRootDir);
if (
installOptions.dependenciesGraph &&
isFeatureEnabled(DEPS_GRAPH) &&
(installOptions.rootComponents || installOptions.rootComponentsForCapsules)
) {
try {
await this.dependenciesGraphToLockfile(installOptions.dependenciesGraph, {
manifests,
rootDir,
registries,
proxyConfig,
networkConfig,
cacheDir: config.cacheDir,
});
} catch (error) {
// If the lockfile could not be created for some reason, it will be created later during installation.
this.logger.error((error as Error).message);
}
}
this.logger.debug(`running installation in root dir ${rootDir}`);
this.logger.debug('components manifests for installation', manifests);
if (!installOptions.hidePackageManagerOutput) {
// this.logger.setStatusLine('installing dependencies using pnpm');
// turn off the logger because it interrupts the pnpm output
// this.logger.console('-------------------------PNPM OUTPUT-------------------------');
this.logger.off();
}
if (!installOptions.useNesting && installOptions.rootComponentsForCapsules) {
manifests = await extendWithComponentsFromDir(rootDir, manifests);
}
if (installOptions.nmSelfReferences) {
Object.values(manifests).forEach((manifest) => {
if (manifest.name) {
manifest.devDependencies = {
[manifest.name]: 'link:.',
...manifest.devDependencies,
};
}
});
}
this.modulesManifestCache.delete(rootDir);
const { dependenciesChanged, rebuild, storeDir, depsRequiringBuild } = await install(
rootDir,
manifests,
config.storeDir,
config.cacheDir,
registries,
proxyConfig,
networkConfig,
{
autoInstallPeers: installOptions.autoInstallPeers ?? true,
enableModulesDir: installOptions.enableModulesDir,
engineStrict: installOptions.engineStrict ?? config.engineStrict,
excludeLinksFromLockfile: installOptions.excludeLinksFromLockfile,
lockfileOnly: installOptions.lockfileOnly,
frozenLockfile: installOptions.frozenLockfile,
minimumReleaseAge: installOptions.minimumReleaseAge,
minimumReleaseAgeExclude: installOptions.minimumReleaseAgeExclude,
neverBuiltDependencies: installOptions.neverBuiltDependencies,
allowScripts: installOptions.allowScripts,
dangerouslyAllowAllScripts: installOptions.dangerouslyAllowAllScripts,
nodeLinker: installOptions.nodeLinker,
nodeVersion: installOptions.nodeVersion ?? config.nodeVersion,
includeOptionalDeps: installOptions.includeOptionalDeps,
ignorePackageManifest: installOptions.ignorePackageManifest,
dedupeInjectedDeps: installOptions.dedupeInjectedDeps ?? false,
dryRun: installOptions.dependenciesGraph == null && installOptions.dryRun,
overrides: installOptions.overrides,
hoistPattern: installOptions.hoistPatterns ?? config.hoistPattern,
publicHoistPattern: config.shamefullyHoist
? ['*']
: ['@eslint/plugin-*', '*eslint-plugin*', '@prettier/plugin-*', '*prettier-plugin-*'],
hoistWorkspacePackages: installOptions.hoistWorkspacePackages ?? false,
hoistInjectedDependencies: installOptions.hoistInjectedDependencies,
packageImportMethod: installOptions.packageImportMethod ?? config.packageImportMethod,
preferOffline: installOptions.preferOffline,
rootComponents: installOptions.rootComponents,
rootComponentsForCapsules: installOptions.rootComponentsForCapsules,
sideEffectsCacheRead: installOptions.sideEffectsCache ?? true,
sideEffectsCacheWrite: installOptions.sideEffectsCache ?? true,
pnpmHomeDir: config.pnpmHomeDir,
updateAll: installOptions.updateAll,
hidePackageManagerOutput: installOptions.hidePackageManagerOutput,
reportOptions: {
appendOnly: installOptions.optimizeReportForNonTerminal,
process: process.env.BIT_CLI_SERVER_NO_TTY ? { ...process, stdout: new ServerSendOutStream() } : undefined,
throttleProgress: installOptions.throttleProgress,
hideProgressPrefix: installOptions.hideProgressPrefix,
hideLifecycleOutput: installOptions.hideLifecycleOutput,
peerDependencyRules: installOptions.peerDependencyRules,
},
returnListOfDepsRequiringBuild: installOptions.returnListOfDepsRequiringBuild,
forcedHarmonyVersion: installOptions.forcedHarmonyVersion,
},
this.logger
);
if (!installOptions.hidePackageManagerOutput) {
this.logger.on();
// Make a divider row to improve output
// this.logger.console('-------------------------END PNPM OUTPUT-------------------------');
// this.logger.consoleSuccess('installing dependencies using pnpm');
}
return { dependenciesChanged, rebuild, storeDir, depsRequiringBuild };
}
async getPeerDependencyIssues(
rootDir: string,
manifests: Record<string, ProjectManifest>,
installOptions: PackageManagerInstallOptions = {}
): Promise<PeerDependencyIssuesByProjects> {
const proxyConfig = await this.depResolver.getProxyConfig();
const networkConfig = await this.depResolver.getNetworkConfig();
const registries = await this.depResolver.getRegistries();
// require it dynamically for performance purpose. the pnpm package require many files - do not move to static import
// eslint-disable-next-line global-require, import/no-dynamic-require
const lynx = require('./lynx');
const { config } = await this.readConfig(installOptions.packageManagerConfigRootDir);
return lynx.getPeerDependencyIssues(manifests, {
storeDir: config.storeDir,
cacheDir: config.cacheDir,
proxyConfig,
registries,
rootDir,
networkConfig,
overrides: installOptions.overrides,
packageImportMethod: installOptions.packageImportMethod ?? config.packageImportMethod,
});
}
async resolveRemoteVersion(
packageName: string,
options: PackageManagerResolveRemoteVersionOptions
): Promise<ResolvedPackageVersion> {
// require it dynamically for performance purpose. the pnpm package require many files - do not move to static import
// eslint-disable-next-line global-require, import/no-dynamic-require
const { resolveRemoteVersion } = require('./lynx');
const registries = await this.depResolver.getRegistries();
const proxyConfig = await this.depResolver.getProxyConfig();
const networkConfig = await this.depResolver.getNetworkConfig();
const { config } = await this.readConfig(options.packageManagerConfigRootDir);
return resolveRemoteVersion(packageName, {
rootDir: options.rootDir,
cacheDir: config.cacheDir,
registries,
proxyConfig,
networkConfig,
fullMetadata: options.fullMetadata,
});
}
async getProxyConfig?(): Promise<PackageManagerProxyConfig> {
// eslint-disable-next-line global-require, import/no-dynamic-require
const { getProxyConfig } = require('./get-proxy-config');
const { config } = await this.readConfig();
return getProxyConfig(config);
}
async getNetworkConfig?(): Promise<PackageManagerNetworkConfig> {
const { config } = await this.readConfig();
if (!this.username) {
this.username = (await this.cloud.getCurrentUser())?.username ?? 'anonymous';
}
// We need to use config.rawConfig as it will only contain the settings defined by the user.
// config contains default values of the settings when they are not defined by the user.
const result: PackageManagerNetworkConfig = {
userAgent: `bit user/${this.username}`,
};
if (config.rawConfig['max-sockets'] != null) {
result.maxSockets = config.rawConfig['max-sockets'];
}
if (config.rawConfig['network-concurrency'] != null) {
result.networkConcurrency = config.rawConfig['network-concurrency'];
}
if (config.rawConfig['fetch-retries'] != null) {
result.fetchRetries = config.rawConfig['fetch-retries'];
}
if (config.rawConfig['fetch-timeout'] != null) {
result.fetchTimeout = config.rawConfig['fetch-timeout'];
}
if (config.rawConfig['fetch-retry-maxtimeout'] != null) {
result.fetchRetryMaxtimeout = config.rawConfig['fetch-retry-maxtimeout'];
}
if (config.rawConfig['fetch-retry-mintimeout'] != null) {
result.fetchRetryMintimeout = config.rawConfig['fetch-retry-mintimeout'];
}
if (config.rawConfig['strict-ssl'] != null) {
result.strictSSL = config.rawConfig['strict-ssl'];
}
if (config.ca != null) {
result.ca = config.ca;
}
if (config.cert != null) {
result.cert = config.cert;
}
if (config.key != null) {
result.key = config.key;
}
return result;
}
async getRegistries(): Promise<Registries> {
// eslint-disable-next-line global-require, import/no-dynamic-require
const { getRegistries } = require('./get-registries');
const { config } = await this.readConfig();
const pnpmRegistry = await getRegistries(config);
const defaultRegistry = new Registry(
pnpmRegistry.default.uri,
pnpmRegistry.default.alwaysAuth,
pnpmRegistry.default.authHeaderValue,
pnpmRegistry.default.originalAuthType,
pnpmRegistry.default.originalAuthValue
);
const pnpmScoped = omit(pnpmRegistry, ['default']);
const scopesRegistries: Record<string, Registry> = Object.keys(pnpmScoped).reduce((acc, scopedRegName) => {
const scopedReg = pnpmScoped[scopedRegName];
const name = scopedRegName.replace('@', '');
acc[name] = new Registry(
scopedReg.uri,
scopedReg.alwaysAuth,
scopedReg.authHeaderValue,
scopedReg.originalAuthType,
scopedReg.originalAuthValue
);
return acc;
}, {});
// Add bit registry server if not exist
if (!scopesRegistries.bit) {
scopesRegistries.bit = new Registry(BIT_CLOUD_REGISTRY, true);
}
return new Registries(defaultRegistry, scopesRegistries);
}
async getInjectedDirs(rootDir: string, componentDir: string, packageName: string): Promise<string[]> {
const modulesState = await this._readModulesManifest(rootDir);
if (modulesState?.injectedDeps == null) return [];
return modulesState.injectedDeps[`node_modules/${packageName}`] ?? modulesState.injectedDeps[componentDir] ?? [];
}
async _readModulesManifest(lockfileDir: string): Promise<Modules | undefined> {
if (this.modulesManifestCache.has(lockfileDir)) {
return this.modulesManifestCache.get(lockfileDir);
}
const modulesManifest = await readModulesManifest(join(lockfileDir, 'node_modules'));
if (modulesManifest) {
this.modulesManifestCache.set(lockfileDir, modulesManifest);
}
return modulesManifest ?? undefined;
}
getWorkspaceDepsOfBitRoots(manifests: ProjectManifest[]): Record<string, string> {
return Object.fromEntries(manifests.map((manifest) => [manifest.name, 'workspace:*']));
}
async pruneModules(rootDir: string): Promise<void> {
return pnpmPruneModules(rootDir);
}
async findUsages(depName: string, opts: { lockfileDir: string; depth?: number }): Promise<string> {
const lockfile = await readWantedLockfile(opts.lockfileDir, { ignoreIncompatible: false });
if (!lockfile) return '';
const importerIds = Object.keys(lockfile.importers ?? {}).filter((id) => !id.includes(`${BIT_ROOTS_DIR}/`));
const projectPaths = importerIds.map((id) => join(opts.lockfileDir, id));
const importerInfoMap = new Map<string, ImporterInfo>();
for (const importerId of importerIds) {
const pkgJson = tryReadPackageJson(join(opts.lockfileDir, importerId));
importerInfoMap.set(importerId, {
name: pkgJson?.name ?? importerId,
version: pkgJson?.version ?? '',
});
}
const trees = await buildDependentsTree([depName], projectPaths, {
include: {
dependencies: true,
devDependencies: true,
optionalDependencies: true,
},
lockfileDir: opts.lockfileDir,
registries: {
default: 'https://registry.npmjs.org',
},
importerInfoMap,
lockfile,
nameFormatter({ manifest }) {
if ('componentId' in manifest) {
const { scope, name } = manifest.componentId as { scope: string; name: string };
return `${scope}/${name}`;
}
return manifest.name;
},
});
return renderDependentsTree(trees, {
depth: opts.depth ?? Infinity,
long: false,
});
}
/**
* Calculating the dependencies graph of a given component using the lockfile.
*/
async calcDependenciesGraph(opts: CalcDepsGraphOptions): Promise<void> {
const originalLockfile = await readWantedLockfile(opts.rootDir, { ignoreIncompatible: false });
if (!originalLockfile) {
return;
}
for (const { componentRootDir, componentRelativeDir, pkgName, component } of opts.components) {
let compRootDir: string | undefined;
if (componentRootDir && !originalLockfile.importers[componentRootDir] && componentRootDir.includes('@')) {
compRootDir = componentRootDir.split('@')[0];
} else {
compRootDir = componentRootDir;
}
if (!originalLockfile.importers[compRootDir as ProjectId]) {
continue;
}
const filterByImporterIds = [componentRelativeDir as ProjectId];
if (compRootDir != null) {
filterByImporterIds.push(compRootDir as ProjectId);
}
// Only clone the importers that will be mutated, reuse the rest of the lockfile as-is
const clonedImporters: Record<string, any> = {};
for (const importerId of filterByImporterIds) {
if (originalLockfile.importers[importerId]) {
clonedImporters[importerId] = structuredClone(originalLockfile.importers[importerId]);
}
}
const lockfile = {
...originalLockfile,
importers: { ...originalLockfile.importers, ...clonedImporters },
};
for (const importerId of filterByImporterIds) {
for (const depType of [
'dependencies',
'devDependencies',
'optionalDependencies',
'specifiers',
'dependenciesMeta',
]) {
for (const workspacePkgName of opts.componentIdByPkgName.keys()) {
if (workspacePkgName !== pkgName) {
delete lockfile.importers[importerId]?.[depType]?.[workspacePkgName];
}
}
}
}
// Filters the lockfile so that it only includes packages related to the given component.
const partialLockfile = convertLockfileObjectToLockfileFile(
filterLockfileByImporters(lockfile, filterByImporterIds, {
include: {
dependencies: true,
devDependencies: true,
optionalDependencies: true,
},
failOnMissingDependencies: false,
skipped: new Set(),
})
);
const graph = convertLockfileToGraph(partialLockfile, {
...opts,
componentRootDir: compRootDir,
componentRelativeDir,
pkgName,
});
component.state._consumer.dependenciesGraph = graph;
}
}
}
function tryReadPackageJson(pkgDir: string) {
try {
return JSON.parse(fs.readFileSync(join(pkgDir, 'package.json'), 'utf8'));
} catch {
return undefined;
}
}