-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathpnpm-parser.ts
651 lines (605 loc) · 18.2 KB
/
pnpm-parser.ts
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import type {
Lockfile,
PackageSnapshot,
PackageSnapshots,
ProjectSnapshot,
} from '@pnpm/lockfile-types';
import {
isV5Syntax,
loadPnpmHoistedDepsDefinition,
parseAndNormalizePnpmLockfile,
stringifyToPnpmYaml,
} from './utils/pnpm-normalizer';
import {
getHoistedPackageVersion,
NormalizedPackageJson,
} from './utils/package-json';
import { sortObjectByKeys } from '../../../utils/object-sort';
import {
RawProjectGraphDependency,
validateDependency,
} from '../../../project-graph/project-graph-builder';
import {
DependencyType,
ProjectGraph,
ProjectGraphExternalNode,
} from '../../../config/project-graph';
import { hashArray } from '../../../hasher/file-hasher';
import { CreateDependenciesContext } from '../../../project-graph/plugins';
// we use key => node map to avoid duplicate work when parsing keys
let keyMap = new Map<string, Set<ProjectGraphExternalNode>>();
let currentLockFileHash: string;
let parsedLockFile: Lockfile;
function parsePnpmLockFile(
lockFileContent: string,
lockFileHash: string
): Lockfile {
if (lockFileHash === currentLockFileHash) {
return parsedLockFile;
}
keyMap.clear();
const results = parseAndNormalizePnpmLockfile(lockFileContent);
parsedLockFile = results;
currentLockFileHash = lockFileHash;
return results;
}
export function getPnpmLockfileNodes(
lockFileContent: string,
lockFileHash: string
): Record<string, ProjectGraphExternalNode> {
const data = parsePnpmLockFile(lockFileContent, lockFileHash);
if (+data.lockfileVersion.toString() >= 10) {
console.warn(
'Nx was tested only with pnpm lockfile version 5-9. If you encounter any issues, please report them and downgrade to older version of pnpm.'
);
}
const isV5 = isV5Syntax(data);
return getNodes(data, keyMap, isV5);
}
export function getPnpmLockfileDependencies(
lockFileContent: string,
lockFileHash: string,
ctx: CreateDependenciesContext
) {
const data = parsePnpmLockFile(lockFileContent, lockFileHash);
if (+data.lockfileVersion.toString() >= 10) {
console.warn(
'Nx was tested only with pnpm lockfile version 5-9. If you encounter any issues, please report them and downgrade to older version of pnpm.'
);
}
const isV5 = isV5Syntax(data);
return getDependencies(data, keyMap, isV5, ctx);
}
function matchPropValue(
record: Record<string, string>,
key: string,
originalPackageName: string
): string | undefined {
if (!record) {
return undefined;
}
const index = Object.values(record).findIndex((version) => version === key);
if (index > -1) {
return Object.keys(record)[index];
}
// check if non-aliased name is found
if (
record[originalPackageName] &&
key.startsWith(`/${originalPackageName}/${record[originalPackageName]}`)
) {
return originalPackageName;
}
}
function matchedDependencyName(
importer: Partial<PackageSnapshot>,
key: string,
originalPackageName: string
): string | undefined {
return (
matchPropValue(importer.dependencies, key, originalPackageName) ||
matchPropValue(importer.optionalDependencies, key, originalPackageName) ||
matchPropValue(importer.peerDependencies, key, originalPackageName)
);
}
function createHashFromSnapshot(snapshot: PackageSnapshot) {
return (
snapshot.resolution?.['integrity'] ||
(snapshot.resolution?.['tarball']
? hashArray([snapshot.resolution['tarball']])
: undefined)
);
}
function isAliasVersion(depVersion: string) {
return depVersion.startsWith('/') || depVersion.includes('@');
}
function getNodes(
data: Lockfile,
keyMap: Map<string, Set<ProjectGraphExternalNode>>,
isV5: boolean
): Record<string, ProjectGraphExternalNode> {
const nodes: Map<string, Map<string, ProjectGraphExternalNode>> = new Map();
const maybeAliasedPackageVersions = new Map<string, string>(); // <version, alias>
if (data.importers['.'].optionalDependencies) {
for (const [depName, depVersion] of Object.entries(
data.importers['.'].optionalDependencies
)) {
if (isAliasVersion(depVersion)) {
maybeAliasedPackageVersions.set(depVersion, depName);
}
}
}
if (data.importers['.'].devDependencies) {
for (const [depName, depVersion] of Object.entries(
data.importers['.'].devDependencies
)) {
if (isAliasVersion(depVersion)) {
maybeAliasedPackageVersions.set(depVersion, depName);
}
}
}
if (data.importers['.'].dependencies) {
for (const [depName, depVersion] of Object.entries(
data.importers['.'].dependencies
)) {
if (isAliasVersion(depVersion)) {
maybeAliasedPackageVersions.set(depVersion, depName);
}
}
}
const packageNames = new Set<{
key: string;
packageName: string;
hash?: string;
alias?: boolean;
}>();
let packageNameObj;
for (const [key, snapshot] of Object.entries(data.packages)) {
const originalPackageName = extractNameFromKey(key, isV5);
if (!originalPackageName) {
continue;
}
const hash = createHashFromSnapshot(snapshot);
// snapshot already has a name
if (snapshot.name) {
packageNameObj = {
key,
packageName: snapshot.name,
hash,
};
}
const rootDependencyName =
matchedDependencyName(data.importers['.'], key, originalPackageName) ||
matchedDependencyName(
data.importers['.'],
`/${key}`,
originalPackageName
) ||
// only root importers have devDependencies
matchPropValue(
data.importers['.'].devDependencies,
key,
originalPackageName
) ||
matchPropValue(
data.importers['.'].devDependencies,
`/${key}`,
originalPackageName
);
if (rootDependencyName) {
packageNameObj = {
key,
packageName: rootDependencyName,
hash: createHashFromSnapshot(snapshot),
};
}
if (!snapshot.name && !rootDependencyName) {
packageNameObj = {
key,
packageName: originalPackageName,
hash: createHashFromSnapshot(snapshot),
};
}
if (snapshot.peerDependencies) {
for (const [depName, depVersion] of Object.entries(
snapshot.peerDependencies
)) {
if (isAliasVersion(depVersion)) {
maybeAliasedPackageVersions.set(depVersion, depName);
}
}
}
if (snapshot.optionalDependencies) {
for (const [depName, depVersion] of Object.entries(
snapshot.optionalDependencies
)) {
if (isAliasVersion(depVersion)) {
maybeAliasedPackageVersions.set(depVersion, depName);
}
}
}
if (snapshot.dependencies) {
for (const [depName, depVersion] of Object.entries(
snapshot.dependencies
)) {
if (isAliasVersion(depVersion)) {
maybeAliasedPackageVersions.set(depVersion, depName);
}
}
}
const aliasedDep = maybeAliasedPackageVersions.get(`/${key}`);
if (aliasedDep) {
packageNameObj = {
key,
packageName: aliasedDep,
hash,
alias: true,
};
}
packageNames.add(packageNameObj);
const localAlias = maybeAliasedPackageVersions.get(key);
if (localAlias) {
packageNameObj = {
key,
packageName: localAlias,
hash,
alias: true,
};
packageNames.add(packageNameObj);
}
}
for (const { key, packageName, hash, alias } of packageNames) {
const rawVersion = findVersion(key, packageName, isV5, alias);
if (!rawVersion) {
continue;
}
const version = parseBaseVersion(rawVersion, isV5);
if (!version) {
continue;
}
if (!nodes.has(packageName)) {
nodes.set(packageName, new Map());
}
if (!nodes.get(packageName).has(version)) {
const node: ProjectGraphExternalNode = {
type: 'npm',
name:
version && !version.startsWith('npm:')
? `npm:${packageName}@${version}`
: `npm:${packageName}`,
data: {
version,
packageName,
hash: hash ?? hashArray([packageName, version]),
},
};
nodes.get(packageName).set(version, node);
if (!keyMap.has(key)) {
keyMap.set(key, new Set([node]));
} else {
keyMap.get(key).add(node);
}
} else {
const node = nodes.get(packageName).get(version);
if (!keyMap.has(key)) {
keyMap.set(key, new Set([node]));
} else {
keyMap.get(key).add(node);
}
}
}
const hoistedDeps = loadPnpmHoistedDepsDefinition();
const results: Record<string, ProjectGraphExternalNode> = {};
for (const [packageName, versionMap] of nodes.entries()) {
let hoistedNode: ProjectGraphExternalNode;
if (versionMap.size === 1) {
hoistedNode = versionMap.values().next().value;
} else {
const hoistedVersion = getHoistedVersion(hoistedDeps, packageName, isV5);
hoistedNode = versionMap.get(hoistedVersion);
}
if (hoistedNode) {
hoistedNode.name = `npm:${packageName}`;
}
versionMap.forEach((node) => {
results[node.name] = node;
});
}
return results;
}
function getHoistedVersion(
hoistedDependencies: Record<string, any>,
packageName: string,
isV5: boolean
): string {
let version = getHoistedPackageVersion(packageName);
if (!version) {
const key = Object.keys(hoistedDependencies).find((k) =>
k.startsWith(`/${packageName}/`)
);
if (key) {
version = parseBaseVersion(getVersion(key.slice(1), packageName), isV5);
} else {
// pnpm might not hoist every package
// similarly those packages will not be available to be used via import
return;
}
}
return version;
}
function getDependencies(
data: Lockfile,
keyMap: Map<string, Set<ProjectGraphExternalNode>>,
isV5: boolean,
ctx: CreateDependenciesContext
): RawProjectGraphDependency[] {
const results: RawProjectGraphDependency[] = [];
Object.entries(data.packages).forEach(([key, snapshot]) => {
const nodes = keyMap.get(key);
nodes.forEach((node) => {
[snapshot.dependencies, snapshot.optionalDependencies].forEach(
(section) => {
if (section) {
Object.entries(section).forEach(([name, versionRange]) => {
const version = parseBaseVersion(
findVersion(versionRange, name, isV5),
isV5
);
const target =
ctx.externalNodes[`npm:${name}@${version}`] ||
ctx.externalNodes[`npm:${name}`];
if (target) {
const dep: RawProjectGraphDependency = {
source: node.name,
target: target.name,
type: DependencyType.static,
};
validateDependency(dep, ctx);
results.push(dep);
}
});
}
}
);
});
});
return results;
}
function parseBaseVersion(rawVersion: string, isV5: boolean): string {
return isV5 ? rawVersion.split('_')[0] : rawVersion.split('(')[0];
}
export function stringifyPnpmLockfile(
graph: ProjectGraph,
rootLockFileContent: string,
packageJson: NormalizedPackageJson
): string {
const data = parseAndNormalizePnpmLockfile(rootLockFileContent);
const { lockfileVersion, packages } = data;
const rootSnapshot = mapRootSnapshot(
packageJson,
packages,
graph.externalNodes,
+lockfileVersion
);
const snapshots = mapSnapshots(
data.packages,
graph.externalNodes,
+lockfileVersion
);
const output: Lockfile = {
...data,
lockfileVersion,
importers: {
'.': rootSnapshot,
},
packages: sortObjectByKeys(snapshots),
};
return stringifyToPnpmYaml(output);
}
function mapSnapshots(
packages: PackageSnapshots,
nodes: Record<string, ProjectGraphExternalNode>,
lockfileVersion: number
): PackageSnapshots {
const result: PackageSnapshots = {};
Object.values(nodes).forEach((node) => {
const matchedKeys = findOriginalKeys(packages, node, lockfileVersion, {
returnFullKey: true,
});
// the package manager doesn't check for types of dependencies
// so we can safely set all to prod
matchedKeys.forEach(([key, snapshot]) => {
if (lockfileVersion >= 9) {
delete snapshot['dev'];
result[key] = snapshot;
} else {
snapshot['dev'] = false; // all dependencies are prod
remapDependencies(snapshot);
if (snapshot.resolution?.['tarball']) {
// tarballs are not prefixed with /
result[key] = snapshot;
} else {
result[`/${key}`] = snapshot;
}
}
});
});
return result;
}
function remapDependencies(snapshot: PackageSnapshot) {
[
'dependencies',
'optionalDependencies',
'devDependencies',
'peerDependencies',
].forEach((depType) => {
if (snapshot[depType]) {
for (const [packageName, version] of Object.entries(
snapshot[depType] as Record<string, string>
)) {
if (version.match(/^[a-zA-Z]+.*/)) {
// remap packageName@version to packageName/version
snapshot[depType][packageName] = `/${version.replace(
/([a-zA-Z].+)@/,
'$1/'
)}`;
}
}
}
});
}
function findOriginalKeys(
packages: PackageSnapshots,
{ data: { packageName, version } }: ProjectGraphExternalNode,
lockfileVersion: number,
{ returnFullKey }: { returnFullKey?: boolean } = {}
): Array<[string, PackageSnapshot]> {
const matchedKeys = [];
for (const key of Object.keys(packages)) {
const snapshot = packages[key];
// tarball package
if (
key.startsWith(`${packageName}@${version}`) &&
snapshot.resolution?.['tarball']
) {
matchedKeys.push([getVersion(key, packageName), snapshot]);
}
// standard package
if (lockfileVersion < 6 && key.startsWith(`${packageName}/${version}`)) {
matchedKeys.push([
returnFullKey ? key : getVersion(key, packageName),
snapshot,
]);
}
if (
lockfileVersion >= 6 &&
lockfileVersion < 9 &&
key.startsWith(`${packageName}@${version}`)
) {
matchedKeys.push([
// we need to replace the @ with / for v5-7 syntax because the dpParse function expects old format
returnFullKey
? key.replace(
`${packageName}@${version}`,
`${packageName}/${version}`
)
: getVersion(key, packageName),
snapshot,
]);
}
if (lockfileVersion >= 9 && key.startsWith(`${packageName}@${version}`)) {
matchedKeys.push([
returnFullKey ? key : getVersion(key, packageName),
snapshot,
]);
}
// alias package
if (versionIsAlias(key, version, lockfileVersion)) {
if (lockfileVersion >= 9) {
// no postprocessing needed for v9
matchedKeys.push([key, snapshot]);
} else {
// for root specifiers we need to ensure alias is prefixed with /
const prefixedKey = returnFullKey ? key : `/${key}`;
const mappedKey = prefixedKey.replace(/(\/?..+)@/, '$1/');
matchedKeys.push([mappedKey, snapshot]);
}
}
}
return matchedKeys;
}
// check if version has a form of npm:packageName@version and
// key starts with /packageName/version
function versionIsAlias(
key: string,
versionExpr: string,
lockfileVersion: number
): boolean {
const PREFIX = 'npm:';
if (!versionExpr.startsWith(PREFIX)) return false;
const indexOfVersionSeparator = versionExpr.indexOf('@', PREFIX.length + 1);
const packageName = versionExpr.slice(PREFIX.length, indexOfVersionSeparator);
const version = versionExpr.slice(indexOfVersionSeparator + 1);
return lockfileVersion < 6
? key.startsWith(`${packageName}/${version}`)
: key.startsWith(`${packageName}@${version}`);
}
function mapRootSnapshot(
packageJson: NormalizedPackageJson,
packages: PackageSnapshots,
nodes: Record<string, ProjectGraphExternalNode>,
lockfileVersion: number
): ProjectSnapshot {
const snapshot: ProjectSnapshot = { specifiers: {} };
[
'dependencies',
'optionalDependencies',
'devDependencies',
'peerDependencies',
].forEach((depType) => {
if (packageJson[depType]) {
Object.keys(packageJson[depType]).forEach((packageName) => {
const version = packageJson[depType][packageName];
const node =
nodes[`npm:${packageName}@${version}`] || nodes[`npm:${packageName}`];
snapshot.specifiers[packageName] = version;
// peer dependencies are mapped to dependencies
let section = depType === 'peerDependencies' ? 'dependencies' : depType;
snapshot[section] = snapshot[section] || {};
snapshot[section][packageName] = findOriginalKeys(
packages,
node,
lockfileVersion
)[0][0];
});
}
});
Object.keys(snapshot).forEach((key) => {
snapshot[key] = sortObjectByKeys(snapshot[key]);
});
return snapshot;
}
function findVersion(
key: string,
packageName: string,
isV5: boolean,
alias?: boolean
): string {
if (isV5 && key.startsWith(`${packageName}/`)) {
return getVersion(key, packageName);
}
// this matches v6 syntax and tarball packages
if (key.startsWith(`${packageName}@`)) {
return getVersion(key, packageName);
}
if (alias) {
const aliasName = isV5
? key.slice(0, key.lastIndexOf('/'))
: key.slice(0, key.indexOf('@', 2)); // we use 2 to ensure we don't catch the first @
const version = getVersion(key, aliasName);
return `npm:${aliasName}@${version}`;
}
// for tarball package the entire key is the version spec
return key;
}
function getVersion(key: string, packageName: string): string {
return key.slice(packageName.length + 1);
}
function extractNameFromKey(key: string, isV5: boolean): string {
// if package name contains org e.g. "@babel/[email protected]"
if (key.startsWith('@')) {
if (isV5) {
const startFrom = key.indexOf('/');
return key.slice(0, key.indexOf('/', startFrom + 1));
} else {
// find the position of the '@'
return key.slice(0, key.indexOf('@', 1));
}
}
if (isV5) {
// if package has just a name e.g. "react/7.12.5..."
return key.slice(0, key.indexOf('/', 1));
} else {
// if package has just a name e.g. "[email protected]..."
return key.slice(0, key.indexOf('@', 1));
}
}