-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathProject.ts
2712 lines (2126 loc) Β· 106 KB
/
Project.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
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
import {npath} from '@yarnpkg/fslib';
import {PortablePath, ppath, xfs, normalizeLineEndings, Filename} from '@yarnpkg/fslib';
import {parseSyml, stringifySyml} from '@yarnpkg/parsers';
import {UsageError} from 'clipanion';
import {createHash} from 'crypto';
import {structuredPatch} from 'diff';
import pick from 'lodash/pick';
import pLimit from 'p-limit';
import semver from 'semver';
import internal from 'stream';
import {promisify} from 'util';
import v8 from 'v8';
import zlib from 'zlib';
import {Cache, CacheOptions} from './Cache';
import {Configuration} from './Configuration';
import {Fetcher, FetchOptions} from './Fetcher';
import {Installer, BuildDirective, BuildDirectiveType, InstallStatus} from './Installer';
import {LegacyMigrationResolver} from './LegacyMigrationResolver';
import {Linker, LinkOptions} from './Linker';
import {LockfileResolver} from './LockfileResolver';
import {DependencyMeta, Manifest} from './Manifest';
import {MessageName} from './MessageName';
import {MultiResolver} from './MultiResolver';
import {Report, ReportError} from './Report';
import {ResolveOptions, Resolver} from './Resolver';
import {RunInstallPleaseResolver} from './RunInstallPleaseResolver';
import {SUPPORTS_GROUPS, StreamReport} from './StreamReport';
import {ThrowReport} from './ThrowReport';
import {WorkspaceResolver} from './WorkspaceResolver';
import {Workspace} from './Workspace';
import {isFolderInside} from './folderUtils';
import * as formatUtils from './formatUtils';
import * as hashUtils from './hashUtils';
import * as miscUtils from './miscUtils';
import * as nodeUtils from './nodeUtils';
import * as scriptUtils from './scriptUtils';
import * as semverUtils from './semverUtils';
import * as structUtils from './structUtils';
import {LinkType} from './types';
import {Descriptor, Ident, Locator, Package} from './types';
import {IdentHash, DescriptorHash, LocatorHash, PackageExtensionStatus} from './types';
// When upgraded, the lockfile entries have to be resolved again (but the specific
// versions are still pinned, no worry). Bump it when you change the fields within
// the Package type; no more no less.
export const LOCKFILE_VERSION = miscUtils.parseInt(
process.env.YARN_LOCKFILE_VERSION_OVERRIDE ??
8,
);
// Same thing but must be bumped when the members of the Project class changes (we
// don't recommend our users to check-in this file, so it's fine to bump it even
// between patch or minor releases).
const INSTALL_STATE_VERSION = 3;
const MULTIPLE_KEYS_REGEXP = / *, */g;
const TRAILING_SLASH_REGEXP = /\/$/;
const FETCHER_CONCURRENCY = 32;
const gzip = promisify(zlib.gzip);
const gunzip = promisify(zlib.gunzip);
export enum InstallMode {
/**
* Doesn't run the link step, and only fetches what's necessary to compute
* an updated lockfile.
*/
UpdateLockfile = `update-lockfile`,
/**
* Don't run the build scripts.
*/
SkipBuild = `skip-build`,
}
export type InstallOptions = {
/**
* Instance of the cache that the project will use when packages have to be
* fetched. Some fetches may occur even during the resolution, for example
* when resolving git packages.
*/
cache: Cache;
/**
* An optional override for the default fetching pipeline. This is for
* overrides only - if you need to _add_ resolvers, prefer adding them
* through regular plugins instead.
*/
fetcher?: Fetcher;
/**
* An optional override for the default resolution pipeline. This is for
* overrides only - if you need to _add_ resolvers, prefer adding them
* through regular plugins instead.
*/
resolver?: Resolver;
/**
* Provide a report instance that'll be use to store the information emitted
* during the install process.
*/
report: Report;
/**
* If true, Yarn will check that the lockfile won't change after the
* resolution step. Additionally, after the link step, Yarn will retrieve
* the list of files in `immutablePatterns` and check that they didn't get
* modified either.
*/
immutable?: boolean;
/**
* If true, Yarn will exclusively use the lockfile metadata. Setting this
* flag will cause it to ignore any change in the manifests, and to abort
* if any dependency isn't present in the lockfile.
*/
lockfileOnly?: boolean;
/**
* If true, Yarn will check that the pre-existing resolutions found in the
* lockfile are coherent with the ranges that depend on them.
*/
checkResolutions?: boolean;
/**
* Changes which artifacts are generated during the install. Check the
* enumeration documentation for details.
*/
mode?: InstallMode;
/**
* If true (the default), Yarn will update the workspace manifests once the
* install has completed.
*/
persistProject?: boolean;
};
const INSTALL_STATE_FIELDS = {
restoreLinkersCustomData: [
`linkersCustomData`,
] as const,
restoreResolutions: [
`accessibleLocators`,
`conditionalLocators`,
`disabledLocators`,
`optionalBuilds`,
`storedDescriptors`,
`storedResolutions`,
`storedPackages`,
`lockFileChecksum`,
] as const,
restoreBuildState: [
`skippedBuilds`,
`storedBuildState`,
] as const,
};
type RestoreInstallStateOpts = {
[key in keyof typeof INSTALL_STATE_FIELDS]?: boolean;
};
// Just a type that's the union of all the fields declared in `INSTALL_STATE_FIELDS`
type InstallState = Pick<Project, typeof INSTALL_STATE_FIELDS[keyof typeof INSTALL_STATE_FIELDS][number]>;
export type PeerRequirement = {
subject: LocatorHash;
requested: Ident;
rootRequester: LocatorHash;
allRequesters: Array<LocatorHash>;
};
export enum PeerWarningType {
NotProvided,
NotCompatible,
NotCompatibleAggregate,
}
export type PeerWarning = {
type: PeerWarningType.NotProvided;
subject: Locator;
requested: Ident;
requester: Ident;
hash: string;
} | {
type: PeerWarningType.NotCompatible;
subject: Locator;
requested: Ident;
requester: Ident;
version: string;
hash: string;
requirementCount: number;
} | {
type: PeerWarningType.NotCompatibleAggregate;
subject: Locator;
requested: Ident;
dependents: Map<LocatorHash, Locator>;
requesters: Map<LocatorHash, Locator>;
links: Map<LocatorHash, Locator>;
version: string;
hash: string;
};
const makeLockfileChecksum = (normalizedContent: string) =>
hashUtils.makeHash(`${INSTALL_STATE_VERSION}`, normalizedContent);
export class Project {
public readonly configuration: Configuration;
public readonly cwd: PortablePath;
/**
* Is meant to be populated by the consumer. Should the descriptor referenced
* by the key be requested, the descriptor referenced in the value will be
* resolved instead. The resolved data will then be used as final resolution
* for the initial descriptor.
*
* Note that the lockfile will contain the second descriptor but not the
* first one (meaning that if you remove the alias during a subsequent
* install, it'll be lost and the real package will be resolved / installed).
*/
public resolutionAliases: Map<DescriptorHash, DescriptorHash> = new Map();
public workspaces: Array<Workspace> = [];
public workspacesByCwd: Map<PortablePath, Workspace> = new Map();
public workspacesByIdent: Map<IdentHash, Workspace> = new Map();
public storedResolutions: Map<DescriptorHash, LocatorHash> = new Map();
public storedDescriptors: Map<DescriptorHash, Descriptor> = new Map();
public storedPackages: Map<LocatorHash, Package> = new Map();
public storedChecksums: Map<LocatorHash, string> = new Map();
public storedBuildState: Map<LocatorHash, string> = new Map();
public accessibleLocators: Set<LocatorHash> = new Set();
public conditionalLocators: Set<LocatorHash> = new Set();
public disabledLocators: Set<LocatorHash> = new Set();
public originalPackages: Map<LocatorHash, Package> = new Map();
public optionalBuilds: Set<LocatorHash> = new Set();
public skippedBuilds: Set<LocatorHash> = new Set();
/**
* If true, the data contained within `originalPackages` are from a different
* lockfile version and need to be refreshed.
*/
public lockfileLastVersion: number | null = null;
public lockfileNeedsRefresh: boolean = false;
/**
* Populated by the `resolveEverything` method.
* *Not* stored inside the install state.
*
* The map keys are 6 hexadecimal characters except the first one, always `p`.
*/
public peerRequirements: Map<string, PeerRequirement> = new Map();
public peerWarnings: Array<PeerWarning> = [];
/**
* Contains whatever data the linkers (cf `Linker.ts`) want to persist
* from an install to another.
*/
public linkersCustomData: Map<string, unknown> = new Map();
/**
* Those checksums are used to detect whether the relevant files actually
* changed since we last read them (to skip part of their generation).
*/
public lockFileChecksum: string | null = null;
public installStateChecksum: string | null = null;
static async find(configuration: Configuration, startingCwd: PortablePath): Promise<{project: Project, workspace: Workspace | null, locator: Locator}> {
if (!configuration.projectCwd)
throw new UsageError(`No project found in ${startingCwd}`);
let packageCwd = configuration.projectCwd;
let nextCwd = startingCwd;
let currentCwd = null;
while (currentCwd !== configuration.projectCwd) {
currentCwd = nextCwd;
if (xfs.existsSync(ppath.join(currentCwd, Filename.manifest))) {
packageCwd = currentCwd;
break;
}
nextCwd = ppath.dirname(currentCwd);
}
const project = new Project(configuration.projectCwd, {configuration});
Configuration.telemetry?.reportProject(project.cwd);
await project.setupResolutions();
await project.setupWorkspaces();
Configuration.telemetry?.reportWorkspaceCount(project.workspaces.length);
Configuration.telemetry?.reportDependencyCount(project.workspaces.reduce((sum, workspace) => sum + workspace.manifest.dependencies.size + workspace.manifest.devDependencies.size, 0));
// If we're in a workspace, no need to go any further to find which package we're in
const workspace = project.tryWorkspaceByCwd(packageCwd);
if (workspace)
return {project, workspace, locator: workspace.anchoredLocator};
// Otherwise, we need to ask the project (which will in turn ask the linkers for help)
// Note: the trailing slash is caused by a quirk in the PnP implementation that requires folders to end with a trailing slash to disambiguate them from regular files
const locator = await project.findLocatorForLocation(`${packageCwd}/` as PortablePath, {strict: true});
if (locator)
return {project, locator, workspace: null};
const projectCwdLog = formatUtils.pretty(configuration, project.cwd, formatUtils.Type.PATH);
const packageCwdLog = formatUtils.pretty(configuration, ppath.relative(project.cwd, packageCwd), formatUtils.Type.PATH);
const unintendedProjectLog = `- If ${projectCwdLog} isn't intended to be a project, remove any yarn.lock and/or package.json file there.`;
const missingWorkspaceLog = `- If ${projectCwdLog} is intended to be a project, it might be that you forgot to list ${packageCwdLog} in its workspace configuration.`;
const decorrelatedProjectLog = `- Finally, if ${projectCwdLog} is fine and you intend ${packageCwdLog} to be treated as a completely separate project (not even a workspace), create an empty yarn.lock file in it.`;
throw new UsageError(`The nearest package directory (${formatUtils.pretty(configuration, packageCwd, formatUtils.Type.PATH)}) doesn't seem to be part of the project declared in ${formatUtils.pretty(configuration, project.cwd, formatUtils.Type.PATH)}.\n\n${[
unintendedProjectLog,
missingWorkspaceLog,
decorrelatedProjectLog,
].join(`\n`)}`);
}
constructor(projectCwd: PortablePath, {configuration}: {configuration: Configuration}) {
this.configuration = configuration;
this.cwd = projectCwd;
}
private async setupResolutions() {
this.storedResolutions = new Map();
this.storedDescriptors = new Map();
this.storedPackages = new Map();
this.lockFileChecksum = null;
const lockfilePath = ppath.join(this.cwd, Filename.lockfile);
const defaultLanguageName = this.configuration.get(`defaultLanguageName`);
if (xfs.existsSync(lockfilePath)) {
const content = await xfs.readFilePromise(lockfilePath, `utf8`);
// We store the salted checksum of the lockfile in order to invalidate the install state when needed
this.lockFileChecksum = makeLockfileChecksum(content);
const parsed: any = parseSyml(content);
// Protects against v1 lockfiles
if (parsed.__metadata) {
const lockfileVersion = parsed.__metadata.version;
const cacheKey = parsed.__metadata.cacheKey;
this.lockfileLastVersion = lockfileVersion;
this.lockfileNeedsRefresh = lockfileVersion < LOCKFILE_VERSION;
for (const key of Object.keys(parsed)) {
if (key === `__metadata`)
continue;
const data = parsed[key];
if (typeof data.resolution === `undefined`)
throw new Error(`Assertion failed: Expected the lockfile entry to have a resolution field (${key})`);
const locator = structUtils.parseLocator(data.resolution, true);
const manifest = new Manifest();
manifest.load(data, {yamlCompatibilityMode: true});
const version = manifest.version;
const languageName = manifest.languageName || defaultLanguageName;
const linkType = data.linkType.toUpperCase() as LinkType;
const conditions = data.conditions ?? null;
const dependencies = manifest.dependencies;
const peerDependencies = manifest.peerDependencies;
const dependenciesMeta = manifest.dependenciesMeta;
const peerDependenciesMeta = manifest.peerDependenciesMeta;
const bin = manifest.bin;
if (data.checksum != null) {
const checksum = typeof cacheKey !== `undefined` && !data.checksum.includes(`/`)
? `${cacheKey}/${data.checksum}`
: data.checksum;
this.storedChecksums.set(locator.locatorHash, checksum);
}
const pkg: Package = {...locator, version, languageName, linkType, conditions, dependencies, peerDependencies, dependenciesMeta, peerDependenciesMeta, bin};
this.originalPackages.set(pkg.locatorHash, pkg);
for (const entry of key.split(MULTIPLE_KEYS_REGEXP)) {
let descriptor = structUtils.parseDescriptor(entry);
// Yarn pre-v4 used to generate descriptors that were sometimes
// missing the `npm:` protocol
if (lockfileVersion <= 6) {
descriptor = this.configuration.normalizeDependency(descriptor);
descriptor = structUtils.makeDescriptor(descriptor, descriptor.range.replace(/^patch:[^@]+@(?!npm(:|%3A))/, `$1npm%3A`));
}
this.storedDescriptors.set(descriptor.descriptorHash, descriptor);
this.storedResolutions.set(descriptor.descriptorHash, locator.locatorHash);
}
}
} else if (content.includes(`yarn lockfile v1`)) {
this.lockfileLastVersion = -1;
}
}
}
private async setupWorkspaces() {
this.workspaces = [];
this.workspacesByCwd = new Map();
this.workspacesByIdent = new Map();
const pathsChecked = new Set<PortablePath>();
const limitSetup = pLimit(4);
const loadWorkspaceReducer = async (previousTask: Promise<void>, workspaceCwd: PortablePath): Promise<void> => {
if (pathsChecked.has(workspaceCwd))
return previousTask;
pathsChecked.add(workspaceCwd);
const workspace = new Workspace(workspaceCwd, {project: this});
await limitSetup(() => workspace.setup());
const nextTask = previousTask.then(() => {
this.addWorkspace(workspace);
});
return Array.from(workspace.workspacesCwds).reduce(loadWorkspaceReducer, nextTask);
};
await loadWorkspaceReducer(Promise.resolve(), this.cwd);
}
private addWorkspace(workspace: Workspace) {
const dup = this.workspacesByIdent.get(workspace.anchoredLocator.identHash);
if (typeof dup !== `undefined`)
throw new Error(`Duplicate workspace name ${structUtils.prettyIdent(this.configuration, workspace.anchoredLocator)}: ${npath.fromPortablePath(workspace.cwd)} conflicts with ${npath.fromPortablePath(dup.cwd)}`);
this.workspaces.push(workspace);
this.workspacesByCwd.set(workspace.cwd, workspace);
this.workspacesByIdent.set(workspace.anchoredLocator.identHash, workspace);
}
get topLevelWorkspace() {
return this.getWorkspaceByCwd(this.cwd);
}
tryWorkspaceByCwd(workspaceCwd: PortablePath) {
if (!ppath.isAbsolute(workspaceCwd))
workspaceCwd = ppath.resolve(this.cwd, workspaceCwd);
workspaceCwd = ppath.normalize(workspaceCwd)
.replace(/\/+$/, ``) as PortablePath;
const workspace = this.workspacesByCwd.get(workspaceCwd);
if (!workspace)
return null;
return workspace;
}
getWorkspaceByCwd(workspaceCwd: PortablePath) {
const workspace = this.tryWorkspaceByCwd(workspaceCwd);
if (!workspace)
throw new Error(`Workspace not found (${workspaceCwd})`);
return workspace;
}
tryWorkspaceByFilePath(filePath: PortablePath) {
let bestWorkspace = null;
for (const workspace of this.workspaces) {
const rel = ppath.relative(workspace.cwd, filePath);
if (rel.startsWith(`../`))
continue;
if (bestWorkspace && bestWorkspace.cwd.length >= workspace.cwd.length)
continue;
bestWorkspace = workspace;
}
if (!bestWorkspace)
return null;
return bestWorkspace;
}
getWorkspaceByFilePath(filePath: PortablePath) {
const workspace = this.tryWorkspaceByFilePath(filePath);
if (!workspace)
throw new Error(`Workspace not found (${filePath})`);
return workspace;
}
tryWorkspaceByIdent(ident: Ident) {
const workspace = this.workspacesByIdent.get(ident.identHash);
if (typeof workspace === `undefined`)
return null;
return workspace;
}
getWorkspaceByIdent(ident: Ident) {
const workspace = this.tryWorkspaceByIdent(ident);
if (!workspace)
throw new Error(`Workspace not found (${structUtils.prettyIdent(this.configuration, ident)})`);
return workspace;
}
tryWorkspaceByDescriptor(descriptor: Descriptor) {
if (descriptor.range.startsWith(WorkspaceResolver.protocol)) {
const specifier = descriptor.range.slice(WorkspaceResolver.protocol.length) as PortablePath;
if (specifier !== `^` && specifier !== `~` && specifier !== `*` && !semverUtils.validRange(specifier)) {
return this.tryWorkspaceByCwd(specifier);
}
}
const workspace = this.tryWorkspaceByIdent(descriptor);
if (workspace === null)
return null;
if (structUtils.isVirtualDescriptor(descriptor))
descriptor = structUtils.devirtualizeDescriptor(descriptor);
if (!workspace.accepts(descriptor.range))
return null;
return workspace;
}
getWorkspaceByDescriptor(descriptor: Descriptor) {
const workspace = this.tryWorkspaceByDescriptor(descriptor);
if (workspace === null)
throw new Error(`Workspace not found (${structUtils.prettyDescriptor(this.configuration, descriptor)})`);
return workspace;
}
tryWorkspaceByLocator(locator: Locator) {
const workspace = this.tryWorkspaceByIdent(locator);
if (workspace === null)
return null;
if (structUtils.isVirtualLocator(locator))
locator = structUtils.devirtualizeLocator(locator);
if (workspace.anchoredLocator.locatorHash !== locator.locatorHash)
return null;
return workspace;
}
getWorkspaceByLocator(locator: Locator) {
const workspace = this.tryWorkspaceByLocator(locator);
if (!workspace)
throw new Error(`Workspace not found (${structUtils.prettyLocator(this.configuration, locator)})`);
return workspace;
}
private deleteDescriptor(descriptorHash: DescriptorHash) {
this.storedResolutions.delete(descriptorHash);
this.storedDescriptors.delete(descriptorHash);
}
private deleteLocator(locatorHash: LocatorHash) {
this.originalPackages.delete(locatorHash);
this.storedPackages.delete(locatorHash);
this.accessibleLocators.delete(locatorHash);
}
forgetResolution(descriptor: Descriptor): void;
forgetResolution(locator: Locator): void;
forgetResolution(dataStructure: Descriptor | Locator): void {
if (`descriptorHash` in dataStructure) {
const locatorHash = this.storedResolutions.get(dataStructure.descriptorHash);
this.deleteDescriptor(dataStructure.descriptorHash);
// We delete unused locators
const remainingResolutions = new Set(this.storedResolutions.values());
if (typeof locatorHash !== `undefined` && !remainingResolutions.has(locatorHash)) {
this.deleteLocator(locatorHash);
}
}
if (`locatorHash` in dataStructure) {
this.deleteLocator(dataStructure.locatorHash);
// We delete all of the descriptors that have been resolved to the locator
for (const [descriptorHash, locatorHash] of this.storedResolutions) {
if (locatorHash === dataStructure.locatorHash) {
this.deleteDescriptor(descriptorHash);
}
}
}
}
forgetTransientResolutions() {
const resolver = this.configuration.makeResolver();
const reverseLookup = new Map<LocatorHash, Set<DescriptorHash>>();
for (const [descriptorHash, locatorHash] of this.storedResolutions.entries()) {
let descriptorHashes = reverseLookup.get(locatorHash);
if (!descriptorHashes)
reverseLookup.set(locatorHash, descriptorHashes = new Set());
descriptorHashes.add(descriptorHash);
}
for (const pkg of this.originalPackages.values()) {
let shouldPersistResolution: boolean;
try {
shouldPersistResolution = resolver.shouldPersistResolution(pkg, {project: this, resolver});
} catch {
shouldPersistResolution = false;
}
if (!shouldPersistResolution) {
this.deleteLocator(pkg.locatorHash);
const descriptors = reverseLookup.get(pkg.locatorHash);
if (descriptors) {
reverseLookup.delete(pkg.locatorHash);
for (const descriptorHash of descriptors) {
this.deleteDescriptor(descriptorHash);
}
}
}
}
}
forgetVirtualResolutions() {
for (const pkg of this.storedPackages.values()) {
for (const [dependencyHash, dependency] of pkg.dependencies) {
if (structUtils.isVirtualDescriptor(dependency)) {
pkg.dependencies.set(dependencyHash, structUtils.devirtualizeDescriptor(dependency));
}
}
}
}
getDependencyMeta(ident: Ident, version: string | null): DependencyMeta {
const dependencyMeta = {};
const dependenciesMeta = this.topLevelWorkspace.manifest.dependenciesMeta;
const dependencyMetaSet = dependenciesMeta.get(structUtils.stringifyIdent(ident));
if (!dependencyMetaSet)
return dependencyMeta;
const defaultMeta = dependencyMetaSet.get(null);
if (defaultMeta)
Object.assign(dependencyMeta, defaultMeta);
if (version === null || !semver.valid(version))
return dependencyMeta;
for (const [range, meta] of dependencyMetaSet)
if (range !== null && range === version)
Object.assign(dependencyMeta, meta);
return dependencyMeta;
}
async findLocatorForLocation(cwd: PortablePath, {strict = false}: {strict?: boolean} = {}) {
const report = new ThrowReport();
const linkers = this.configuration.getLinkers();
const linkerOptions = {project: this, report};
for (const linker of linkers) {
const locator = await linker.findPackageLocator(cwd, linkerOptions);
if (locator) {
// If strict mode, the specified cwd must be a package,
// not merely contained in a package.
if (strict) {
const location = await linker.findPackageLocation(locator, linkerOptions);
if (location.replace(TRAILING_SLASH_REGEXP, ``) !== cwd.replace(TRAILING_SLASH_REGEXP, ``)) {
continue;
}
}
return locator;
}
}
return null;
}
async loadUserConfig() {
const configPath = ppath.join(this.cwd, `yarn.config.cjs`);
if (!await xfs.existsPromise(configPath))
return null;
return miscUtils.dynamicRequire(configPath);
}
async preparePackage(originalPkg: Package, {resolver, resolveOptions}: {resolver: Resolver, resolveOptions: ResolveOptions}) {
const pkg = this.configuration.normalizePackage(originalPkg);
for (const [identHash, descriptor] of pkg.dependencies) {
const dependency = await this.configuration.reduceHook(hooks => {
return hooks.reduceDependency;
}, descriptor, this, pkg, descriptor, {
resolver,
resolveOptions,
});
if (!structUtils.areIdentsEqual(descriptor, dependency))
throw new Error(`Assertion failed: The descriptor ident cannot be changed through aliases`);
const bound = resolver.bindDescriptor(dependency, pkg, resolveOptions);
pkg.dependencies.set(identHash, bound);
}
return pkg;
}
async resolveEverything(opts: Pick<InstallOptions, `report` | `resolver` | `checkResolutions` | `mode`> & ({report: Report, lockfileOnly: true} | {lockfileOnly?: boolean, cache: Cache})) {
if (!this.workspacesByCwd || !this.workspacesByIdent)
throw new Error(`Workspaces must have been setup before calling this function`);
// Reverts the changes that have been applied to the tree because of any previous virtual resolution pass
this.forgetVirtualResolutions();
// Keep a copy of the original packages so that we can figure out what was added / removed later
const initialPackages = new Map(this.originalPackages);
const addedPackages: Array<Locator> = [];
// Ensures that we notice it when dependencies are added / removed from all sources coming from the filesystem
if (!opts.lockfileOnly)
this.forgetTransientResolutions();
// Note that the resolution process is "offline" until everything has been
// successfully resolved; all the processing is expected to have zero side
// effects until we're ready to set all the variables at once (the one
// exception being when a resolver needs to fetch a package, in which case
// we might need to populate the cache).
//
// This makes it possible to use the same Project instance for multiple
// purposes at the same time (since `resolveEverything` is async, it might
// happen that we want to do something while waiting for it to end; if we
// were to mutate the project then it would end up in a partial state that
// could lead to hard-to-debug issues).
const realResolver = opts.resolver || this.configuration.makeResolver();
const legacyMigrationResolver = new LegacyMigrationResolver(realResolver);
await legacyMigrationResolver.setup(this, {report: opts.report});
const resolverChain = opts.lockfileOnly
? [new RunInstallPleaseResolver(realResolver)]
: [legacyMigrationResolver, realResolver];
const resolver: Resolver = new MultiResolver([
new LockfileResolver(realResolver),
...resolverChain,
]);
const noLockfileResolver: Resolver = new MultiResolver([
...resolverChain,
]);
const fetcher = this.configuration.makeFetcher();
const resolveOptions: ResolveOptions = opts.lockfileOnly
? {project: this, report: opts.report, resolver}
: {project: this, report: opts.report, resolver, fetchOptions: {project: this, cache: opts.cache, checksums: this.storedChecksums, report: opts.report, fetcher, cacheOptions: {mirrorWriteOnly: true}}};
const allDescriptors = new Map<DescriptorHash, Descriptor>();
const allPackages = new Map<LocatorHash, Package>();
const allResolutions = new Map<DescriptorHash, LocatorHash>();
const originalPackages = new Map<LocatorHash, Package>();
const packageResolutionPromises = new Map<LocatorHash, Promise<Package>>();
const descriptorResolutionPromises = new Map<DescriptorHash, Promise<Package>>();
const dependencyResolutionLocator = this.topLevelWorkspace.anchoredLocator;
const resolutionDependencies = new Set<LocatorHash>();
const resolutionQueue: Array<Promise<unknown>> = [];
// Doing these calls early is important: it seems calling it after we've started the resolution incurs very high
// performance penalty on WSL, with the Gatsby benchmark jumping from ~28s to ~130s. It's possible this is due to
// the number of async tasks being listed in the report, although it's strange this doesn't occur on other systems.
const currentArchitecture = nodeUtils.getArchitectureSet();
const supportedArchitectures = this.configuration.getSupportedArchitectures();
await opts.report.startProgressPromise(Report.progressViaTitle(), async progress => {
const startPackageResolution = async (locator: Locator) => {
const originalPkg = await miscUtils.prettifyAsyncErrors(async () => {
return await resolver.resolve(locator, resolveOptions);
}, message => {
return `${structUtils.prettyLocator(this.configuration, locator)}: ${message}`;
});
if (!structUtils.areLocatorsEqual(locator, originalPkg))
throw new Error(`Assertion failed: The locator cannot be changed by the resolver (went from ${structUtils.prettyLocator(this.configuration, locator)} to ${structUtils.prettyLocator(this.configuration, originalPkg)})`);
originalPackages.set(originalPkg.locatorHash, originalPkg);
// What didn't exist before is an added package
const existedBefore = initialPackages.delete(originalPkg.locatorHash);
if (!existedBefore && !this.tryWorkspaceByLocator(originalPkg))
addedPackages.push(originalPkg);
const pkg = await this.preparePackage(originalPkg, {resolver, resolveOptions});
const dependencyResolutions = miscUtils.allSettledSafe([...pkg.dependencies.values()].map(descriptor => {
return scheduleDescriptorResolution(descriptor);
}));
resolutionQueue.push(dependencyResolutions);
// While the promise is now part of `resolutionQueue`, nothing is
// technically `awaiting` it just yet (and nothing will until the
// current resolution pass fully ends, and the next one starts).
//
// To avoid V8 printing an UnhandledPromiseRejectionWarning, we
// bind a empty `catch`.
//
dependencyResolutions.catch(() => {});
allPackages.set(pkg.locatorHash, pkg);
return pkg;
};
const schedulePackageResolution = async (locator: Locator) => {
const promise = packageResolutionPromises.get(locator.locatorHash);
if (typeof promise !== `undefined`)
return promise;
const newPromise = Promise.resolve().then(() => startPackageResolution(locator));
packageResolutionPromises.set(locator.locatorHash, newPromise);
return newPromise;
};
const startDescriptorAliasing = async (descriptor: Descriptor, alias: Descriptor): Promise<Package> => {
const resolution = await scheduleDescriptorResolution(alias);
allDescriptors.set(descriptor.descriptorHash, descriptor);
allResolutions.set(descriptor.descriptorHash, resolution.locatorHash);
return resolution;
};
const startDescriptorResolution = async (descriptor: Descriptor): Promise<Package> => {
progress.setTitle(structUtils.prettyDescriptor(this.configuration, descriptor));
const alias = this.resolutionAliases.get(descriptor.descriptorHash);
if (typeof alias !== `undefined`)
return startDescriptorAliasing(descriptor, this.storedDescriptors.get(alias)!);
const resolutionDependenciesList = resolver.getResolutionDependencies(descriptor, resolveOptions);
const resolvedDependencies = Object.fromEntries(
await miscUtils.allSettledSafe(
Object.entries(resolutionDependenciesList).map(async ([dependencyName, dependency]) => {
const bound = resolver.bindDescriptor(dependency, dependencyResolutionLocator, resolveOptions);
const resolvedPackage = await scheduleDescriptorResolution(bound);
resolutionDependencies.add(resolvedPackage.locatorHash);
return [dependencyName, resolvedPackage] as const;
}),
),
);
const candidateResolutions = await miscUtils.prettifyAsyncErrors(async () => {
return await resolver.getCandidates(descriptor, resolvedDependencies, resolveOptions);
}, message => {
return `${structUtils.prettyDescriptor(this.configuration, descriptor)}: ${message}`;
});
const finalResolution = candidateResolutions[0];
if (typeof finalResolution === `undefined`)
throw new ReportError(MessageName.RESOLUTION_FAILED, `${structUtils.prettyDescriptor(this.configuration, descriptor)}: No candidates found`);
if (opts.checkResolutions) {
const {locators} = await noLockfileResolver.getSatisfying(descriptor, resolvedDependencies, [finalResolution], {...resolveOptions, resolver: noLockfileResolver});
if (!locators.find(locator => locator.locatorHash === finalResolution.locatorHash)) {
throw new ReportError(MessageName.RESOLUTION_MISMATCH, `Invalid resolution ${structUtils.prettyResolution(this.configuration, descriptor, finalResolution)}`);
}
}
allDescriptors.set(descriptor.descriptorHash, descriptor);
allResolutions.set(descriptor.descriptorHash, finalResolution.locatorHash);
return schedulePackageResolution(finalResolution);
};
const scheduleDescriptorResolution = (descriptor: Descriptor) => {
const promise = descriptorResolutionPromises.get(descriptor.descriptorHash);
if (typeof promise !== `undefined`)
return promise;
allDescriptors.set(descriptor.descriptorHash, descriptor);
const newPromise = Promise.resolve().then(() => startDescriptorResolution(descriptor));
descriptorResolutionPromises.set(descriptor.descriptorHash, newPromise);
return newPromise;
};
for (const workspace of this.workspaces) {
const workspaceDescriptor = workspace.anchoredDescriptor;
resolutionQueue.push(scheduleDescriptorResolution(workspaceDescriptor));
}
while (resolutionQueue.length > 0) {
const copy = [...resolutionQueue];
resolutionQueue.length = 0;
await miscUtils.allSettledSafe(copy);
}
});
// What remains is a removed package
const removedPackages: Array<Locator> = miscUtils.mapAndFilter(initialPackages.values(), pkg => {
if (this.tryWorkspaceByLocator(pkg))
return miscUtils.mapAndFilter.skip;
return pkg;
});
if (addedPackages.length > 0 || removedPackages.length > 0) {
const topLevelResolutions = new Set(this.workspaces.flatMap(workspace => {
const workspacePkg = allPackages.get(workspace.anchoredLocator.locatorHash);
if (!workspacePkg)
throw new Error(`Assertion failed: The workspace should have been resolved`);
return Array.from(workspacePkg.dependencies.values(), descriptor => {
const resolution = allResolutions.get(descriptor.descriptorHash);
if (!resolution)
throw new Error(`Assertion failed: The resolution should have been registered`);
return resolution;
});
}));
const sortTopLevelFirst = (locator: Locator) => topLevelResolutions.has(locator.locatorHash) ? `0` : `1`;
const sortByLocatorString = (locator: Locator) => structUtils.stringifyLocator(locator);
const sortedAddedPackages = miscUtils.sortMap(addedPackages, [sortTopLevelFirst, sortByLocatorString]);
const sortedRemovedPackages = miscUtils.sortMap(removedPackages, [sortTopLevelFirst, sortByLocatorString]);
const recommendedLength = opts.report.getRecommendedLength();
if (sortedAddedPackages.length > 0)
opts.report.reportInfo(MessageName.UPDATED_RESOLUTION_RECORD, `${formatUtils.pretty(this.configuration, `+`, formatUtils.Type.ADDED)} ${formatUtils.prettyTruncatedLocatorList(this.configuration, sortedAddedPackages, recommendedLength)}`);
if (sortedRemovedPackages.length > 0) {
opts.report.reportInfo(MessageName.UPDATED_RESOLUTION_RECORD, `${formatUtils.pretty(this.configuration, `-`, formatUtils.Type.REMOVED)} ${formatUtils.prettyTruncatedLocatorList(this.configuration, sortedRemovedPackages, recommendedLength)}`);
}
}
// In this step we now create virtual packages for each package with at
// least one peer dependency. We also use it to search for the alias
// descriptors that aren't depended upon by anything and can be safely
// pruned.
const volatileDescriptors = new Set(this.resolutionAliases.values());
const optionalBuilds = new Set(allPackages.keys());
const accessibleLocators = new Set<LocatorHash>();
const peerRequirements: Project['peerRequirements'] = new Map();
const peerWarnings: Project['peerWarnings'] = [];
applyVirtualResolutionMutations({
project: this,
accessibleLocators,
volatileDescriptors,
optionalBuilds,
peerRequirements,
peerWarnings,
allDescriptors,