-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathNodeModulesLinker.ts
1375 lines (1173 loc) Β· 55 KB
/
NodeModulesLinker.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 {structUtils, Report, Manifest, miscUtils, formatUtils} from '@yarnpkg/core';
import {Locator, Package, FinalizeInstallStatus, hashUtils} from '@yarnpkg/core';
import {Linker, LinkOptions, MinimalLinkOptions, LinkType, WindowsLinkType} from '@yarnpkg/core';
import {LocatorHash, Descriptor, DependencyMeta, Configuration} from '@yarnpkg/core';
import {MessageName, Project, FetchResult, Installer} from '@yarnpkg/core';
import {PortablePath, npath, ppath, toFilename, Filename} from '@yarnpkg/fslib';
import {VirtualFS, xfs, FakeFS, NativePath} from '@yarnpkg/fslib';
import {ZipOpenFS} from '@yarnpkg/libzip';
import {buildNodeModulesTree} from '@yarnpkg/nm';
import {NodeModulesLocatorMap, buildLocatorMap, NodeModulesHoistingLimits} from '@yarnpkg/nm';
import {parseSyml} from '@yarnpkg/parsers';
import {jsInstallUtils} from '@yarnpkg/plugin-pnp';
import {PnpApi, PackageInformation} from '@yarnpkg/pnp';
import cmdShim from '@zkochan/cmd-shim';
import {UsageError} from 'clipanion';
import crypto from 'crypto';
import fs from 'fs';
const STATE_FILE_VERSION = 1;
const NODE_MODULES = `node_modules` as Filename;
const DOT_BIN = `.bin` as Filename;
const INSTALL_STATE_FILE = `.yarn-state.yml` as Filename;
const MTIME_ACCURANCY = 1000;
type InstallState = {locatorMap: NodeModulesLocatorMap, locationTree: LocationTree, binSymlinks: BinSymlinkMap, nmMode: NodeModulesMode, mtimeMs: number};
type BinSymlinkMap = Map<PortablePath, Map<Filename, PortablePath>>;
type LoadManifest = (locator: LocatorKey, installLocation: PortablePath) => Promise<Pick<Manifest, 'bin'>>;
export enum NodeModulesMode {
CLASSIC = `classic`,
HARDLINKS_LOCAL = `hardlinks-local`,
HARDLINKS_GLOBAL = `hardlinks-global`,
}
export class NodeModulesLinker implements Linker {
private installStateCache: Map<string, Promise<InstallState | null>> = new Map();
getCustomDataKey() {
return JSON.stringify({
name: `NodeModulesLinker`,
version: 3,
});
}
supportsPackage(pkg: Package, opts: MinimalLinkOptions) {
return this.isEnabled(opts);
}
async findPackageLocation(locator: Locator, opts: LinkOptions) {
if (!this.isEnabled(opts))
throw new Error(`Assertion failed: Expected the node-modules linker to be enabled`);
const workspace = opts.project.tryWorkspaceByLocator(locator);
if (workspace)
return workspace.cwd;
const installState = await miscUtils.getFactoryWithDefault(this.installStateCache, opts.project.cwd, async () => {
return await findInstallState(opts.project, {unrollAliases: true});
});
if (installState === null)
throw new UsageError(`Couldn't find the node_modules state file - running an install might help (findPackageLocation)`);
const locatorInfo = installState.locatorMap.get(structUtils.stringifyLocator(locator));
if (!locatorInfo) {
const err = new UsageError(`Couldn't find ${structUtils.prettyLocator(opts.project.configuration, locator)} in the currently installed node_modules map - running an install might help`);
(err as any).code = `LOCATOR_NOT_INSTALLED`;
throw err;
}
// Sort locations from shallowest to deepest in terms of directory nesting
const sortedLocations = locatorInfo.locations.sort((loc1, loc2) => loc1.split(ppath.sep).length - loc2.split(ppath.sep).length);
// Find the location with shallowest directory nesting that starts inside node_modules of cwd
const startingCwdModules = ppath.join(opts.project.configuration.startingCwd, NODE_MODULES);
return sortedLocations.find(location => ppath.contains(startingCwdModules, location)) || locatorInfo.locations[0];
}
async findPackageLocator(location: PortablePath, opts: LinkOptions) {
if (!this.isEnabled(opts))
return null;
const installState = await miscUtils.getFactoryWithDefault(this.installStateCache, opts.project.cwd, async () => {
return await findInstallState(opts.project, {unrollAliases: true});
});
if (installState === null)
return null;
const {locationRoot, segments} = parseLocation(ppath.resolve(location), {skipPrefix: opts.project.cwd});
let locationNode = installState.locationTree.get(locationRoot);
if (!locationNode)
return null;
let locator = locationNode.locator!;
for (const segment of segments) {
locationNode = locationNode.children.get(segment);
if (!locationNode)
break;
locator = locationNode.locator || locator;
}
return structUtils.parseLocator(locator);
}
makeInstaller(opts: LinkOptions) {
return new NodeModulesInstaller(opts);
}
private isEnabled(opts: MinimalLinkOptions) {
return opts.project.configuration.get(`nodeLinker`) === `node-modules`;
}
}
class NodeModulesInstaller implements Installer {
// Stores data that we need to extract in the `installPackage` step but use
// in the `finalizeInstall` step. Contrary to custom data this isn't persisted
// anywhere - we literally just use it for the lifetime of the installer then
// discard it.
private localStore: Map<LocatorHash, {
pkg: Package;
customPackageData: CustomPackageData;
dependencyMeta: DependencyMeta;
pnpNode: PackageInformation<NativePath>;
}> = new Map();
private realLocatorChecksums: Map<LocatorHash, string | null> = new Map();
constructor(private opts: LinkOptions) {
// Nothing to do
}
private customData: {
store: Map<LocatorHash, CustomPackageData>;
} = {
store: new Map(),
};
attachCustomData(customData: any) {
this.customData = customData;
}
async installPackage(pkg: Package, fetchResult: FetchResult) {
const packageLocation = ppath.resolve(fetchResult.packageFs.getRealPath(), fetchResult.prefixPath);
let customPackageData = this.customData.store.get(pkg.locatorHash);
if (typeof customPackageData === `undefined`) {
customPackageData = await extractCustomPackageData(pkg, fetchResult);
if (pkg.linkType === LinkType.HARD) {
this.customData.store.set(pkg.locatorHash, customPackageData);
}
}
// We don't link the package at all if it's for an unsupported platform
if (!structUtils.isPackageCompatible(pkg, this.opts.project.configuration.getSupportedArchitectures()))
return {packageLocation: null, buildDirective: null};
const packageDependencies = new Map<string, string | [string, string] | null>();
const packagePeers = new Set<string>();
if (!packageDependencies.has(structUtils.stringifyIdent(pkg)))
packageDependencies.set(structUtils.stringifyIdent(pkg), pkg.reference);
let realLocator: Locator = pkg;
// Only virtual packages should have effective peer dependencies, but the
// workspaces are a special case because the original packages are kept in
// the dependency tree even after being virtualized; so in their case we
// just ignore their declared peer dependencies.
if (structUtils.isVirtualLocator(pkg)) {
realLocator = structUtils.devirtualizeLocator(pkg);
for (const descriptor of pkg.peerDependencies.values()) {
packageDependencies.set(structUtils.stringifyIdent(descriptor), null);
packagePeers.add(structUtils.stringifyIdent(descriptor));
}
}
const pnpNode: PackageInformation<NativePath> = {
packageLocation: `${npath.fromPortablePath(packageLocation)}/`,
packageDependencies,
packagePeers,
linkType: pkg.linkType,
discardFromLookup: fetchResult.discardFromLookup ?? false,
};
this.localStore.set(pkg.locatorHash, {
pkg,
customPackageData,
dependencyMeta: this.opts.project.getDependencyMeta(pkg, pkg.version),
pnpNode,
});
// We need ZIP contents checksum for CAS addressing purposes, so we need to strip cache key from checksum here
const checksum = fetchResult.checksum ? fetchResult.checksum.substring(fetchResult.checksum.indexOf(`/`) + 1) : null;
this.realLocatorChecksums.set(realLocator.locatorHash, checksum);
return {
packageLocation,
buildDirective: null,
};
}
async attachInternalDependencies(locator: Locator, dependencies: Array<[Descriptor, Locator]>) {
const slot = this.localStore.get(locator.locatorHash);
if (typeof slot === `undefined`)
throw new Error(`Assertion failed: Expected information object to have been registered`);
for (const [descriptor, locator] of dependencies) {
const target = !structUtils.areIdentsEqual(descriptor, locator)
? [structUtils.stringifyIdent(locator), locator.reference] as [string, string]
: locator.reference;
slot.pnpNode.packageDependencies.set(structUtils.stringifyIdent(descriptor), target);
}
}
async attachExternalDependents(locator: Locator, dependentPaths: Array<PortablePath>) {
throw new Error(`External dependencies haven't been implemented for the node-modules linker`);
}
async finalizeInstall() {
if (this.opts.project.configuration.get(`nodeLinker`) !== `node-modules`)
return undefined;
const defaultFsLayer = new VirtualFS({
baseFs: new ZipOpenFS({
maxOpenFiles: 80,
readOnlyArchives: true,
}),
});
let preinstallState = await findInstallState(this.opts.project);
const nmModeSetting = this.opts.project.configuration.get(`nmMode`);
// Remove build state as well, to force rebuild of all the packages
if (preinstallState === null || nmModeSetting !== preinstallState.nmMode) {
this.opts.project.storedBuildState.clear();
preinstallState = {locatorMap: new Map(), binSymlinks: new Map(), locationTree: new Map(), nmMode: nmModeSetting, mtimeMs: 0};
}
const hoistingLimitsByCwd = new Map(this.opts.project.workspaces.map(workspace => {
let hoistingLimits = this.opts.project.configuration.get(`nmHoistingLimits`);
try {
hoistingLimits = miscUtils.validateEnum(NodeModulesHoistingLimits, workspace.manifest.installConfig?.hoistingLimits ?? hoistingLimits);
} catch (e) {
const workspaceName = structUtils.prettyWorkspace(this.opts.project.configuration, workspace);
this.opts.report.reportWarning(MessageName.INVALID_MANIFEST, `${workspaceName}: Invalid 'installConfig.hoistingLimits' value. Expected one of ${Object.values(NodeModulesHoistingLimits).join(`, `)}, using default: "${hoistingLimits}"`);
}
return [workspace.relativeCwd, hoistingLimits];
}));
const selfReferencesByCwd = new Map(this.opts.project.workspaces.map(workspace => {
let selfReferences = this.opts.project.configuration.get(`nmSelfReferences`);
selfReferences = workspace.manifest.installConfig?.selfReferences ?? selfReferences;
return [workspace.relativeCwd, selfReferences];
}));
const pnpApi: PnpApi = {
VERSIONS: {
std: 1,
},
topLevel: {
name: null,
reference: null,
},
getLocator: (name, referencish) => {
if (Array.isArray(referencish)) {
return {name: referencish[0], reference: referencish[1]};
} else {
return {name, reference: referencish};
}
},
getDependencyTreeRoots: () => {
return this.opts.project.workspaces.map(workspace => {
const anchoredLocator = workspace.anchoredLocator;
return {name: structUtils.stringifyIdent(workspace.locator), reference: anchoredLocator.reference};
});
},
getPackageInformation: pnpLocator => {
const locator = pnpLocator.reference === null
? this.opts.project.topLevelWorkspace.anchoredLocator
: structUtils.makeLocator(structUtils.parseIdent(pnpLocator.name), pnpLocator.reference);
const slot = this.localStore.get(locator.locatorHash);
if (typeof slot === `undefined`)
throw new Error(`Assertion failed: Expected the package reference to have been registered`);
return slot.pnpNode;
},
findPackageLocator: location => {
const workspace = this.opts.project.tryWorkspaceByCwd(npath.toPortablePath(location));
if (workspace !== null) {
const anchoredLocator = workspace.anchoredLocator;
return {name: structUtils.stringifyIdent(anchoredLocator), reference: anchoredLocator.reference};
}
throw new Error(`Assertion failed: Unimplemented`);
},
resolveToUnqualified: () => {
throw new Error(`Assertion failed: Unimplemented`);
},
resolveUnqualified: () => {
throw new Error(`Assertion failed: Unimplemented`);
},
resolveRequest: () => {
throw new Error(`Assertion failed: Unimplemented`);
},
resolveVirtual: path => {
return npath.fromPortablePath(VirtualFS.resolveVirtual(npath.toPortablePath(path)));
},
};
const {tree, errors, preserveSymlinksRequired} = buildNodeModulesTree(pnpApi, {pnpifyFs: false, validateExternalSoftLinks: true, hoistingLimitsByCwd, project: this.opts.project, selfReferencesByCwd});
if (!tree) {
for (const {messageName, text} of errors)
this.opts.report.reportError(messageName, text);
return undefined;
}
const locatorMap = buildLocatorMap(tree);
await persistNodeModules(preinstallState, locatorMap, {
baseFs: defaultFsLayer,
project: this.opts.project,
report: this.opts.report,
realLocatorChecksums: this.realLocatorChecksums,
loadManifest: async locatorKey => {
const locator = structUtils.parseLocator(locatorKey);
const slot = this.localStore.get(locator.locatorHash);
if (typeof slot === `undefined`)
throw new Error(`Assertion failed: Expected the slot to exist`);
return slot.customPackageData.manifest;
},
});
const installStatuses: Array<FinalizeInstallStatus> = [];
for (const [locatorKey, installRecord] of locatorMap.entries()) {
if (isLinkLocator(locatorKey))
continue;
const locator = structUtils.parseLocator(locatorKey);
const slot = this.localStore.get(locator.locatorHash);
if (typeof slot === `undefined`)
throw new Error(`Assertion failed: Expected the slot to exist`);
// Workspaces are built by the core
if (this.opts.project.tryWorkspaceByLocator(slot.pkg))
continue;
const buildScripts = jsInstallUtils.extractBuildScripts(slot.pkg, slot.customPackageData, slot.dependencyMeta, {configuration: this.opts.project.configuration, report: this.opts.report});
if (buildScripts.length === 0)
continue;
installStatuses.push({
buildLocations: installRecord.locations,
locatorHash: locator.locatorHash,
buildDirective: buildScripts,
});
}
if (preserveSymlinksRequired)
this.opts.report.reportWarning(MessageName.NM_PRESERVE_SYMLINKS_REQUIRED, `The application uses portals and that's why ${formatUtils.pretty(this.opts.project.configuration, `--preserve-symlinks`, formatUtils.Type.CODE)} Node option is required for launching it`);
return {
customData: this.customData,
records: installStatuses,
};
}
}
type UnboxPromise<T extends Promise<any>> = T extends Promise<infer U> ? U: never;
type CustomPackageData = UnboxPromise<ReturnType<typeof extractCustomPackageData>>;
async function extractCustomPackageData(pkg: Package, fetchResult: FetchResult) {
const manifest = await Manifest.tryFind(fetchResult.prefixPath, {baseFs: fetchResult.packageFs}) ?? new Manifest();
const preservedScripts = new Set([`preinstall`, `install`, `postinstall`]);
for (const scriptName of manifest.scripts.keys())
if (!preservedScripts.has(scriptName))
manifest.scripts.delete(scriptName);
return {
manifest: {
bin: manifest.bin,
scripts: manifest.scripts,
},
misc: {
hasBindingGyp: jsInstallUtils.hasBindingGyp(fetchResult),
},
};
}
async function writeInstallState(project: Project, locatorMap: NodeModulesLocatorMap, binSymlinks: BinSymlinkMap, nmMode: {value: NodeModulesMode}, {installChangedByUser}: {installChangedByUser: boolean}) {
let locatorState = ``;
locatorState += `# Warning: This file is automatically generated. Removing it is fine, but will\n`;
locatorState += `# cause your node_modules installation to become invalidated.\n`;
locatorState += `\n`;
locatorState += `__metadata:\n`;
locatorState += ` version: ${STATE_FILE_VERSION}\n`;
locatorState += ` nmMode: ${nmMode.value}\n`;
const locators = Array.from(locatorMap.keys()).sort();
const topLevelLocator = structUtils.stringifyLocator(project.topLevelWorkspace.anchoredLocator);
for (const locator of locators) {
const installRecord = locatorMap.get(locator)!;
locatorState += `\n`;
locatorState += `${JSON.stringify(locator)}:\n`;
locatorState += ` locations:\n`;
for (const location of installRecord.locations) {
const internalPath = ppath.contains(project.cwd, location);
if (internalPath === null)
throw new Error(`Assertion failed: Expected the path to be within the project (${location})`);
locatorState += ` - ${JSON.stringify(internalPath)}\n`;
}
if (installRecord.aliases.length > 0) {
locatorState += ` aliases:\n`;
for (const alias of installRecord.aliases) {
locatorState += ` - ${JSON.stringify(alias)}\n`;
}
}
if (locator === topLevelLocator && binSymlinks.size > 0) {
locatorState += ` bin:\n`;
for (const [location, symlinks] of binSymlinks) {
const internalPath = ppath.contains(project.cwd, location);
if (internalPath === null)
throw new Error(`Assertion failed: Expected the path to be within the project (${location})`);
locatorState += ` ${JSON.stringify(internalPath)}:\n`;
for (const [name, target] of symlinks) {
const relativePath = ppath.relative(ppath.join(location, NODE_MODULES), target);
locatorState += ` ${JSON.stringify(name)}: ${JSON.stringify(relativePath)}\n`;
}
}
}
}
const rootPath = project.cwd;
const installStatePath = ppath.join(rootPath, NODE_MODULES, INSTALL_STATE_FILE);
// Force install state file rewrite, so that it has mtime bigger than all node_modules subfolders
if (installChangedByUser)
await xfs.removePromise(installStatePath);
await xfs.changeFilePromise(installStatePath, locatorState, {
automaticNewlines: true,
});
}
async function findInstallState(project: Project, {unrollAliases = false}: {unrollAliases?: boolean} = {}): Promise<InstallState | null> {
const rootPath = project.cwd;
const installStatePath = ppath.join(rootPath, NODE_MODULES, INSTALL_STATE_FILE);
let stats;
try {
stats = await xfs.statPromise(installStatePath);
} catch (e) {
}
if (!stats)
return null;
const locatorState = parseSyml(await xfs.readFilePromise(installStatePath, `utf8`));
// If we have a higher serialized version than we can handle, ignore the state alltogether
if (locatorState.__metadata.version > STATE_FILE_VERSION)
return null;
const nmMode = locatorState.__metadata.nmMode || NodeModulesMode.CLASSIC;
const locatorMap: NodeModulesLocatorMap = new Map();
const binSymlinks: BinSymlinkMap = new Map();
delete locatorState.__metadata;
for (const [locatorStr, installRecord] of Object.entries(locatorState)) {
const locations = installRecord.locations.map((location: PortablePath) => {
return ppath.join(rootPath, location);
});
const recordSymlinks = installRecord.bin;
if (recordSymlinks) {
for (const [relativeLocation, locationSymlinks] of Object.entries(recordSymlinks)) {
const location = ppath.join(rootPath, npath.toPortablePath(relativeLocation));
const symlinks = miscUtils.getMapWithDefault(binSymlinks, location);
for (const [name, target] of Object.entries(locationSymlinks as any)) {
symlinks.set(toFilename(name), npath.toPortablePath([location, NODE_MODULES, target].join(ppath.sep)));
}
}
}
locatorMap.set(locatorStr, {
target: PortablePath.dot,
linkType: LinkType.HARD,
locations,
aliases: installRecord.aliases || [],
});
if (unrollAliases && installRecord.aliases) {
for (const reference of installRecord.aliases) {
const {scope, name} = structUtils.parseLocator(locatorStr);
const alias = structUtils.makeLocator(structUtils.makeIdent(scope, name), reference);
const aliasStr = structUtils.stringifyLocator(alias);
locatorMap.set(aliasStr, {
target: PortablePath.dot,
linkType: LinkType.HARD,
locations,
aliases: [],
});
}
}
}
return {locatorMap, binSymlinks, locationTree: buildLocationTree(locatorMap, {skipPrefix: project.cwd}), nmMode, mtimeMs: stats.mtimeMs};
}
const removeDir = async (dir: PortablePath, options: {contentsOnly: boolean, innerLoop?: boolean, allowSymlink?: boolean}): Promise<any> => {
if (dir.split(ppath.sep).indexOf(NODE_MODULES) < 0)
throw new Error(`Assertion failed: trying to remove dir that doesn't contain node_modules: ${dir}`);
try {
if (!options.innerLoop) {
const stats = options.allowSymlink ? await xfs.statPromise(dir) : await xfs.lstatPromise(dir);
if (options.allowSymlink && !stats.isDirectory() ||
(!options.allowSymlink && stats.isSymbolicLink())) {
await xfs.unlinkPromise(dir);
return;
}
}
const entries = await xfs.readdirPromise(dir, {withFileTypes: true});
for (const entry of entries) {
const targetPath = ppath.join(dir, toFilename(entry.name));
if (entry.isDirectory()) {
if (entry.name !== NODE_MODULES || (options && options.innerLoop)) {
await removeDir(targetPath, {innerLoop: true, contentsOnly: false});
}
} else {
await xfs.unlinkPromise(targetPath);
}
}
if (!options.contentsOnly) {
await xfs.rmdirPromise(dir);
}
} catch (e) {
if (e.code !== `ENOENT` && e.code !== `ENOTEMPTY`) {
throw e;
}
}
};
const CONCURRENT_OPERATION_LIMIT = 4;
type LocatorKey = string;
type LocationNode = { children: Map<Filename, LocationNode>, locator?: LocatorKey, linkType: LinkType };
type LocationRoot = PortablePath;
/**
* Locations tree. It starts with the map of location roots and continues as maps
* of nested directory entries.
*
* Example:
* Map {
* '' => children: Map {
* 'react-apollo' => {
* children: Map {
* 'node_modules' => {
* children: Map {
* '@apollo' => {
* children: Map {
* 'react-hooks' => {
* children: Map {},
* locator: '@apollo/react-hooks:virtual:cf...#npm:3.1.3'
* }
* }
* }
* }
* }
* },
* locator: 'react-apollo:virtual:24...#npm:3.1.3'
* },
* },
* 'packages/client' => children: Map {
* 'node_modules' => Map {
* ...
* }
* }
* ...
* }
*/
type LocationTree = Map<LocationRoot, LocationNode>;
const parseLocation = (location: PortablePath, {skipPrefix}: {skipPrefix: PortablePath}): {locationRoot: PortablePath, segments: Array<Filename>} => {
const projectRelativePath = ppath.contains(skipPrefix, location);
if (projectRelativePath === null)
throw new Error(`Assertion failed: Writing attempt prevented to ${location} which is outside project root: ${skipPrefix}`);
const allSegments = projectRelativePath
.split(ppath.sep)
// Ignore empty segments (after trailing slashes)
.filter(segment => segment !== ``);
const nmIndex = allSegments.indexOf(NODE_MODULES);
// Project path, up until the first node_modules segment
const relativeRoot = allSegments.slice(0, nmIndex).join(ppath.sep) as PortablePath;
const locationRoot = ppath.join(skipPrefix, relativeRoot);
// All segments that follow
const segments = allSegments.slice(nmIndex) as Array<Filename>;
return {locationRoot, segments};
};
const buildLocationTree = (locatorMap: NodeModulesLocatorMap | null, {skipPrefix}: {skipPrefix: PortablePath}): LocationTree => {
const locationTree: LocationTree = new Map();
if (locatorMap === null)
return locationTree;
const makeNode: () => LocationNode = () => ({
children: new Map(),
linkType: LinkType.HARD,
});
for (const [locator, info] of locatorMap.entries()) {
if (info.linkType === LinkType.SOFT) {
const internalPath = ppath.contains(skipPrefix, info.target);
if (internalPath !== null) {
const node = miscUtils.getFactoryWithDefault(locationTree, info.target, makeNode);
node.locator = locator;
node.linkType = info.linkType;
}
}
for (const location of info.locations) {
const {locationRoot, segments} = parseLocation(location, {skipPrefix});
let node = miscUtils.getFactoryWithDefault(locationTree, locationRoot, makeNode);
for (let idx = 0; idx < segments.length; ++idx) {
const segment = segments[idx];
// '.' segment exists only for top-level locator, skip it
if (segment !== `.`) {
const nextNode = miscUtils.getFactoryWithDefault(node.children, segment, makeNode);
node.children.set(segment, nextNode);
node = nextNode;
}
if (idx === segments.length - 1) {
node.locator = locator;
node.linkType = info.linkType;
}
}
}
}
return locationTree;
};
const symlinkPromise = async (srcPath: PortablePath, dstPath: PortablePath, windowsLinkType: WindowsLinkType) => {
// use junctions on windows if in classic mode
if (process.platform === `win32` && windowsLinkType === WindowsLinkType.JUNCTIONS) {
let stats;
try {
stats = await xfs.lstatPromise(srcPath);
} catch (e) {
}
if (!stats || stats.isDirectory()) {
await xfs.symlinkPromise(srcPath, dstPath, `junction`);
return;
}
// fall through to symlink
}
// use symlink if tests for junction case fail
await xfs.symlinkPromise(ppath.relative(ppath.dirname(dstPath), srcPath), dstPath);
};
async function atomicFileWrite(tmpDir: PortablePath, dstPath: PortablePath, content: Buffer) {
const tmpPath = ppath.join(tmpDir, toFilename(`${crypto.randomBytes(16).toString(`hex`)}.tmp`));
try {
await xfs.writeFilePromise(tmpPath, content);
try {
await xfs.linkPromise(tmpPath, dstPath);
} catch (e) {
}
} finally {
await xfs.unlinkPromise(tmpPath);
}
}
async function copyFilePromise({srcPath, dstPath, entry, globalHardlinksStore, baseFs, nmMode}: {srcPath: PortablePath, dstPath: PortablePath, entry: DirEntry, globalHardlinksStore: PortablePath | null, baseFs: FakeFS<PortablePath>, nmMode: {value: NodeModulesMode}}) {
if (entry.kind === DirEntryKind.FILE) {
if (nmMode.value === NodeModulesMode.HARDLINKS_GLOBAL && globalHardlinksStore && entry.digest) {
const contentFilePath = ppath.join(globalHardlinksStore, entry.digest.substring(0, 2) as Filename, `${entry.digest.substring(2)}.dat` as Filename);
let doesContentFileExist;
try {
const stats = await xfs.statPromise(contentFilePath);
if (stats && (!entry.mtimeMs || stats.mtimeMs > entry.mtimeMs || stats.mtimeMs < entry.mtimeMs - MTIME_ACCURANCY)) {
const contentDigest = await hashUtils.checksumFile(contentFilePath, {baseFs: xfs, algorithm: `sha1`});
if (contentDigest !== entry.digest) {
// If file content was modified by the user, or corrupted, we first move it out of the way
const tmpPath = ppath.join(globalHardlinksStore, toFilename(`${crypto.randomBytes(16).toString(`hex`)}.tmp`));
await xfs.renamePromise(contentFilePath, tmpPath);
// Then we overwrite the temporary file, thus restorting content of original file in all the linked projects
const content = await baseFs.readFilePromise(srcPath);
await xfs.writeFilePromise(tmpPath, content);
try {
// Then we try to move content file back on its place, if its still free
// If we fail here, it means that some other process or thread has created content file
// And this is okay, we will end up with two content files, but both with original content, unlucky files will have `.tmp` extension
await xfs.linkPromise(tmpPath, contentFilePath);
entry.mtimeMs = new Date().getTime();
await xfs.unlinkPromise(tmpPath);
} catch (e) {
}
} else if (!entry.mtimeMs) {
entry.mtimeMs = Math.ceil(stats.mtimeMs);
}
}
await xfs.linkPromise(contentFilePath, dstPath);
doesContentFileExist = true;
} catch (e) {
doesContentFileExist = false;
}
if (!doesContentFileExist) {
const content = await baseFs.readFilePromise(srcPath);
await atomicFileWrite(globalHardlinksStore, contentFilePath, content);
entry.mtimeMs = new Date().getTime();
try {
await xfs.linkPromise(contentFilePath, dstPath);
} catch (e) {
if (e && e.code && e.code == `EXDEV`) {
nmMode.value = NodeModulesMode.HARDLINKS_LOCAL;
await baseFs.copyFilePromise(srcPath, dstPath);
}
}
}
} else {
await baseFs.copyFilePromise(srcPath, dstPath);
}
const mode = entry.mode & 0o777;
// An optimization - files will have rw-r-r permissions (0o644) by default, we can skip chmod for them
if (mode !== 0o644) {
await xfs.chmodPromise(dstPath, mode);
}
}
}
enum DirEntryKind {
FILE = `file`, DIRECTORY = `directory`, SYMLINK = `symlink`,
}
type DirEntry = {
kind: DirEntryKind.FILE;
mode: number;
digest?: string;
mtimeMs?: number;
} | {
kind: DirEntryKind. DIRECTORY;
} | {
kind: DirEntryKind.SYMLINK;
symlinkTo: PortablePath;
};
const copyPromise = async (dstDir: PortablePath, srcDir: PortablePath, {baseFs, globalHardlinksStore, nmMode, windowsLinkType: windowsLinkType, packageChecksum}: {baseFs: FakeFS<PortablePath>, globalHardlinksStore: PortablePath | null, nmMode: {value: NodeModulesMode}, windowsLinkType: WindowsLinkType, packageChecksum: string | null}) => {
await xfs.mkdirPromise(dstDir, {recursive: true});
const getEntriesRecursive = async (relativePath: PortablePath = PortablePath.dot): Promise<Map<PortablePath, DirEntry>> => {
const srcPath = ppath.join(srcDir, relativePath);
const entries = await baseFs.readdirPromise(srcPath, {withFileTypes: true});
const entryMap = new Map();
for (const entry of entries) {
const relativeEntryPath = ppath.join(relativePath, entry.name);
let entryValue: DirEntry;
const srcEntryPath = ppath.join(srcPath, entry.name);
if (entry.isFile()) {
entryValue = {kind: DirEntryKind.FILE, mode: (await baseFs.lstatPromise(srcEntryPath)).mode};
if (nmMode.value === NodeModulesMode.HARDLINKS_GLOBAL) {
const digest = await hashUtils.checksumFile(srcEntryPath, {baseFs, algorithm: `sha1`});
entryValue.digest = digest;
}
} else if (entry.isDirectory()) {
entryValue = {kind: DirEntryKind.DIRECTORY};
} else if (entry.isSymbolicLink()) {
entryValue = {kind: DirEntryKind.SYMLINK, symlinkTo: await baseFs.readlinkPromise(srcEntryPath)};
} else {
throw new Error(`Unsupported file type (file: ${srcEntryPath}, mode: 0o${await baseFs.statSync(srcEntryPath).mode.toString(8).padStart(6, `0`)})`);
}
entryMap.set(relativeEntryPath, entryValue);
if (entry.isDirectory() && relativeEntryPath !== NODE_MODULES) {
const childEntries = await getEntriesRecursive(relativeEntryPath);
for (const [childRelativePath, childEntry] of childEntries) {
entryMap.set(childRelativePath, childEntry);
}
}
}
return entryMap;
};
let allEntries: Map<PortablePath, DirEntry>;
if (nmMode.value === NodeModulesMode.HARDLINKS_GLOBAL && globalHardlinksStore && packageChecksum) {
const entriesJsonPath = ppath.join(globalHardlinksStore, packageChecksum.substring(0, 2) as Filename, `${packageChecksum.substring(2)}.json` as Filename);
try {
allEntries = new Map(Object.entries(JSON.parse(await xfs.readFilePromise(entriesJsonPath, `utf8`)))) as Map<PortablePath, DirEntry>;
} catch (e) {
allEntries = await getEntriesRecursive();
}
} else {
allEntries = await getEntriesRecursive();
}
let mtimesChanged = false;
for (const [relativePath, entry] of allEntries) {
const srcPath = ppath.join(srcDir, relativePath);
const dstPath = ppath.join(dstDir, relativePath);
if (entry.kind === DirEntryKind.DIRECTORY) {
await xfs.mkdirPromise(dstPath, {recursive: true});
} else if (entry.kind === DirEntryKind.FILE) {
const originalMtime = entry.mtimeMs;
await copyFilePromise({srcPath, dstPath, entry, nmMode, baseFs, globalHardlinksStore});
if (entry.mtimeMs !== originalMtime) {
mtimesChanged = true;
}
} else if (entry.kind === DirEntryKind.SYMLINK) {
await symlinkPromise(ppath.resolve(ppath.dirname(dstPath), entry.symlinkTo), dstPath, windowsLinkType);
}
}
if (nmMode.value === NodeModulesMode.HARDLINKS_GLOBAL && globalHardlinksStore && mtimesChanged && packageChecksum) {
const entriesJsonPath = ppath.join(globalHardlinksStore, packageChecksum.substring(0, 2) as Filename, `${packageChecksum.substring(2)}.json` as Filename);
await xfs.removePromise(entriesJsonPath);
await atomicFileWrite(globalHardlinksStore, entriesJsonPath, Buffer.from(JSON.stringify(Object.fromEntries(allEntries))));
}
};
/**
* Synchronizes previous install state with the actual directories available on disk
*
* @param locationTree location tree
* @param binSymlinks bin symlinks map
* @param stateMtimeMs state file timestamp (this file is written after all node_modules files and directories)
*
* @returns location tree and bin symlinks with modules, unavailable on disk, removed
*/
function syncPreinstallStateWithDisk(locationTree: LocationTree, binSymlinks: BinSymlinkMap, stateMtimeMs: number, project: Project): {locationTree: LocationTree, binSymlinks: BinSymlinkMap, locatorLocations: Map<LocatorKey, Set<PortablePath>>, installChangedByUser: boolean} {
const refinedLocationTree: LocationTree = new Map();
const refinedBinSymlinks = new Map();
const locatorLocations = new Map();
let installChangedByUser = false;
const syncNodeWithDisk = (parentPath: PortablePath, entry: Filename, parentNode: LocationNode, refinedNode: LocationNode, parentDiskEntries: Set<Filename>) => {
let doesExistOnDisk = true;
const entryPath = ppath.join(parentPath, entry);
let childDiskEntries = new Set<Filename>();
if (entry === NODE_MODULES || entry.startsWith(`@`)) {
let stats;
try {
stats = xfs.statSync(entryPath);
} catch (e) {
}
doesExistOnDisk = !!stats;
if (!stats) {
installChangedByUser = true;
} else if (stats.mtimeMs > stateMtimeMs) {
installChangedByUser = true;
childDiskEntries = new Set(xfs.readdirSync(entryPath));
} else {
childDiskEntries = new Set(parentNode.children.get(entry)!.children.keys());
}
const binarySymlinks = binSymlinks.get(parentPath);
if (binarySymlinks) {
const binPath = ppath.join(parentPath, NODE_MODULES, DOT_BIN);
let binStats;
try {
binStats = xfs.statSync(binPath);
} catch (e) {
}
if (!binStats) {
installChangedByUser = true;
} else if (binStats.mtimeMs > stateMtimeMs) {
installChangedByUser = true;
const diskEntries = new Set(xfs.readdirSync(binPath));
const refinedBinarySymlinks = new Map();
refinedBinSymlinks.set(parentPath, refinedBinarySymlinks);
for (const [entry, target] of binarySymlinks) {
if (diskEntries.has(entry)) {
refinedBinarySymlinks.set(entry, target);
}
}
} else {
refinedBinSymlinks.set(parentPath, binarySymlinks);
}
}
} else {
doesExistOnDisk = parentDiskEntries.has(entry);
}
const node = parentNode.children.get(entry)!;
if (doesExistOnDisk) {
const {linkType, locator} = node;
const childRefinedNode = {children: new Map(), linkType, locator};
refinedNode.children.set(entry, childRefinedNode);
if (locator) {
const locations = miscUtils.getSetWithDefault(locatorLocations, locator);
locations.add(entryPath);
locatorLocations.set(locator, locations);
}
for (const childEntry of node.children.keys()) {
syncNodeWithDisk(entryPath, childEntry, node, childRefinedNode, childDiskEntries);
}
} else if (node.locator) {
project.storedBuildState.delete(structUtils.parseLocator(node.locator).locatorHash);
}
};
for (const [workspaceRoot, node] of locationTree) {
const {linkType, locator} = node;
const refinedNode = {children: new Map(), linkType, locator};
refinedLocationTree.set(workspaceRoot, refinedNode);
if (locator) {
const locations = miscUtils.getSetWithDefault(locatorLocations, node.locator);
locations.add(workspaceRoot);
locatorLocations.set(node.locator, locations);
}
if (node.children.has(NODE_MODULES)) {
syncNodeWithDisk(workspaceRoot, NODE_MODULES, node, refinedNode, new Set());
}
}
return {locationTree: refinedLocationTree, binSymlinks: refinedBinSymlinks, locatorLocations, installChangedByUser};
}
function isLinkLocator(locatorKey: LocatorKey): boolean {
let descriptor = structUtils.parseDescriptor(locatorKey);
if (structUtils.isVirtualDescriptor(descriptor))
descriptor = structUtils.devirtualizeDescriptor(descriptor);
return descriptor.range.startsWith(`link:`);
}
async function createBinSymlinkMap(installState: NodeModulesLocatorMap, locationTree: LocationTree, projectRoot: PortablePath, {loadManifest}: {loadManifest: LoadManifest}) {
const locatorScriptMap = new Map<LocatorKey, Map<string, string>>();
for (const [locatorKey, {locations}] of installState) {
const manifest = !isLinkLocator(locatorKey)
? await loadManifest(locatorKey, locations[0])
: null;
const bin = new Map();
if (manifest) {
for (const [name, value] of manifest.bin) {
const target = ppath.join(locations[0], value);
if (value !== `` && xfs.existsSync(target)) {
bin.set(name, value);
}
}
}
locatorScriptMap.set(locatorKey, bin);
}
const binSymlinks: BinSymlinkMap = new Map();
const getBinSymlinks = (location: PortablePath, parentLocatorLocation: PortablePath, node: LocationNode): Map<Filename, PortablePath> => {
const symlinks = new Map();
const internalPath = ppath.contains(projectRoot, location);
if (node.locator && internalPath !== null) {
const binScripts = locatorScriptMap.get(node.locator)!;
for (const [filename, scriptPath] of binScripts) {
const symlinkTarget = ppath.join(location, npath.toPortablePath(scriptPath));
symlinks.set(toFilename(filename), symlinkTarget);