-
Notifications
You must be signed in to change notification settings - Fork 683
Expand file tree
/
Copy pathPnpmShrinkwrapFile.ts
More file actions
1391 lines (1234 loc) · 53.5 KB
/
PnpmShrinkwrapFile.ts
File metadata and controls
1391 lines (1234 loc) · 53.5 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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'node:path';
import crypto from 'node:crypto';
import * as semver from 'semver';
import type {
ProjectId,
Lockfile,
PackageSnapshot,
ProjectSnapshot,
LockfileFileV9,
ResolvedDependencies
} from '@pnpm/lockfile.types-900';
import {
FileSystem,
AlreadyReportedError,
Import,
Path,
type IPackageJson,
InternalError
} from '@rushstack/node-core-library';
import { Colorize, type ITerminal } from '@rushstack/terminal';
import type { IReadonlyLookupByPath } from '@rushstack/lookup-by-path';
import { BaseShrinkwrapFile } from '../base/BaseShrinkwrapFile';
import { DependencySpecifier } from '../DependencySpecifier';
import type { RushConfiguration } from '../../api/RushConfiguration';
import type { IShrinkwrapFilePolicyValidatorOptions } from '../policy/ShrinkwrapFilePolicy';
import { PNPM_SHRINKWRAP_YAML_FORMAT } from './PnpmYamlCommon';
import { RushConstants } from '../RushConstants';
import type { IExperimentsJson } from '../../api/ExperimentsConfiguration';
import { DependencyType, type PackageJsonDependency, PackageJsonEditor } from '../../api/PackageJsonEditor';
import type { RushConfigurationProject } from '../../api/RushConfigurationProject';
import { PnpmfileConfiguration } from './PnpmfileConfiguration';
import { PnpmProjectShrinkwrapFile } from './PnpmProjectShrinkwrapFile';
import type { PackageManagerOptionsConfigurationBase } from '../base/BasePackageManagerOptionsConfiguration';
import { PnpmOptionsConfiguration } from './PnpmOptionsConfiguration';
import type { IPnpmfile, IPnpmfileContext } from './IPnpmfile';
import type { Subspace } from '../../api/Subspace';
import { CustomTipId, type CustomTipsConfiguration } from '../../api/CustomTipsConfiguration';
import { convertLockfileV9ToLockfileObject } from './PnpmShrinkWrapFileConverters';
const yamlModule: typeof import('js-yaml') = Import.lazy('js-yaml', require);
const pnpmKitV8: typeof import('@rushstack/rush-pnpm-kit-v8') = Import.lazy(
'@rushstack/rush-pnpm-kit-v8',
require
);
const pnpmKitV9: typeof import('@rushstack/rush-pnpm-kit-v9') = Import.lazy(
'@rushstack/rush-pnpm-kit-v9',
require
);
export enum ShrinkwrapFileMajorVersion {
V6 = 6,
V9 = 9
}
export interface IPeerDependenciesMetaYaml {
optional?: boolean;
}
export interface IDependenciesMetaYaml {
injected?: boolean;
}
export type IPnpmV7VersionSpecifier = string;
export interface IPnpmV8VersionSpecifier {
version: string;
specifier: string;
}
export type IPnpmV9VersionSpecifier = string;
export type IPnpmVersionSpecifier =
| IPnpmV7VersionSpecifier
| IPnpmV8VersionSpecifier
| IPnpmV9VersionSpecifier;
export interface IPnpmShrinkwrapDependencyYaml extends Omit<PackageSnapshot, 'resolution'> {
resolution: {
/** The directory this package should clone, for injected dependencies */
directory?: string;
/** The hash of the tarball, to ensure archive integrity */
integrity?: string;
/** The name of the tarball, if this was from a TGZ file */
tarball?: string;
};
}
export type IPnpmShrinkwrapImporterYaml = ProjectSnapshot;
export interface IPnpmShrinkwrapYaml extends Lockfile {
/**
* This interface represents the raw pnpm-lock.YAML file
* Example:
* {
* "dependencies": {
* "@rush-temp/project1": "file:./projects/project1.tgz"
* },
* "packages": {
* "file:projects/library1.tgz": {
* "dependencies: {
* "markdown": "0.5.0"
* },
* "name": "@rush-temp/library1",
* "resolution": {
* "tarball": "file:projects/library1.tgz"
* },
* "version": "0.0.0"
* },
* "markdown/0.5.0": {
* "resolution": {
* "integrity": "sha1-KCBbVlqK51kt4gdGPWY33BgnIrI="
* }
* }
* },
* "registry": "http://localhost:4873/",
* "shrinkwrapVersion": 3,
* "specifiers": {
* "@rush-temp/project1": "file:./projects/project1.tgz"
* }
* }
*/
/** The list of resolved version numbers for direct dependencies */
dependencies?: Record<string, string>;
/** The list of specifiers used to resolve direct dependency versions */
specifiers?: Record<string, string>;
/** URL of the registry which was used */
registry?: string;
}
export interface ILoadFromStringOptions {
subspaceHasNoProjects: boolean;
}
export interface ILoadFromFileOptions extends ILoadFromStringOptions {
withCaching?: boolean;
}
export function parsePnpm9DependencyKey(
dependencyName: string,
versionSpecifier: IPnpmVersionSpecifier
): DependencySpecifier | undefined {
if (!versionSpecifier) {
return undefined;
}
const dependencyKey: string = normalizePnpmVersionSpecifier(versionSpecifier);
// Example: file:projects/project2
// Example: project-2@file:projects/project2
// Example: link:../projects/project1
if (/(file|link):/.test(dependencyKey)) {
// If it starts with an NPM scheme such as "file:projects/my-app.tgz", we don't support that
return undefined;
}
const { peersIndex } = pnpmKitV9.dependencyPath.indexOfPeersSuffix(dependencyKey);
if (peersIndex !== -1) {
// Remove peer suffix
const key: string = dependencyKey.slice(0, peersIndex);
// Example: 7.26.0
if (semver.valid(key)) {
return DependencySpecifier.parseWithCache(dependencyName, key);
}
}
// Example: @babel/preset-env@7.26.0 -> name=@babel/preset-env version=7.26.0
// Example: @babel/preset-env@7.26.0(peer@1.2.3) -> name=@babel/preset-env version=7.26.0
// Example: https://github.com/jonschlinkert/pad-left/tarball/2.1.0 -> name=undefined version=undefined
// Example: pad-left@https://github.com/jonschlinkert/pad-left/tarball/2.1.0 -> name=pad-left nonSemverVersion=https://xxxx
// Example: pad-left@https://codeload.github.com/jonschlinkert/pad-left/tar.gz/7798d648225aa5 -> name=pad-left nonSemverVersion=https://xxxx
const dependency: import('@rushstack/rush-pnpm-kit-v9').dependencyPath.DependencyPath =
pnpmKitV9.dependencyPath.parse(dependencyKey);
const name: string = dependency.name ?? dependencyName;
const version: string = dependency.version ?? dependency.nonSemverVersion ?? dependencyKey;
// Example: https://xxxx/pad-left/tarball/2.1.0
// Example: https://github.com/jonschlinkert/pad-left/tarball/2.1.0
// Example: https://codeload.github.com/jonschlinkert/pad-left/tar.gz/7798d648225aa5d879660a37c408ab4675b65ac7
if (/^https?:/.test(version)) {
return DependencySpecifier.parseWithCache(name, version);
}
// Is it an alias for a different package?
if (name === dependencyName) {
// No, it's a regular dependency
return DependencySpecifier.parseWithCache(name, version);
} else {
// If the parsed package name is different from the dependencyName, then this is an NPM package alias
return DependencySpecifier.parseWithCache(dependencyName, `npm:${name}@${version}`);
}
}
/**
* Given an encoded "dependency key" from the PNPM shrinkwrap file, this parses it into an equivalent
* DependencySpecifier.
*
* @returns a SemVer string, or undefined if the version specifier cannot be parsed
*/
export function parsePnpmDependencyKey(
dependencyName: string,
versionSpecifier: IPnpmVersionSpecifier
): DependencySpecifier | undefined {
if (!versionSpecifier) {
return undefined;
}
const dependencyKey: string = normalizePnpmVersionSpecifier(versionSpecifier);
if (/^\w+:/.test(dependencyKey)) {
// If it starts with an NPM scheme such as "file:projects/my-app.tgz", we don't support that
return undefined;
}
// The package name parsed from the dependency key, or dependencyName if it was omitted.
// Example: "@scope/depame"
let parsedPackageName: string;
// The trailing portion of the dependency key that includes the version and optional peer dependency path.
// Example: "2.8.0/chai@3.5.0+sinon@1.17.7"
let parsedInstallPath: string;
// Example: "path.pkgs.visualstudio.com/@scope/depame/1.4.0" --> 0="@scope/depame" 1="1.4.0"
// Example: "/isarray/2.0.1" --> 0="isarray" 1="2.0.1"
// Example: "/sinon-chai/2.8.0/chai@3.5.0+sinon@1.17.7" --> 0="sinon-chai" 1="2.8.0/chai@3.5.0+sinon@1.17.7"
// Example: "/typescript@5.1.6" --> 0=typescript 1="5.1.6"
// Example: 1.2.3_peer-dependency@.4.5.6 --> no match
// Example: 1.2.3_@scope+peer-dependency@.4.5.6 --> no match
// Example: 1.2.3(peer-dependency@.4.5.6) --> no match
// Example: 1.2.3(@scope/peer-dependency@.4.5.6) --> no match
const packageNameMatch: RegExpMatchArray | null = /^[^\/(]*\/((?:@[^\/(]+\/)?[^\/(]+)[\/@](.*)$/.exec(
dependencyKey
);
if (packageNameMatch) {
parsedPackageName = packageNameMatch[1];
parsedInstallPath = packageNameMatch[2];
} else {
parsedPackageName = dependencyName;
// Example: "23.6.0_babel-core@6.26.3"
// Example: "23.6.0"
parsedInstallPath = dependencyKey;
}
// The SemVer value
// Example: "2.8.0"
let parsedVersionPart: string;
// Example: "23.6.0_babel-core@6.26.3" --> "23.6.0"
// Example: "2.8.0/chai@3.5.0+sinon@1.17.7" --> "2.8.0"
// Example: "0.53.1(@types/node@14.18.36)" --> "0.53.1"
const versionMatch: RegExpMatchArray | null = /^([^\(\/_]+)[(\/_]/.exec(parsedInstallPath);
if (versionMatch) {
parsedVersionPart = versionMatch[1];
} else {
// Example: "2.8.0"
parsedVersionPart = parsedInstallPath;
}
// By this point, we expect parsedVersionPart to be a valid SemVer range
if (!parsedVersionPart) {
return undefined;
}
if (!semver.valid(parsedVersionPart)) {
const urlRegex: RegExp =
/^(git@|@)?([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}(\/|\+)([^\/\\]+\/?)*([^\/\\]+)$/i;
// Test for urls:
// Examples:
// @github.com/abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
// github.com/abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
// github.com.au/abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
// bitbucket.com/abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
// bitbucket.com+abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
// git@bitbucket.com+abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
// bitbucket.co.in/abc/def/188ed64efd5218beda276e02f2277bf3a6b745b2
if (urlRegex.test(dependencyKey)) {
const dependencySpecifier: DependencySpecifier = DependencySpecifier.parseWithCache(
dependencyName,
dependencyKey
);
return dependencySpecifier;
} else {
return undefined;
}
}
// Is it an alias for a different package?
if (parsedPackageName === dependencyName) {
// No, it's a regular dependency
return DependencySpecifier.parseWithCache(parsedPackageName, parsedVersionPart);
} else {
// If the parsed package name is different from the dependencyName, then this is an NPM package alias
return DependencySpecifier.parseWithCache(
dependencyName,
`npm:${parsedPackageName}@${parsedVersionPart}`
);
}
}
export function normalizePnpmVersionSpecifier(versionSpecifier: IPnpmVersionSpecifier): string {
if (typeof versionSpecifier === 'string') {
return versionSpecifier;
} else {
return versionSpecifier.version;
}
}
const cacheByLockfileHash: Map<string, PnpmShrinkwrapFile | undefined> = new Map();
export class PnpmShrinkwrapFile extends BaseShrinkwrapFile {
public readonly shrinkwrapFileMajorVersion: number;
public readonly isWorkspaceCompatible: boolean;
public readonly registry: string;
public readonly dependencies: ReadonlyMap<string, IPnpmVersionSpecifier>;
public readonly importers: ReadonlyMap<string, IPnpmShrinkwrapImporterYaml>;
public readonly specifiers: ReadonlyMap<string, string>;
public readonly packages: ReadonlyMap<string, IPnpmShrinkwrapDependencyYaml>;
public readonly overrides: ReadonlyMap<string, string>;
public readonly packageExtensionsChecksum: undefined | string;
public readonly hash: string;
private readonly _shrinkwrapJson: IPnpmShrinkwrapYaml;
private readonly _integrities: Map<string, Map<string, string>>;
private _pnpmfileConfiguration: PnpmfileConfiguration | undefined;
private constructor(shrinkwrapJson: IPnpmShrinkwrapYaml, hash: string, subspaceHasNoProjects: boolean) {
super();
this.hash = hash;
this._shrinkwrapJson = shrinkwrapJson;
cacheByLockfileHash.set(hash, this);
// Normalize the data
const lockfileVersion: string | number | undefined = shrinkwrapJson.lockfileVersion;
if (typeof lockfileVersion === 'string') {
const isDotIncluded: boolean = lockfileVersion.includes('.');
this.shrinkwrapFileMajorVersion = parseInt(
lockfileVersion.substring(0, isDotIncluded ? lockfileVersion.indexOf('.') : undefined),
10
);
} else if (typeof lockfileVersion === 'number') {
this.shrinkwrapFileMajorVersion = Math.floor(lockfileVersion);
} else {
this.shrinkwrapFileMajorVersion = 0;
}
this.registry = shrinkwrapJson.registry || '';
this.dependencies = new Map(Object.entries(shrinkwrapJson.dependencies || {}));
this.importers = new Map(Object.entries(shrinkwrapJson.importers || {}));
this.specifiers = new Map(Object.entries(shrinkwrapJson.specifiers || {}));
this.packages = new Map(Object.entries(shrinkwrapJson.packages || {}));
this.overrides = new Map(Object.entries(shrinkwrapJson.overrides || {}));
this.packageExtensionsChecksum = shrinkwrapJson.packageExtensionsChecksum;
let isWorkspaceCompatible: boolean;
const importerCount: number = this.importers.size;
if (this.shrinkwrapFileMajorVersion >= ShrinkwrapFileMajorVersion.V9) {
// Lockfile v9 always has "." in importers filed.
if (subspaceHasNoProjects) {
// If there are no projects in this subspace, the "." importer will be the only importer
isWorkspaceCompatible = importerCount === 1;
} else {
isWorkspaceCompatible = importerCount > 1;
}
} else {
isWorkspaceCompatible = importerCount > 0;
}
this.isWorkspaceCompatible = isWorkspaceCompatible;
this._integrities = new Map();
}
public static getLockfileV9PackageId(name: string, version: string): string {
/**
* name@1.2.3 -> name@1.2.3
* name@1.2.3(peer) -> name@1.2.3(peer)
* https://xxx/@a/b -> name@https://xxx/@a/b
* file://xxx -> name@file://xxx
* 1.2.3 -> name@1.2.3
*/
if (/https?:/.test(version)) {
return /@https?:/.test(version) ? version : `${name}@${version}`;
} else if (/file:/.test(version)) {
return /@file:/.test(version) ? version : `${name}@${version}`;
}
return pnpmKitV9.dependencyPath.removeSuffix(version).includes('@', 1) ? version : `${name}@${version}`;
}
/**
* Clears the cache of PnpmShrinkwrapFile instances to free up memory.
*/
public static clearCache(): void {
cacheByLockfileHash.clear();
}
public static loadFromFile(
shrinkwrapYamlFilePath: string,
options: ILoadFromFileOptions
): PnpmShrinkwrapFile | undefined {
try {
const shrinkwrapContent: string = FileSystem.readFile(shrinkwrapYamlFilePath);
return PnpmShrinkwrapFile.loadFromString(shrinkwrapContent, options);
} catch (error) {
if (FileSystem.isNotExistError(error as Error)) {
return undefined; // file does not exist
}
throw new Error(`Error reading "${shrinkwrapYamlFilePath}":\n ${(error as Error).message}`);
}
}
public static loadFromString(
shrinkwrapContent: string,
options: ILoadFromStringOptions
): PnpmShrinkwrapFile {
const hash: string = crypto.createHash('sha-256').update(shrinkwrapContent, 'utf8').digest('hex');
const cached: PnpmShrinkwrapFile | undefined = cacheByLockfileHash.get(hash);
if (cached) {
return cached;
}
const { subspaceHasNoProjects } = options;
const shrinkwrapJson: IPnpmShrinkwrapYaml = yamlModule.load(shrinkwrapContent) as IPnpmShrinkwrapYaml;
if ((shrinkwrapJson as LockfileFileV9).snapshots) {
const lockfile: IPnpmShrinkwrapYaml | null = convertLockfileV9ToLockfileObject(
shrinkwrapJson as LockfileFileV9
);
/**
* In Lockfile V9,
* 1. There is no top-level dependencies field, but it is a property of the importers field.
* 2. The version may is not equal to the key in the package field. Thus, it needs to be standardized in the form of `<name>:<version>`.
*
* importers:
* .:
* dependencies:
* 'project1':
* specifier: file:./projects/project1
* version: file:projects/project1
*
* packages:
* project1@file:projects/project1:
* resolution: {directory: projects/project1, type: directory}
*/
const dependencies: ResolvedDependencies | undefined =
lockfile.importers['.' as ProjectId]?.dependencies;
if (dependencies) {
lockfile.dependencies = {};
for (const [name, versionSpecifier] of Object.entries(dependencies)) {
lockfile.dependencies[name] = PnpmShrinkwrapFile.getLockfileV9PackageId(name, versionSpecifier);
}
}
return new PnpmShrinkwrapFile(lockfile, hash, subspaceHasNoProjects);
}
return new PnpmShrinkwrapFile(shrinkwrapJson, hash, subspaceHasNoProjects);
}
public getShrinkwrapHash(experimentsConfig?: IExperimentsJson): string {
// The 'omitImportersFromPreventManualShrinkwrapChanges' experiment skips the 'importers' section
// when computing the hash, since the main concern is changes to the overall external dependency footprint
const { omitImportersFromPreventManualShrinkwrapChanges } = experimentsConfig || {};
const shrinkwrapContent: string = this._serializeInternal(
omitImportersFromPreventManualShrinkwrapChanges
);
return crypto.createHash('sha1').update(shrinkwrapContent).digest('hex');
}
/**
* Determine whether `pnpm-lock.yaml` contains insecure sha1 hashes.
* @internal
*/
private _disallowInsecureSha1(
customTipsConfiguration: CustomTipsConfiguration,
exemptPackageVersions: Record<string, string[]>,
terminal: ITerminal,
subspaceName: string
): boolean {
const exemptPackageList: Map<string, boolean> = new Map();
for (const [pkgName, versions] of Object.entries(exemptPackageVersions)) {
for (const version of versions) {
exemptPackageList.set(this._getPackageId(pkgName, version), true);
}
}
for (const [pkgName, { resolution }] of this.packages) {
if (
resolution?.integrity?.startsWith('sha1') &&
!exemptPackageList.has(this._parseDependencyPath(pkgName))
) {
terminal.writeErrorLine(
'Error: An integrity field with "sha1" was detected in the pnpm-lock.yaml file located in subspace ' +
`${subspaceName}; this conflicts with the "disallowInsecureSha1" policy from pnpm-config.json.\n`
);
customTipsConfiguration._showErrorTip(terminal, CustomTipId.TIP_RUSH_DISALLOW_INSECURE_SHA1);
return true; // Indicates an error was found
}
}
return false;
}
/** @override */
public validateShrinkwrapAfterUpdate(
rushConfiguration: RushConfiguration,
subspace: Subspace,
terminal: ITerminal
): void {
const pnpmOptions: PnpmOptionsConfiguration = subspace.getPnpmOptions() || rushConfiguration.pnpmOptions;
const { pnpmLockfilePolicies } = pnpmOptions;
let invalidPoliciesCount: number = 0;
if (pnpmLockfilePolicies?.disallowInsecureSha1?.enabled) {
const isError: boolean = this._disallowInsecureSha1(
rushConfiguration.customTipsConfiguration,
pnpmLockfilePolicies.disallowInsecureSha1.exemptPackageVersions,
terminal,
subspace.subspaceName
);
if (isError) {
invalidPoliciesCount += 1;
}
}
if (invalidPoliciesCount > 0) {
throw new AlreadyReportedError();
}
}
/** @override */
public validate(
packageManagerOptionsConfig: PackageManagerOptionsConfigurationBase,
policyOptions: IShrinkwrapFilePolicyValidatorOptions,
experimentsConfig?: IExperimentsJson
): void {
super.validate(packageManagerOptionsConfig, policyOptions);
if (!(packageManagerOptionsConfig instanceof PnpmOptionsConfiguration)) {
throw new Error('The provided package manager options are not valid for PNPM shrinkwrap files.');
}
if (!policyOptions.allowShrinkwrapUpdates) {
if (!policyOptions.repoState.isValid) {
// eslint-disable-next-line no-console
console.log(
Colorize.red(
`The ${RushConstants.repoStateFilename} file is invalid. There may be a merge conflict marker ` +
'in the file. You may need to run "rush update" to refresh its contents.'
) + '\n'
);
throw new AlreadyReportedError();
}
// Only check the hash if allowShrinkwrapUpdates is false. If true, the shrinkwrap file
// may have changed and the hash could be invalid.
if (packageManagerOptionsConfig.preventManualShrinkwrapChanges) {
if (!policyOptions.repoState.pnpmShrinkwrapHash) {
// eslint-disable-next-line no-console
console.log(
Colorize.red(
'The existing shrinkwrap file hash could not be found. You may need to run "rush update" to ' +
'populate the hash. See the "preventManualShrinkwrapChanges" setting documentation for details.'
) + '\n'
);
throw new AlreadyReportedError();
}
if (this.getShrinkwrapHash(experimentsConfig) !== policyOptions.repoState.pnpmShrinkwrapHash) {
// eslint-disable-next-line no-console
console.log(
Colorize.red(
'The shrinkwrap file hash does not match the expected hash. Please run "rush update" to ensure the ' +
'shrinkwrap file is up to date. See the "preventManualShrinkwrapChanges" setting documentation for ' +
'details.'
) + '\n'
);
throw new AlreadyReportedError();
}
}
}
}
/**
* This operation exactly mirrors the behavior of PNPM's own implementation:
* https://github.com/pnpm/pnpm/blob/73ebfc94e06d783449579cda0c30a40694d210e4/lockfile/lockfile-file/src/experiments/inlineSpecifiersLockfileConverters.ts#L162
*/
private _convertLockfileV6DepPathToV5DepPath(newDepPath: string): string {
if (!newDepPath.includes('@', 2) || newDepPath.startsWith('file:')) return newDepPath;
const index: number = newDepPath.indexOf('@', newDepPath.indexOf('/@') + 2);
if (newDepPath.includes('(') && index > pnpmKitV8.dependencyPath.indexOfPeersSuffix(newDepPath))
return newDepPath;
return `${newDepPath.substring(0, index)}/${newDepPath.substring(index + 1)}`;
}
/**
* Normalize dependency paths for PNPM shrinkwrap files.
* Example: "/eslint-utils@3.0.0(eslint@8.23.1)" --> "/eslint-utils@3.0.0"
* Example: "/@typescript-eslint/experimental-utils/5.9.1_eslint@8.6.0+typescript@4.4.4" --> "/@typescript-eslint/experimental-utils/5.9.1"
*/
private _parseDependencyPath(packagePath: string): string {
let name: string | undefined;
let version: string | undefined;
/**
* For PNPM lockfile version 9 and above, use pnpmKitV9 to parse the dependency path.
* Example: "@some/pkg@1.0.0" --> "@some/pkg@1.0.0"
* Example: "@some/pkg@1.0.0(peer@2.0.0)" --> "@some/pkg@1.0.0"
* Example: "pkg@1.0.0(patch_hash)" --> "pkg@1.0.0"
*/
if (this.shrinkwrapFileMajorVersion >= ShrinkwrapFileMajorVersion.V9) {
({ name, version } = pnpmKitV9.dependencyPath.parse(packagePath));
} else {
if (this.shrinkwrapFileMajorVersion >= ShrinkwrapFileMajorVersion.V6) {
packagePath = this._convertLockfileV6DepPathToV5DepPath(packagePath);
}
({ name, version } = pnpmKitV8.dependencyPath.parse(packagePath));
}
if (!name || !version) {
throw new InternalError(`Unable to parse package path: ${packagePath}`);
}
return this._getPackageId(name, version);
}
/** @override */
public getTempProjectNames(): ReadonlyArray<string> {
return this._getTempProjectNames(this._shrinkwrapJson.dependencies || {});
}
/**
* Gets the path to the tarball file if the package is a tarball.
* Returns undefined if the package entry doesn't exist or the package isn't a tarball.
* Example of return value: file:projects/build-tools.tgz
*/
public getTarballPath(packageName: string): string | undefined {
const dependency: IPnpmShrinkwrapDependencyYaml | undefined = this.packages.get(packageName);
return dependency?.resolution?.tarball;
}
public getTopLevelDependencyKey(dependencyName: string): IPnpmVersionSpecifier | undefined {
return this.dependencies.get(dependencyName);
}
/**
* Gets the version number from the list of top-level dependencies in the "dependencies" section
* of the shrinkwrap file. Sample return values:
* '2.1.113'
* '1.9.0-dev.27'
* 'file:projects/empty-webpart-project.tgz'
* undefined
*
* @override
*/
public getTopLevelDependencyVersion(dependencyName: string): DependencySpecifier | undefined {
let value: IPnpmVersionSpecifier | undefined = this.dependencies.get(dependencyName);
if (value) {
value = normalizePnpmVersionSpecifier(value);
// Getting the top level dependency version from a PNPM lockfile version 5.x or 6.1
// --------------------------------------------------------------------------
//
// 1) Top-level tarball dependency entries in pnpm-lock.yaml look like in 5.x:
// ```
// '@rush-temp/sp-filepicker': 'file:projects/sp-filepicker.tgz_0ec79d3b08edd81ebf49cd19ca50b3f5'
// ```
// And in version 6.1, they look like:
// ```
// '@rush-temp/sp-filepicker':
// specifier: file:./projects/generate-api-docs.tgz
// version: file:projects/generate-api-docs.tgz
// ```
// Then, it would be defined below (version 5.x):
// ```
// 'file:projects/sp-filepicker.tgz_0ec79d3b08edd81ebf49cd19ca50b3f5':
// dependencies:
// '@microsoft/load-themed-styles': 1.10.7
// ...
// resolution:
// integrity: sha512-guuoFIc**==
// tarball: 'file:projects/sp-filepicker.tgz'
// ```
// Or in version 6.1:
// ```
// file:projects/sp-filepicker.tgz:
// resolution: {integrity: sha512-guuoFIc**==, tarball: file:projects/sp-filepicker.tgz}
// name: '@rush-temp/sp-filepicker'
// version: 0.0.0
// dependencies:
// '@microsoft/load-themed-styles': 1.10.7
// ...
// dev: false
// ```
// Here, we are interested in the part 'file:projects/sp-filepicker.tgz'. Splitting by underscores is not the
// best way to get this because file names could have underscores in them. Instead, we could use the tarball
// field in the resolution section.
// 2) Top-level non-tarball dependency entries in pnpm-lock.yaml would look like in 5.x:
// ```
// '@rushstack/set-webpack-public-path-plugin': 2.1.133
// @microsoft/sp-build-node': 1.9.0-dev.27_typescript@2.9.2
// ```
// And in version 6.1, they look like:
// ```
// '@rushstack/set-webpack-public-path-plugin':
// specifier: ^2.1.133
// version: 2.1.133
// '@microsoft/sp-build-node':
// specifier: 1.9.0-dev.27
// version: 1.9.0-dev.27(typescript@2.9.2)
// ```
// Here, we could either just split by underscores and take the first part (5.x) or use the specifier field
// (6.1).
// The below code is also compatible with lockfile versions < 5.1
const dependency: IPnpmShrinkwrapDependencyYaml | undefined = this.packages.get(value);
if (dependency?.resolution?.tarball && value.startsWith(dependency.resolution.tarball)) {
return DependencySpecifier.parseWithCache(dependencyName, dependency.resolution.tarball);
}
if (this.shrinkwrapFileMajorVersion >= ShrinkwrapFileMajorVersion.V9) {
const { version, nonSemverVersion } = pnpmKitV9.dependencyPath.parse(value);
value = version ?? nonSemverVersion ?? value;
} else {
let underscoreOrParenthesisIndex: number = value.indexOf('_');
if (underscoreOrParenthesisIndex < 0) {
underscoreOrParenthesisIndex = value.indexOf('(');
}
if (underscoreOrParenthesisIndex >= 0) {
value = value.substring(0, underscoreOrParenthesisIndex);
}
}
return DependencySpecifier.parseWithCache(dependencyName, value);
}
return undefined;
}
/**
* The PNPM shrinkwrap file has top-level dependencies on the temp projects like this (version 5.x):
*
* ```
* dependencies:
* '@rush-temp/my-app': 'file:projects/my-app.tgz_25c559a5921686293a001a397be4dce0'
* packages:
* /@types/node/10.14.15:
* dev: false
* 'file:projects/my-app.tgz_25c559a5921686293a001a397be4dce0':
* dev: false
* name: '@rush-temp/my-app'
* version: 0.0.0
* ```
*
* or in version 6.1, like this:
* ```
* dependencies:
* '@rush-temp/my-app':
* specifier: file:./projects/my-app.tgz
* version: file:projects/my-app.tgz
* packages:
* /@types/node@10.14.15:
* resolution: {integrity: sha512-iAB+**==}
* dev: false
* file:projects/my-app.tgz
* resolution: {integrity: sha512-guuoFIc**==, tarball: file:projects/sp-filepicker.tgz}
* name: '@rush-temp/my-app'
* version: 0.0.0
* dependencies:
* '@microsoft/load-themed-styles': 1.10.7
* ...
* dev: false
* ```
*
* We refer to 'file:projects/my-app.tgz_25c559a5921686293a001a397be4dce0' or 'file:projects/my-app.tgz' as
* the temp project dependency key of the temp project '@rush-temp/my-app'.
*/
public getTempProjectDependencyKey(tempProjectName: string): string | undefined {
const tempProjectDependencyKey: IPnpmVersionSpecifier | undefined =
this.dependencies.get(tempProjectName);
return tempProjectDependencyKey ? normalizePnpmVersionSpecifier(tempProjectDependencyKey) : undefined;
}
public getShrinkwrapEntryFromTempProjectDependencyKey(
tempProjectDependencyKey: string
): IPnpmShrinkwrapDependencyYaml | undefined {
return this.packages.get(tempProjectDependencyKey);
}
public getShrinkwrapEntry(
name: string,
version: IPnpmVersionSpecifier
): IPnpmShrinkwrapDependencyYaml | undefined {
const packageId: string = this._getPackageId(name, version);
return this.packages.get(packageId);
}
/**
* Serializes the PNPM Shrinkwrap file
*
* @override
*/
protected serialize(): string {
return this._serializeInternal(false);
}
/**
* Gets the resolved version number of a dependency for a specific temp project.
* For PNPM, we can reuse the version that another project is using.
* Note that this function modifies the shrinkwrap data if tryReusingPackageVersionsFromShrinkwrap is set to true.
*
* @override
*/
protected tryEnsureDependencyVersion(
dependencySpecifier: DependencySpecifier,
tempProjectName: string
): DependencySpecifier | undefined {
// PNPM doesn't have the same advantage of NPM, where we can skip generate as long as the
// shrinkwrap file puts our dependency in either the top of the node_modules folder
// or underneath the package we are looking at.
// This is because the PNPM shrinkwrap file describes the exact links that need to be created
// to recreate the graph..
// Because of this, we actually need to check for a version that this package is directly
// linked to.
const packageName: string = dependencySpecifier.packageName;
const tempProjectDependencyKey: string | undefined = this.getTempProjectDependencyKey(tempProjectName);
if (!tempProjectDependencyKey) {
return undefined;
}
const packageDescription: IPnpmShrinkwrapDependencyYaml | undefined =
this._getPackageDescription(tempProjectDependencyKey);
if (
!packageDescription ||
!packageDescription.dependencies ||
!packageDescription.dependencies.hasOwnProperty(packageName)
) {
return undefined;
}
const dependencyKey: IPnpmVersionSpecifier = packageDescription.dependencies[packageName];
return this._parsePnpmDependencyKey(packageName, dependencyKey);
}
/** @override */
public findOrphanedProjects(
rushConfiguration: RushConfiguration,
subspace: Subspace
): ReadonlyArray<string> {
// The base shrinkwrap handles orphaned projects the same across all package managers,
// but this is only valid for non-workspace installs
if (!this.isWorkspaceCompatible) {
return super.findOrphanedProjects(rushConfiguration, subspace);
}
const subspaceTempFolder: string = subspace.getSubspaceTempFolderPath();
const lookup: IReadonlyLookupByPath<RushConfigurationProject> =
rushConfiguration.getProjectLookupForRoot(subspaceTempFolder);
const orphanedProjectPaths: string[] = [];
for (const importerKey of this.getImporterKeys()) {
if (!lookup.findChildPath(importerKey)) {
// PNPM importer keys are relative paths from the workspace root, which is the common temp folder
orphanedProjectPaths.push(path.resolve(subspaceTempFolder, importerKey));
}
}
return orphanedProjectPaths;
}
/** @override */
public getProjectShrinkwrap(project: RushConfigurationProject): PnpmProjectShrinkwrapFile {
return new PnpmProjectShrinkwrapFile(this, project);
}
public *getImporterKeys(): Iterable<string> {
// Filter out the root importer used for the generated package.json in the root
// of the install, since we do not use this.
for (const key of this.importers.keys()) {
if (key !== '.') {
yield key;
}
}
}
public getImporterKeyByPath(workspaceRoot: string, projectFolder: string): string {
return Path.convertToSlashes(path.relative(workspaceRoot, projectFolder));
}
public getImporter(importerKey: string): IPnpmShrinkwrapImporterYaml | undefined {
return this.importers.get(importerKey);
}
public getIntegrityForImporter(importerKey: string): Map<string, string> | undefined {
// This logic formerly lived in PnpmProjectShrinkwrapFile. Moving it here allows caching of the external
// dependency integrity relationships across projects
let integrityMap: Map<string, string> | undefined = this._integrities.get(importerKey);
if (!integrityMap) {
const importer: IPnpmShrinkwrapImporterYaml | undefined = this.getImporter(importerKey);
if (importer) {
const resolvedIntegrityMap: Map<string, string> = new Map();
integrityMap = resolvedIntegrityMap;
this._integrities.set(importerKey, resolvedIntegrityMap);
const sha256Digest: string = crypto
.createHash('sha256')
.update(JSON.stringify(importer))
.digest('base64');
const selfIntegrity: string = `${importerKey}:${sha256Digest}:`;
resolvedIntegrityMap.set(importerKey, selfIntegrity);
const { dependencies, devDependencies, optionalDependencies } = importer;
const processCollection = (
collection: Record<string, IPnpmVersionSpecifier>,
optional: boolean
): void => {
const externalDeps: Record<string, IPnpmVersionSpecifier> = {};
for (const [name, versionSpecifier] of Object.entries(collection)) {
const version: string = normalizePnpmVersionSpecifier(versionSpecifier);
if (version.startsWith('link:')) {
// This is a workspace-local dependency; resolve it to an importer key and recurse.
// The link: path is relative to the project folder (which is the importer key itself),
// so we join the importer key with the link path (not dirname).
// Lockfile paths are always POSIX, so we use path.posix helpers.
const linkPath: string = version.slice('link:'.length);
const targetKey: string = path.posix.normalize(path.posix.join(importerKey, linkPath));
const linkedIntegrities: Map<string, string> | undefined =
this.getIntegrityForImporter(targetKey);
if (linkedIntegrities) {
for (const [dep, integrity] of linkedIntegrities) {
resolvedIntegrityMap.set(dep, integrity);
}
}
} else {
externalDeps[name] = versionSpecifier;
}
}
this._addIntegrities(resolvedIntegrityMap, externalDeps, optional);
};
if (dependencies) {
processCollection(dependencies, false);
}
if (devDependencies) {
processCollection(devDependencies, false);
}
if (optionalDependencies) {
processCollection(optionalDependencies, true);
}
}
}
return integrityMap;
}
/** @override */
public async isWorkspaceProjectModifiedAsync(
project: RushConfigurationProject,
subspace: Subspace,
variant: string | undefined
): Promise<boolean> {
const importerKey: string = this.getImporterKeyByPath(
subspace.getSubspaceTempFolderPath(),
project.projectFolder
);
const importer: IPnpmShrinkwrapImporterYaml | undefined = this.getImporter(importerKey);
if (!importer) {
return true;
}
// First, let's transform the package.json using the pnpmfile
const packageJson: IPackageJson = project.packageJsonEditor.saveToObject();
// Initialize the pnpmfile if it doesn't exist
if (!this._pnpmfileConfiguration) {
this._pnpmfileConfiguration = await PnpmfileConfiguration.initializeAsync(
project.rushConfiguration,
subspace,
variant
);
}
let transformedPackageJson: IPackageJson = packageJson;