-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathProject.ts
1916 lines (1481 loc) Β· 76 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 {PortablePath, npath, ppath, toFilename, xfs, normalizeLineEndings} from '@yarnpkg/fslib';
import {parseSyml, stringifySyml} from '@yarnpkg/parsers';
import {UsageError} from 'clipanion';
import {createHash} from 'crypto';
import {structuredPatch} from 'diff';
// @ts-ignore
import Logic from 'logic-solver';
import pLimit from 'p-limit';
import semver from 'semver';
import {tmpNameSync} from 'tmp';
import {Cache} from './Cache';
import {Configuration, FormatType} from './Configuration';
import {Fetcher} from './Fetcher';
import {Installer, BuildDirective, BuildType} from './Installer';
import {LegacyMigrationResolver} from './LegacyMigrationResolver';
import {Linker} 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 {ThrowReport} from './ThrowReport';
import {Workspace} from './Workspace';
import {isFolderInside} from './folderUtils';
import * as miscUtils from './miscUtils';
import * as scriptUtils from './scriptUtils';
import * as semverUtils from './semverUtils';
import * as structUtils from './structUtils';
import {IdentHash, DescriptorHash, LocatorHash} from './types';
import {Descriptor, Ident, Locator, Package} from './types';
import {LinkType} 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.
const LOCKFILE_VERSION = 4;
const MULTIPLE_KEYS_REGEXP = / *, */g;
export type InstallOptions = {
cache: Cache,
fetcher?: Fetcher,
resolver?: Resolver
report: Report,
immutable?: boolean,
lockfileOnly?: boolean,
};
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 accessibleLocators: Set<LocatorHash> = new Set();
public originalPackages: Map<LocatorHash, Package> = new Map();
public optionalBuilds: Set<LocatorHash> = new Set();
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, toFilename(`package.json`)))) {
packageCwd = currentCwd;
break;
}
nextCwd = ppath.dirname(currentCwd);
}
const project = new Project(configuration.projectCwd, {configuration});
await project.setupResolutions();
await project.setupWorkspaces();
// 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);
if (locator)
return {project, locator, workspace: null};
throw new UsageError(`The nearest package directory (${packageCwd}) doesn't seem to be part of the project declared at ${project.cwd}. If the project directory is right, it might be that you forgot to list a workspace. If it isn't, it's likely because you have a yarn.lock file at the detected location, confusing the project detection.`);
}
static generateBuildStateFile(buildState: Map<LocatorHash, string>, locatorStore: Map<LocatorHash, Locator>) {
let bstateFile = `# Warning: This file is automatically generated. Removing it is fine, but will\n# cause all your builds to become invalidated.\n`;
const bstateData = [...buildState].map(([locatorHash, hash]) => {
const locator = locatorStore.get(locatorHash);
if (typeof locator === `undefined`)
throw new Error(`Assertion failed: The locator should have been registered`);
return [structUtils.stringifyLocator(locator), locator.locatorHash, hash];
});
for (const [locatorString, locatorHash, buildHash] of miscUtils.sortMap(bstateData, [d => d[0], d => d[1]])) {
bstateFile += `\n`;
bstateFile += `# ${locatorString}\n`;
bstateFile += `${JSON.stringify(locatorHash)}:\n`;
bstateFile += ` ${buildHash}\n`;
}
return bstateFile;
}
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();
const lockfilePath = ppath.join(this.cwd, this.configuration.get(`lockfileFilename`));
const defaultLanguageName = this.configuration.get(`defaultLanguageName`);
if (xfs.existsSync(lockfilePath)) {
const content = await xfs.readFilePromise(lockfilePath, `utf8`);
const parsed: any = parseSyml(content);
// Protects against v1 lockfiles
if (parsed.__metadata) {
const lockfileVersion = parsed.__metadata.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);
const version = manifest.version;
const languageName = manifest.languageName || defaultLanguageName;
const linkType = data.linkType.toUpperCase() as LinkType;
const dependencies = manifest.dependencies;
const peerDependencies = manifest.peerDependencies;
const dependenciesMeta = manifest.dependenciesMeta;
const peerDependenciesMeta = manifest.peerDependenciesMeta;
const bin = manifest.bin;
if (data.checksum != null)
this.storedChecksums.set(locator.locatorHash, data.checksum);
if (lockfileVersion >= LOCKFILE_VERSION) {
const pkg: Package = {...locator, version, languageName, linkType, dependencies, peerDependencies, dependenciesMeta, peerDependenciesMeta, bin};
this.originalPackages.set(pkg.locatorHash, pkg);
}
for (const entry of key.split(MULTIPLE_KEYS_REGEXP)) {
const descriptor = structUtils.parseDescriptor(entry);
this.storedDescriptors.set(descriptor.descriptorHash, descriptor);
if (lockfileVersion >= LOCKFILE_VERSION) {
// If the lockfile is up-to-date, we can simply register the
// resolution as a done deal.
this.storedResolutions.set(descriptor.descriptorHash, locator.locatorHash);
} else {
// But if it isn't, then we instead setup an alias so that the
// descriptor will be re-resolved (so that we get to retrieve the
// new fields) while still resolving to the same locators.
const resolutionDescriptor = structUtils.convertLocatorToDescriptor(locator);
if (resolutionDescriptor.descriptorHash !== descriptor.descriptorHash) {
this.storedDescriptors.set(resolutionDescriptor.descriptorHash, resolutionDescriptor);
this.resolutionAliases.set(descriptor.descriptorHash, resolutionDescriptor.descriptorHash);
}
}
}
}
}
}
}
private async setupWorkspaces() {
this.workspaces = [];
this.workspacesByCwd = new Map();
this.workspacesByIdent = new Map();
let workspaceCwds = [this.cwd];
while (workspaceCwds.length > 0) {
const passCwds = workspaceCwds;
workspaceCwds = [];
for (const workspaceCwd of passCwds) {
if (this.workspacesByCwd.has(workspaceCwd))
continue;
const workspace = await this.addWorkspace(workspaceCwd);
const workspacePkg = this.storedPackages.get(workspace.anchoredLocator.locatorHash);
if (workspacePkg)
workspace.dependencies = workspacePkg.dependencies;
for (const workspaceCwd of workspace.workspacesCwds) {
workspaceCwds.push(workspaceCwd);
}
}
}
}
private async addWorkspace(workspaceCwd: PortablePath) {
const workspace = new Workspace(workspaceCwd, {project: this});
await workspace.setup();
if (this.workspacesByIdent.has(workspace.locator.identHash))
throw new Error(`Duplicate workspace name ${structUtils.prettyIdent(this.configuration, workspace.locator)}`);
this.workspaces.push(workspace);
this.workspacesByCwd.set(workspaceCwd, workspace);
this.workspacesByIdent.set(workspace.locator.identHash, workspace);
return workspace;
}
get topLevelWorkspace() {
return this.getWorkspaceByCwd(this.cwd);
}
tryWorkspaceByCwd(workspaceCwd: PortablePath) {
if (!ppath.isAbsolute(workspaceCwd))
workspaceCwd = ppath.resolve(this.cwd, workspaceCwd);
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;
}
getWorkspaceByFilePath(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)
throw new Error(`Workspace not found (${filePath})`);
return bestWorkspace;
}
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) {
const workspace = this.tryWorkspaceByIdent(descriptor);
if (workspace === null || !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) {
if (structUtils.isVirtualLocator(locator))
locator = structUtils.devirtualizeLocator(locator);
const workspace = this.tryWorkspaceByIdent(locator);
if (workspace === null || (workspace.locator.locatorHash !== locator.locatorHash && 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;
}
forgetTransientResolutions() {
const resolver = this.configuration.makeResolver();
const forgottenPackages = new Set();
for (const pkg of this.originalPackages.values()) {
let shouldPersistResolution: boolean;
try {
shouldPersistResolution = resolver.shouldPersistResolution(pkg, {project: this, resolver});
} catch {
shouldPersistResolution = false;
}
if (!shouldPersistResolution) {
this.originalPackages.delete(pkg.locatorHash);
forgottenPackages.add(pkg.locatorHash);
}
}
for (const [descriptorHash, locatorHash] of this.storedResolutions) {
if (forgottenPackages.has(locatorHash)) {
this.storedResolutions.delete(descriptorHash);
this.storedDescriptors.delete(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) {
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) {
return locator;
}
}
return null;
}
async resolveEverything(opts: {report: Report, lockfileOnly: true, resolver?: Resolver} | {report: Report, lockfileOnly?: boolean, cache: Cache, resolver?: Resolver}) {
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();
// 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();
await legacyMigrationResolver.setup(this, {report: opts.report});
const resolver: Resolver = opts.lockfileOnly
? new MultiResolver([new LockfileResolver(), new RunInstallPleaseResolver(realResolver)])
: new MultiResolver([new LockfileResolver(), legacyMigrationResolver, realResolver]);
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}};
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 resolutionDependencies = new Map<DescriptorHash, Set<DescriptorHash>>();
const haveBeenAliased = new Set<DescriptorHash>();
let nextResolutionPass = new Set<DescriptorHash>();
for (const workspace of this.workspaces) {
const workspaceDescriptor = workspace.anchoredDescriptor;
allDescriptors.set(workspaceDescriptor.descriptorHash, workspaceDescriptor);
nextResolutionPass.add(workspaceDescriptor.descriptorHash);
}
const limit = pLimit(10);
while (nextResolutionPass.size !== 0) {
const currentResolutionPass = nextResolutionPass;
nextResolutionPass = new Set();
// We remove from the "mustBeResolved" list all packages that have
// already been resolved previously.
for (const descriptorHash of currentResolutionPass)
if (allResolutions.has(descriptorHash))
currentResolutionPass.delete(descriptorHash);
if (currentResolutionPass.size === 0)
break;
// We check that the resolution dependencies have been resolved for all
// descriptors that we're about to resolve. Buffalo buffalo buffalo
// buffalo.
const deferredResolutions = new Set<DescriptorHash>();
const resolvedDependencies = new Map<DescriptorHash, Map<DescriptorHash, Package>>();
for (const descriptorHash of currentResolutionPass) {
const descriptor = allDescriptors.get(descriptorHash);
if (!descriptor)
throw new Error(`Assertion failed: The descriptor should have been registered`);
let dependencies = resolutionDependencies.get(descriptorHash);
if (typeof dependencies === `undefined`) {
resolutionDependencies.set(descriptorHash, dependencies = new Set());
for (const dependency of resolver.getResolutionDependencies(descriptor, resolveOptions)) {
allDescriptors.set(dependency.descriptorHash, dependency);
dependencies.add(dependency.descriptorHash);
}
}
const resolved = miscUtils.getMapWithDefault(resolvedDependencies, descriptorHash);
for (const dependencyHash of dependencies) {
const resolution = allResolutions.get(dependencyHash);
if (typeof resolution !== `undefined`) {
const dependencyPkg = allPackages.get(resolution);
if (typeof dependencyPkg === `undefined`)
throw new Error(`Assertion failed: The package should have been registered`);
// The dependency is ready. We register it into the map so
// that we can pass that to getCandidates right after.
resolved.set(dependencyHash, dependencyPkg);
} else {
// One of the resolution dependencies of this descriptor is
// missing; we need to postpone its resolution for now.
deferredResolutions.add(descriptorHash);
// For this pass however we'll want to schedule the resolution
// of the dependency (so that it's probably ready next pass).
currentResolutionPass.add(dependencyHash);
}
}
}
// Note: we're postponing the resolution only once we already know all
// those that are going to be postponed. This way we can detect
// potential cyclic dependencies.
for (const descriptorHash of deferredResolutions) {
currentResolutionPass.delete(descriptorHash);
nextResolutionPass.add(descriptorHash);
}
if (currentResolutionPass.size === 0)
throw new Error(`Assertion failed: Descriptors should not have cyclic dependencies`);
// Then we request the resolvers for the list of possible references that
// match the given ranges. That will give us a set of candidate references
// for each descriptor.
const passCandidates = new Map(await Promise.all(Array.from(currentResolutionPass).map(descriptorHash => limit(async () => {
const descriptor = allDescriptors.get(descriptorHash);
if (typeof descriptor === `undefined`)
throw new Error(`Assertion failed: The descriptor should have been registered`);
const descriptorDependencies = resolvedDependencies.get(descriptor.descriptorHash);
if (typeof descriptorDependencies === `undefined`)
throw new Error(`Assertion failed: The descriptor dependencies should have been registered`);
let candidateLocators;
try {
candidateLocators = await resolver.getCandidates(descriptor, descriptorDependencies, resolveOptions);
} catch (error) {
error.message = `${structUtils.prettyDescriptor(this.configuration, descriptor)}: ${error.message}`;
throw error;
}
if (candidateLocators.length === 0)
throw new Error(`No candidate found for ${structUtils.prettyDescriptor(this.configuration, descriptor)}`);
return [descriptor.descriptorHash, candidateLocators] as [DescriptorHash, Array<Locator>];
}))));
// That's where we'll store our resolutions until everything has been
// resolved and can be injected into the various stores.
//
// The reason we're storing them in a temporary store instead of writing
// them directly into the global ones is that otherwise we would end up
// with different store orderings between dependency loaded from a
// lockfiles and those who don't (when using a lockfile all descriptors
// will fall into the next shortcut, but when no lockfile is there only
// some of them will; since maps are sorted by insertion, it would affect
// the way they would be ordered).
const passResolutions = new Map<DescriptorHash, Locator>();
// We now make a pre-pass to automatically resolve the descriptors that
// can only be satisfied by a single reference.
for (const [descriptorHash, candidateLocators] of passCandidates) {
if (candidateLocators.length !== 1)
continue;
passResolutions.set(descriptorHash, candidateLocators[0]);
passCandidates.delete(descriptorHash);
}
// We make a second pre-pass to automatically resolve the descriptors
// that can be satisfied by a package we're already using (deduplication).
for (const [descriptorHash, candidateLocators] of passCandidates) {
const selectedLocator = candidateLocators.find(locator => allPackages.has(locator.locatorHash));
if (!selectedLocator)
continue;
passResolutions.set(descriptorHash, selectedLocator);
passCandidates.delete(descriptorHash);
}
// All entries that remain in "passCandidates" are from descriptors that
// we haven't been able to resolve in the first place. We'll now configure
// our SAT solver so that it can figure it out for us. To do this, we
// simply add a constraint for each descriptor that lists all the
// descriptors it would accept. We don't have to check whether the
// locators obtained have already been selected, because if they were the
// would have been resolved in the previous step (we never backtrace to
// try to find better solutions, it would be a too expensive process - we
// just want to get an acceptable solution, not the very best one).
if (passCandidates.size > 0) {
const solver = new Logic.Solver();
for (const candidateLocators of passCandidates.values())
solver.require(Logic.or(...candidateLocators.map(locator => locator.locatorHash)));
let remainingSolutions = 100;
let solution;
let bestSolution = null;
let bestScore = Infinity;
while (remainingSolutions > 0 && (solution = solver.solve()) !== null) {
const trueVars = solution.getTrueVars();
solver.forbid(solution.getFormula());
if (trueVars.length < bestScore) {
bestSolution = trueVars;
bestScore = trueVars.length;
}
remainingSolutions -= 1;
}
if (!bestSolution)
throw new Error(`Assertion failed: No resolution found by the SAT solver`);
const solutionSet = new Set<LocatorHash>(bestSolution as Array<LocatorHash>);
for (const [descriptorHash, candidateLocators] of passCandidates.entries()) {
const selectedLocator = candidateLocators.find(locator => solutionSet.has(locator.locatorHash));
if (!selectedLocator)
throw new Error(`Assertion failed: The descriptor should have been solved during the previous step`);
passResolutions.set(descriptorHash, selectedLocator);
passCandidates.delete(descriptorHash);
}
}
// We now iterate over the locators we've got and, for each of them that
// hasn't been seen before, we fetch its dependency list and schedule
// them for the next cycle.
const newLocators = Array.from(passResolutions.values()).filter(locator => {
return !allPackages.has(locator.locatorHash);
});
const newPackages = new Map(await Promise.all(newLocators.map(async locator => {
const original = await miscUtils.prettifyAsyncErrors(async () => {
return await resolver.resolve(locator, resolveOptions);
}, message => {
return `${structUtils.prettyLocator(this.configuration, locator)}: ${message}`;
});
if (!structUtils.areLocatorsEqual(locator, original))
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, original)})`);
const pkg = this.configuration.normalizePackage(original);
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, locator, resolveOptions);
pkg.dependencies.set(identHash, bound);
}
return [pkg.locatorHash, {original, pkg}] as const;
})));
// Now that the resolution is finished, we can finally insert the data
// stored inside our pass stores into the resolution ones (we now have
// the guarantee that they'll always be inserted into in the same order,
// since mustBeResolved is stable regardless of the order in which the
// resolvers return)
for (const descriptorHash of currentResolutionPass) {
const locator = passResolutions.get(descriptorHash);
if (!locator)
throw new Error(`Assertion failed: The locator should have been registered`);
allResolutions.set(descriptorHash, locator.locatorHash);
// If undefined it means that the package was already known and thus
// didn't need to be resolved again.
const resolutionEntry = newPackages.get(locator.locatorHash);
if (typeof resolutionEntry === `undefined`)
continue;
const {original, pkg} = resolutionEntry;
originalPackages.set(original.locatorHash, original);
allPackages.set(pkg.locatorHash, pkg);
for (const descriptor of pkg.dependencies.values()) {
allDescriptors.set(descriptor.descriptorHash, descriptor);
nextResolutionPass.add(descriptor.descriptorHash);
// We must check and make sure that the descriptor didn't get aliased
// to something else
const aliasHash = this.resolutionAliases.get(descriptor.descriptorHash);
if (aliasHash === undefined)
continue;
// It doesn't cost us much to support the case where a descriptor is
// equal to its own alias (which should mean "no alias")
if (descriptor.descriptorHash === aliasHash)
continue;
const alias = this.storedDescriptors.get(aliasHash);
if (!alias)
throw new Error(`Assertion failed: The alias should have been registered`);
// If it's already been "resolved" (in reality it will be the temporary
// resolution we've set in the next few lines) we simply must skip it
if (allResolutions.has(descriptor.descriptorHash))
continue;
// Temporarily set an invalid resolution so that it won't be resolved
// multiple times if it is found multiple times in the dependency
// tree (this is only temporary, we will replace it by the actual
// resolution after we've finished resolving everything)
allResolutions.set(descriptor.descriptorHash, `temporary` as LocatorHash);
// We can now replace the descriptor by its alias in the list of
// descriptors that must be resolved
nextResolutionPass.delete(descriptor.descriptorHash);
nextResolutionPass.add(aliasHash);
allDescriptors.set(aliasHash, alias);
haveBeenAliased.add(descriptor.descriptorHash);
}
}
}
// Each package that should have been resolved but was skipped because it
// was aliased will now see the resolution for its alias propagated to it
while (haveBeenAliased.size > 0) {
let hasChanged = false;
for (const descriptorHash of haveBeenAliased) {
const descriptor = allDescriptors.get(descriptorHash);
if (!descriptor)
throw new Error(`Assertion failed: The descriptor should have been registered`);
const aliasHash = this.resolutionAliases.get(descriptorHash);
if (aliasHash === undefined)
throw new Error(`Assertion failed: The descriptor should have an alias`);
const resolution = allResolutions.get(aliasHash);
if (resolution === undefined)
throw new Error(`Assertion failed: The resolution should have been registered`);
// The following can happen if a package gets aliased to another package
// that's itself aliased - in this case we just process all those we can
// do, then make new passes until everything is resolved
if (resolution === `temporary`)
continue;
haveBeenAliased.delete(descriptorHash);
allResolutions.set(descriptorHash, resolution);
hasChanged = true;
}
if (!hasChanged) {
throw new Error(`Alias loop detected`);
}
}
// 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>();
applyVirtualResolutionMutations({
project: this,
report: opts.report,
accessibleLocators,
volatileDescriptors,
optionalBuilds,
allDescriptors,
allResolutions,
allPackages,
});
// All descriptors still referenced within the volatileDescriptors set are
// descriptors that aren't depended upon by anything in the dependency tree.
for (const descriptorHash of volatileDescriptors) {
allDescriptors.delete(descriptorHash);
allResolutions.delete(descriptorHash);
}
// Import the dependencies for each resolved workspaces into their own
// Workspace instance.
for (const workspace of this.workspaces) {
const pkg = allPackages.get(workspace.anchoredLocator.locatorHash);
if (!pkg)
throw new Error(`Assertion failed: Expected workspace to have been resolved`);
workspace.dependencies = new Map(pkg.dependencies);
}
// Everything is done, we can now update our internal resolutions to
// reference the new ones
this.storedResolutions = allResolutions;
this.storedDescriptors = allDescriptors;
this.storedPackages = allPackages;
this.accessibleLocators = accessibleLocators;
this.originalPackages = originalPackages;
this.optionalBuilds = optionalBuilds;
}
async fetchEverything({cache, report, fetcher: userFetcher}: InstallOptions) {
const fetcher = userFetcher || this.configuration.makeFetcher();
const fetcherOptions = {checksums: this.storedChecksums, project: this, cache, fetcher, report};
const locatorHashes = miscUtils.sortMap(this.storedResolutions.values(), [(locatorHash: LocatorHash) => {
const pkg = this.storedPackages.get(locatorHash);
if (!pkg)
throw new Error(`Assertion failed: The locator should have been registered`);
return structUtils.stringifyLocator(pkg);
}]);
const limit = pLimit(5);
let firstError = false;
const progress = Report.progressViaCounter(locatorHashes.length);
report.reportProgress(progress);
await Promise.all(locatorHashes.map(locatorHash => limit(async () => {
const pkg = this.storedPackages.get(locatorHash);
if (!pkg)
throw new Error(`Assertion failed: The locator should have been registered`);
if (structUtils.isVirtualLocator(pkg))
return;
let fetchResult;
try {
fetchResult = await fetcher.fetch(pkg, fetcherOptions);
} catch (error) {
error.message = `${structUtils.prettyLocator(this.configuration, pkg)}: ${error.message}`;
report.reportExceptionOnce(error);
firstError = error;
return;
}
if (fetchResult.checksum)
this.storedChecksums.set(pkg.locatorHash, fetchResult.checksum);
else
this.storedChecksums.delete(pkg.locatorHash);
if (fetchResult.releaseFs) {
fetchResult.releaseFs();
}
}).finally(() => {
progress.tick();
})));
if (firstError) {
throw firstError;
}
}
async linkEverything({cache, report, fetcher: optFetcher}: InstallOptions) {
const fetcher = optFetcher || this.configuration.makeFetcher();
const fetcherOptions = {checksums: this.storedChecksums, project: this, cache, fetcher, report};
const linkers = this.configuration.getLinkers();
const linkerOptions = {project: this, report};
const installers = new Map(linkers.map(linker => {
return [linker, linker.makeInstaller(linkerOptions)] as [Linker, Installer];
}));
const packageLinkers: Map<LocatorHash, Linker> = new Map();
const packageLocations: Map<LocatorHash, PortablePath> = new Map();
const packageBuildDirectives: Map<LocatorHash, { directives: BuildDirective[], buildLocations: PortablePath[] }> = new Map();
// Step 1: Installing the packages on the disk
for (const locatorHash of this.accessibleLocators) {
const pkg = this.storedPackages.get(locatorHash);
if (!pkg)
throw new Error(`Assertion failed: The locator should have been registered`);
const fetchResult = await fetcher.fetch(pkg, fetcherOptions);
if (this.tryWorkspaceByLocator(pkg) !== null) {
const buildScripts: Array<BuildDirective> = [];
const {scripts} = await Manifest.find(fetchResult.prefixPath, {baseFs: fetchResult.packageFs});
for (const scriptName of [`preinstall`, `install`, `postinstall`])
if (scripts.has(scriptName))
buildScripts.push([BuildType.SCRIPT, scriptName]);
try {
for (const installer of installers.values()) {
await installer.installPackage(pkg, fetchResult);
}
} finally {
if (fetchResult.releaseFs) {
fetchResult.releaseFs();
}
}
const location = ppath.join(fetchResult.packageFs.getRealPath(), fetchResult.prefixPath);
packageLocations.set(pkg.locatorHash, location);
if (buildScripts.length > 0) {
packageBuildDirectives.set(pkg.locatorHash, {
directives: buildScripts,
buildLocations: [location],
});
}
} else {
const linker = linkers.find(linker => linker.supportsPackage(pkg, linkerOptions));
if (!linker)
throw new ReportError(MessageName.LINKER_NOT_FOUND, `${structUtils.prettyLocator(this.configuration, pkg)} isn't supported by any available linker`);
const installer = installers.get(linker);
if (!installer)
throw new Error(`Assertion failed: The installer should have been registered`);
let installStatus;
try {
installStatus = await installer.installPackage(pkg, fetchResult);
} finally {
if (fetchResult.releaseFs) {
fetchResult.releaseFs();
}