@yarnpkg/nm 3.0.1-rc.8 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/hoist.js DELETED
@@ -1,829 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hoist = void 0;
4
- var Hoistable;
5
- (function (Hoistable) {
6
- Hoistable[Hoistable["YES"] = 0] = "YES";
7
- Hoistable[Hoistable["NO"] = 1] = "NO";
8
- Hoistable[Hoistable["DEPENDS"] = 2] = "DEPENDS";
9
- })(Hoistable || (Hoistable = {}));
10
- const makeLocator = (name, reference) => `${name}@${reference}`;
11
- const makeIdent = (name, reference) => {
12
- const hashIdx = reference.indexOf(`#`);
13
- // Strip virtual reference part, we don't need it for hoisting purposes
14
- const realReference = hashIdx >= 0 ? reference.substring(hashIdx + 1) : reference;
15
- return makeLocator(name, realReference);
16
- };
17
- var DebugLevel;
18
- (function (DebugLevel) {
19
- DebugLevel[DebugLevel["NONE"] = -1] = "NONE";
20
- DebugLevel[DebugLevel["PERF"] = 0] = "PERF";
21
- DebugLevel[DebugLevel["CHECK"] = 1] = "CHECK";
22
- DebugLevel[DebugLevel["REASONS"] = 2] = "REASONS";
23
- DebugLevel[DebugLevel["INTENSIVE_CHECK"] = 9] = "INTENSIVE_CHECK";
24
- })(DebugLevel || (DebugLevel = {}));
25
- /**
26
- * Hoists package tree.
27
- *
28
- * The root node of a tree must has id: '.'.
29
- * This function does not mutate its arguments, it hoists and returns tree copy.
30
- *
31
- * @param tree package tree (cycles in the tree are allowed)
32
- *
33
- * @returns hoisted tree copy
34
- */
35
- const hoist = (tree, opts = {}) => {
36
- const debugLevel = opts.debugLevel || Number(process.env.NM_DEBUG_LEVEL || DebugLevel.NONE);
37
- const check = opts.check || debugLevel >= DebugLevel.INTENSIVE_CHECK;
38
- const hoistingLimits = opts.hoistingLimits || new Map();
39
- const options = { check, debugLevel, hoistingLimits, fastLookupPossible: true };
40
- let startTime;
41
- if (options.debugLevel >= DebugLevel.PERF)
42
- startTime = Date.now();
43
- const treeCopy = cloneTree(tree, options);
44
- let anotherRoundNeeded = false;
45
- let round = 0;
46
- do {
47
- anotherRoundNeeded = hoistTo(treeCopy, [treeCopy], new Set([treeCopy.locator]), new Map(), options).anotherRoundNeeded;
48
- options.fastLookupPossible = false;
49
- round++;
50
- } while (anotherRoundNeeded);
51
- if (options.debugLevel >= DebugLevel.PERF)
52
- console.log(`hoist time: ${Date.now() - startTime}ms, rounds: ${round}`);
53
- if (options.debugLevel >= DebugLevel.CHECK) {
54
- const prevTreeDump = dumpDepTree(treeCopy);
55
- const isGraphChanged = hoistTo(treeCopy, [treeCopy], new Set([treeCopy.locator]), new Map(), options).isGraphChanged;
56
- if (isGraphChanged)
57
- throw new Error(`The hoisting result is not terminal, prev tree:\n${prevTreeDump}, next tree:\n${dumpDepTree(treeCopy)}`);
58
- const checkLog = selfCheck(treeCopy);
59
- if (checkLog) {
60
- throw new Error(`${checkLog}, after hoisting finished:\n${dumpDepTree(treeCopy)}`);
61
- }
62
- }
63
- if (options.debugLevel >= DebugLevel.REASONS)
64
- console.log(dumpDepTree(treeCopy));
65
- return shrinkTree(treeCopy);
66
- };
67
- exports.hoist = hoist;
68
- const getZeroRoundUsedDependencies = (rootNodePath) => {
69
- const rootNode = rootNodePath[rootNodePath.length - 1];
70
- const usedDependencies = new Map();
71
- const seenNodes = new Set();
72
- const addUsedDependencies = (node) => {
73
- if (seenNodes.has(node))
74
- return;
75
- seenNodes.add(node);
76
- for (const dep of node.hoistedDependencies.values())
77
- usedDependencies.set(dep.name, dep);
78
- for (const dep of node.dependencies.values()) {
79
- if (!node.peerNames.has(dep.name)) {
80
- addUsedDependencies(dep);
81
- }
82
- }
83
- };
84
- addUsedDependencies(rootNode);
85
- return usedDependencies;
86
- };
87
- const getUsedDependencies = (rootNodePath) => {
88
- const rootNode = rootNodePath[rootNodePath.length - 1];
89
- const usedDependencies = new Map();
90
- const seenNodes = new Set();
91
- const hiddenDependencies = new Set();
92
- const addUsedDependencies = (node, hiddenDependencies) => {
93
- if (seenNodes.has(node))
94
- return;
95
- seenNodes.add(node);
96
- for (const dep of node.hoistedDependencies.values()) {
97
- if (!hiddenDependencies.has(dep.name)) {
98
- let reachableDependency;
99
- for (const node of rootNodePath) {
100
- reachableDependency = node.dependencies.get(dep.name);
101
- if (reachableDependency) {
102
- usedDependencies.set(reachableDependency.name, reachableDependency);
103
- }
104
- }
105
- }
106
- }
107
- const childrenHiddenDependencies = new Set();
108
- for (const dep of node.dependencies.values())
109
- childrenHiddenDependencies.add(dep.name);
110
- for (const dep of node.dependencies.values()) {
111
- if (!node.peerNames.has(dep.name)) {
112
- addUsedDependencies(dep, childrenHiddenDependencies);
113
- }
114
- }
115
- };
116
- addUsedDependencies(rootNode, hiddenDependencies);
117
- return usedDependencies;
118
- };
119
- /**
120
- * This method clones the node and returns cloned node copy, if the node was not previously decoupled.
121
- *
122
- * The node is considered decoupled if there is no multiple parents to any node
123
- * on the path from the dependency graph root up to this node. This means that there are no other
124
- * nodes in dependency graph that somehow transitively use this node and hence node can be hoisted without
125
- * side effects.
126
- *
127
- * The process of node decoupling is done by going from root node of the graph up to the node in concern
128
- * and decoupling each node on this graph path.
129
- *
130
- * @param node original node
131
- *
132
- * @returns decoupled node
133
- */
134
- const decoupleGraphNode = (parent, node) => {
135
- if (node.decoupled)
136
- return node;
137
- const { name, references, ident, locator, dependencies, originalDependencies, hoistedDependencies, peerNames, reasons, isHoistBorder, hoistPriority, isWorkspace, hoistedFrom, hoistedTo } = node;
138
- // To perform node hoisting from parent node we must clone parent nodes up to the root node,
139
- // because some other package in the tree might depend on the parent package where hoisting
140
- // cannot be performed
141
- const clone = {
142
- name,
143
- references: new Set(references),
144
- ident,
145
- locator,
146
- dependencies: new Map(dependencies),
147
- originalDependencies: new Map(originalDependencies),
148
- hoistedDependencies: new Map(hoistedDependencies),
149
- peerNames: new Set(peerNames),
150
- reasons: new Map(reasons),
151
- decoupled: true,
152
- isHoistBorder,
153
- hoistPriority,
154
- isWorkspace,
155
- hoistedFrom: new Map(hoistedFrom),
156
- hoistedTo: new Map(hoistedTo),
157
- };
158
- const selfDep = clone.dependencies.get(name);
159
- if (selfDep && selfDep.ident == clone.ident)
160
- // Update self-reference
161
- clone.dependencies.set(name, clone);
162
- parent.dependencies.set(clone.name, clone);
163
- return clone;
164
- };
165
- /**
166
- * Builds a map of most preferred packages that might be hoisted to the root node.
167
- *
168
- * The values in the map are idents sorted by preference from most preferred to less preferred.
169
- * If the root node has already some version of a package, the value array will contain only
170
- * one element, since it is not possible for other versions of a package to be hoisted.
171
- *
172
- * @param rootNode root node
173
- * @param preferenceMap preference map
174
- */
175
- const getHoistIdentMap = (rootNode, preferenceMap) => {
176
- const identMap = new Map([[rootNode.name, [rootNode.ident]]]);
177
- for (const dep of rootNode.dependencies.values()) {
178
- if (!rootNode.peerNames.has(dep.name)) {
179
- identMap.set(dep.name, [dep.ident]);
180
- }
181
- }
182
- const keyList = Array.from(preferenceMap.keys());
183
- keyList.sort((key1, key2) => {
184
- const entry1 = preferenceMap.get(key1);
185
- const entry2 = preferenceMap.get(key2);
186
- if (entry2.hoistPriority !== entry1.hoistPriority) {
187
- return entry2.hoistPriority - entry1.hoistPriority;
188
- }
189
- else if (entry2.peerDependents.size !== entry1.peerDependents.size) {
190
- return entry2.peerDependents.size - entry1.peerDependents.size;
191
- }
192
- else {
193
- return entry2.dependents.size - entry1.dependents.size;
194
- }
195
- });
196
- for (const key of keyList) {
197
- const name = key.substring(0, key.indexOf(`@`, 1));
198
- const ident = key.substring(name.length + 1);
199
- if (!rootNode.peerNames.has(name)) {
200
- let idents = identMap.get(name);
201
- if (!idents) {
202
- idents = [];
203
- identMap.set(name, idents);
204
- }
205
- if (idents.indexOf(ident) < 0) {
206
- idents.push(ident);
207
- }
208
- }
209
- }
210
- return identMap;
211
- };
212
- /**
213
- * Gets regular node dependencies only and sorts them in the order so that
214
- * peer dependencies come before the dependency that rely on them.
215
- *
216
- * @param node graph node
217
- * @returns sorted regular dependencies
218
- */
219
- const getSortedRegularDependencies = (node) => {
220
- const dependencies = new Set();
221
- const addDep = (dep, seenDeps = new Set()) => {
222
- if (seenDeps.has(dep))
223
- return;
224
- seenDeps.add(dep);
225
- for (const peerName of dep.peerNames) {
226
- if (!node.peerNames.has(peerName)) {
227
- const peerDep = node.dependencies.get(peerName);
228
- if (peerDep && !dependencies.has(peerDep)) {
229
- addDep(peerDep, seenDeps);
230
- }
231
- }
232
- }
233
- dependencies.add(dep);
234
- };
235
- for (const dep of node.dependencies.values()) {
236
- if (!node.peerNames.has(dep.name)) {
237
- addDep(dep);
238
- }
239
- }
240
- return dependencies;
241
- };
242
- /**
243
- * Performs hoisting all the dependencies down the tree to the root node.
244
- *
245
- * The algorithm used here reduces dependency graph by deduplicating
246
- * instances of the packages while keeping:
247
- * 1. Regular dependency promise: the package should require the exact version of the dependency
248
- * that was declared in its `package.json`
249
- * 2. Peer dependency promise: the package and its direct parent package
250
- * must use the same instance of the peer dependency
251
- *
252
- * The regular and peer dependency promises are kept while performing transform
253
- * on tree branches of packages at a time:
254
- * `root package` -> `parent package 1` ... `parent package n` -> `dependency`
255
- * We check wether we can hoist `dependency` to `root package`, this boils down basically
256
- * to checking:
257
- * 1. Wether `root package` does not depend on other version of `dependency`
258
- * 2. Wether all the peer dependencies of a `dependency` had already been hoisted from all `parent packages`
259
- *
260
- * If many versions of the `dependency` can be hoisted to the `root package` we choose the most used
261
- * `dependency` version in the project among them.
262
- *
263
- * This function mutates the tree.
264
- *
265
- * @param tree package dependencies graph
266
- * @param rootNode root node to hoist to
267
- * @param rootNodePath root node path in the tree
268
- * @param rootNodePathLocators a set of locators for nodes that lead from the top of the tree up to root node
269
- * @param options hoisting options
270
- */
271
- const hoistTo = (tree, rootNodePath, rootNodePathLocators, parentShadowedNodes, options, seenNodes = new Set()) => {
272
- const rootNode = rootNodePath[rootNodePath.length - 1];
273
- if (seenNodes.has(rootNode))
274
- return { anotherRoundNeeded: false, isGraphChanged: false };
275
- seenNodes.add(rootNode);
276
- const preferenceMap = buildPreferenceMap(rootNode);
277
- const hoistIdentMap = getHoistIdentMap(rootNode, preferenceMap);
278
- const usedDependencies = tree == rootNode ? new Map() : (options.fastLookupPossible ? getZeroRoundUsedDependencies(rootNodePath) : getUsedDependencies(rootNodePath));
279
- let wasStateChanged;
280
- let anotherRoundNeeded = false;
281
- let isGraphChanged = false;
282
- const hoistIdents = new Map(Array.from(hoistIdentMap.entries()).map(([k, v]) => [k, v[0]]));
283
- const shadowedNodes = new Map();
284
- do {
285
- const result = hoistGraph(tree, rootNodePath, rootNodePathLocators, usedDependencies, hoistIdents, hoistIdentMap, parentShadowedNodes, shadowedNodes, options);
286
- if (result.isGraphChanged)
287
- isGraphChanged = true;
288
- if (result.anotherRoundNeeded)
289
- anotherRoundNeeded = true;
290
- wasStateChanged = false;
291
- for (const [name, idents] of hoistIdentMap) {
292
- if (idents.length > 1 && !rootNode.dependencies.has(name)) {
293
- hoistIdents.delete(name);
294
- idents.shift();
295
- hoistIdents.set(name, idents[0]);
296
- wasStateChanged = true;
297
- }
298
- }
299
- } while (wasStateChanged);
300
- for (const dependency of rootNode.dependencies.values()) {
301
- if (!rootNode.peerNames.has(dependency.name) && !rootNodePathLocators.has(dependency.locator)) {
302
- rootNodePathLocators.add(dependency.locator);
303
- const result = hoistTo(tree, [...rootNodePath, dependency], rootNodePathLocators, shadowedNodes, options);
304
- if (result.isGraphChanged)
305
- isGraphChanged = true;
306
- if (result.anotherRoundNeeded)
307
- anotherRoundNeeded = true;
308
- rootNodePathLocators.delete(dependency.locator);
309
- }
310
- }
311
- return { anotherRoundNeeded, isGraphChanged };
312
- };
313
- const getNodeHoistInfo = (rootNode, rootNodePathLocators, nodePath, node, usedDependencies, hoistIdents, hoistIdentMap, shadowedNodes, { outputReason, fastLookupPossible }) => {
314
- let reasonRoot;
315
- let reason = null;
316
- let dependsOn = new Set();
317
- if (outputReason)
318
- reasonRoot = `${Array.from(rootNodePathLocators).map(x => prettyPrintLocator(x)).join(`→`)}`;
319
- const parentNode = nodePath[nodePath.length - 1];
320
- // We cannot hoist self-references
321
- const isSelfReference = node.ident === parentNode.ident;
322
- let isHoistable = !isSelfReference;
323
- if (outputReason && !isHoistable)
324
- reason = `- self-reference`;
325
- if (isHoistable) {
326
- isHoistable = !node.isWorkspace;
327
- if (outputReason && !isHoistable) {
328
- reason = `- workspace`;
329
- }
330
- }
331
- if (isHoistable) {
332
- // Direct workspace dependencies must be hoisted to any common ancestor workspace of all the
333
- // graph paths that include the dependency, because otherwise running app with
334
- // `--preserve-symlinks` will become broken (without this flag the Node.js will pick dependency
335
- // from the ancestor on the file system and with this flag it will pick ancestor from the graph
336
- // and if these ancestors are different, the behavious of the application will be different).
337
- // Another problem, which is prevented - is a creation of multiple hoisting layouts
338
- // for the same workspace, because different dependencies of the same workspace might be hoisted
339
- // differently, depending on the recepient workspace.
340
- // It is difficult to find all common ancestors, but there is one easy to find common ancestor -
341
- // the root workspace, so, for now, we either hoist direct dependencies into the root workspace, or we keep them
342
- // unhoisted, thus we are safe from various pathological cases with `--preserve-symlinks`
343
- isHoistable = !parentNode.isWorkspace || parentNode.hoistedFrom.has(node.name) || rootNodePathLocators.size === 1;
344
- if (outputReason && !isHoistable) {
345
- reason = parentNode.reasons.get(node.name);
346
- }
347
- }
348
- if (isHoistable) {
349
- isHoistable = !rootNode.peerNames.has(node.name);
350
- if (outputReason && !isHoistable) {
351
- reason = `- cannot shadow peer: ${prettyPrintLocator(rootNode.originalDependencies.get(node.name).locator)} at ${reasonRoot}`;
352
- }
353
- }
354
- if (isHoistable) {
355
- let isNameAvailable = false;
356
- const usedDep = usedDependencies.get(node.name);
357
- isNameAvailable = (!usedDep || usedDep.ident === node.ident);
358
- if (outputReason && !isNameAvailable)
359
- reason = `- filled by: ${prettyPrintLocator(usedDep.locator)} at ${reasonRoot}`;
360
- if (isNameAvailable) {
361
- for (let idx = nodePath.length - 1; idx >= 1; idx--) {
362
- const parent = nodePath[idx];
363
- const parentDep = parent.dependencies.get(node.name);
364
- if (parentDep && parentDep.ident !== node.ident) {
365
- isNameAvailable = false;
366
- let shadowedNames = shadowedNodes.get(parentNode);
367
- if (!shadowedNames) {
368
- shadowedNames = new Set();
369
- shadowedNodes.set(parentNode, shadowedNames);
370
- }
371
- shadowedNames.add(node.name);
372
- if (outputReason)
373
- reason = `- filled by ${prettyPrintLocator(parentDep.locator)} at ${nodePath.slice(0, idx).map(x => prettyPrintLocator(x.locator)).join(`→`)}`;
374
- break;
375
- }
376
- }
377
- }
378
- isHoistable = isNameAvailable;
379
- }
380
- if (isHoistable) {
381
- const hoistedIdent = hoistIdents.get(node.name);
382
- isHoistable = hoistedIdent === node.ident;
383
- if (outputReason && !isHoistable) {
384
- reason = `- filled by: ${prettyPrintLocator(hoistIdentMap.get(node.name)[0])} at ${reasonRoot}`;
385
- }
386
- }
387
- if (isHoistable) {
388
- let arePeerDepsSatisfied = true;
389
- const checkList = new Set(node.peerNames);
390
- for (let idx = nodePath.length - 1; idx >= 1; idx--) {
391
- const parent = nodePath[idx];
392
- for (const name of checkList) {
393
- if (parent.peerNames.has(name) && parent.originalDependencies.has(name))
394
- continue;
395
- const parentDepNode = parent.dependencies.get(name);
396
- if (parentDepNode && rootNode.dependencies.get(name) !== parentDepNode) {
397
- if (idx === nodePath.length - 1) {
398
- dependsOn.add(parentDepNode);
399
- }
400
- else {
401
- dependsOn = null;
402
- arePeerDepsSatisfied = false;
403
- if (outputReason) {
404
- reason = `- peer dependency ${prettyPrintLocator(parentDepNode.locator)} from parent ${prettyPrintLocator(parent.locator)} was not hoisted to ${reasonRoot}`;
405
- }
406
- }
407
- }
408
- checkList.delete(name);
409
- }
410
- if (!arePeerDepsSatisfied) {
411
- break;
412
- }
413
- }
414
- isHoistable = arePeerDepsSatisfied;
415
- }
416
- if (isHoistable && !fastLookupPossible) {
417
- for (const origDep of node.hoistedDependencies.values()) {
418
- const usedDep = usedDependencies.get(origDep.name);
419
- if (!usedDep || origDep.ident !== usedDep.ident) {
420
- isHoistable = false;
421
- if (outputReason)
422
- reason = `- previously hoisted dependency mismatch, needed: ${prettyPrintLocator(origDep.locator)}, available: ${prettyPrintLocator(usedDep === null || usedDep === void 0 ? void 0 : usedDep.locator)}`;
423
- break;
424
- }
425
- }
426
- }
427
- if (dependsOn !== null && dependsOn.size > 0) {
428
- return { isHoistable: Hoistable.DEPENDS, dependsOn, reason };
429
- }
430
- else {
431
- return { isHoistable: isHoistable ? Hoistable.YES : Hoistable.NO, reason };
432
- }
433
- };
434
- /**
435
- * Performs actual graph transformation, by hoisting packages to the root node.
436
- *
437
- * @param tree dependency tree
438
- * @param rootNodePath root node path in the tree
439
- * @param rootNodePathLocators a set of locators for nodes that lead from the top of the tree up to root node
440
- * @param usedDependencies map of dependency nodes from parents of root node used by root node and its children via parent lookup
441
- * @param hoistIdents idents that should be attempted to be hoisted to the root node
442
- */
443
- const hoistGraph = (tree, rootNodePath, rootNodePathLocators, usedDependencies, hoistIdents, hoistIdentMap, parentShadowedNodes, shadowedNodes, options) => {
444
- const rootNode = rootNodePath[rootNodePath.length - 1];
445
- const seenNodes = new Set();
446
- let anotherRoundNeeded = false;
447
- let isGraphChanged = false;
448
- const hoistNodeDependencies = (nodePath, locatorPath, parentNode, newNodes) => {
449
- if (seenNodes.has(parentNode))
450
- return;
451
- const nextLocatorPath = [...locatorPath, parentNode.locator];
452
- const dependantTree = new Map();
453
- const hoistInfos = new Map();
454
- for (const subDependency of getSortedRegularDependencies(parentNode)) {
455
- const hoistInfo = getNodeHoistInfo(rootNode, rootNodePathLocators, [rootNode, ...nodePath, parentNode], subDependency, usedDependencies, hoistIdents, hoistIdentMap, shadowedNodes, { outputReason: options.debugLevel >= DebugLevel.REASONS, fastLookupPossible: options.fastLookupPossible });
456
- hoistInfos.set(subDependency, hoistInfo);
457
- if (hoistInfo.isHoistable === Hoistable.DEPENDS) {
458
- for (const node of hoistInfo.dependsOn) {
459
- const nodeDependants = dependantTree.get(node.name) || new Set();
460
- nodeDependants.add(subDependency.name);
461
- dependantTree.set(node.name, nodeDependants);
462
- }
463
- }
464
- }
465
- const unhoistableNodes = new Set();
466
- const addUnhoistableNode = (node, hoistInfo, reason) => {
467
- if (!unhoistableNodes.has(node)) {
468
- unhoistableNodes.add(node);
469
- hoistInfos.set(node, { isHoistable: Hoistable.NO, reason });
470
- for (const dependantName of dependantTree.get(node.name) || []) {
471
- addUnhoistableNode(parentNode.dependencies.get(dependantName), hoistInfo, options.debugLevel >= DebugLevel.REASONS ? `- peer dependency ${prettyPrintLocator(node.locator)} from parent ${prettyPrintLocator(parentNode.locator)} was not hoisted` : ``);
472
- }
473
- }
474
- };
475
- for (const [node, hoistInfo] of hoistInfos)
476
- if (hoistInfo.isHoistable === Hoistable.NO)
477
- addUnhoistableNode(node, hoistInfo, hoistInfo.reason);
478
- for (const node of hoistInfos.keys()) {
479
- if (!unhoistableNodes.has(node)) {
480
- isGraphChanged = true;
481
- const shadowedNames = parentShadowedNodes.get(parentNode);
482
- if (shadowedNames && shadowedNames.has(node.name))
483
- anotherRoundNeeded = true;
484
- parentNode.dependencies.delete(node.name);
485
- parentNode.hoistedDependencies.set(node.name, node);
486
- parentNode.reasons.delete(node.name);
487
- const hoistedNode = rootNode.dependencies.get(node.name);
488
- if (options.debugLevel >= DebugLevel.REASONS) {
489
- const hoistedFrom = Array.from(locatorPath).concat([parentNode.locator]).map(x => prettyPrintLocator(x)).join(`→`);
490
- let hoistedFromArray = rootNode.hoistedFrom.get(node.name);
491
- if (!hoistedFromArray) {
492
- hoistedFromArray = [];
493
- rootNode.hoistedFrom.set(node.name, hoistedFromArray);
494
- }
495
- hoistedFromArray.push(hoistedFrom);
496
- parentNode.hoistedTo.set(node.name, Array.from(rootNodePath).map(x => prettyPrintLocator(x.locator)).join(`→`));
497
- }
498
- // Add hoisted node to root node, in case it is not already there
499
- if (!hoistedNode) {
500
- // Avoid adding other version of root node to itself
501
- if (rootNode.ident !== node.ident) {
502
- rootNode.dependencies.set(node.name, node);
503
- newNodes.add(node);
504
- }
505
- }
506
- else {
507
- for (const reference of node.references) {
508
- hoistedNode.references.add(reference);
509
- }
510
- }
511
- }
512
- }
513
- if (options.check) {
514
- const checkLog = selfCheck(tree);
515
- if (checkLog) {
516
- throw new Error(`${checkLog}, after hoisting dependencies of ${[rootNode, ...nodePath, parentNode].map(x => prettyPrintLocator(x.locator)).join(`→`)}:\n${dumpDepTree(tree)}`);
517
- }
518
- }
519
- const children = getSortedRegularDependencies(parentNode);
520
- for (const node of children) {
521
- if (unhoistableNodes.has(node)) {
522
- const hoistInfo = hoistInfos.get(node);
523
- const hoistableIdent = hoistIdents.get(node.name);
524
- if ((hoistableIdent === node.ident || !parentNode.reasons.has(node.name)) && hoistInfo.isHoistable !== Hoistable.YES)
525
- parentNode.reasons.set(node.name, hoistInfo.reason);
526
- if (!node.isHoistBorder && nextLocatorPath.indexOf(node.locator) < 0) {
527
- seenNodes.add(parentNode);
528
- const decoupledNode = decoupleGraphNode(parentNode, node);
529
- hoistNodeDependencies([...nodePath, parentNode], [...locatorPath, parentNode.locator], decoupledNode, nextNewNodes);
530
- seenNodes.delete(parentNode);
531
- }
532
- }
533
- }
534
- };
535
- let newNodes;
536
- let nextNewNodes = new Set(getSortedRegularDependencies(rootNode));
537
- do {
538
- newNodes = nextNewNodes;
539
- nextNewNodes = new Set();
540
- for (const dep of newNodes) {
541
- if (dep.locator === rootNode.locator || dep.isHoistBorder)
542
- continue;
543
- const decoupledDependency = decoupleGraphNode(rootNode, dep);
544
- hoistNodeDependencies([], Array.from(rootNodePathLocators), decoupledDependency, nextNewNodes);
545
- }
546
- } while (nextNewNodes.size > 0);
547
- return { anotherRoundNeeded, isGraphChanged };
548
- };
549
- const selfCheck = (tree) => {
550
- const log = [];
551
- const seenNodes = new Set();
552
- const parents = new Set();
553
- const checkNode = (node, parentDeps, parent) => {
554
- if (seenNodes.has(node))
555
- return;
556
- seenNodes.add(node);
557
- if (parents.has(node))
558
- return;
559
- const dependencies = new Map(parentDeps);
560
- for (const dep of node.dependencies.values())
561
- if (!node.peerNames.has(dep.name))
562
- dependencies.set(dep.name, dep);
563
- for (const origDep of node.originalDependencies.values()) {
564
- const dep = dependencies.get(origDep.name);
565
- const prettyPrintTreePath = () => `${Array.from(parents).concat([node]).map(x => prettyPrintLocator(x.locator)).join(`→`)}`;
566
- if (node.peerNames.has(origDep.name)) {
567
- const parentDep = parentDeps.get(origDep.name);
568
- if (parentDep !== dep || !parentDep || parentDep.ident !== origDep.ident) {
569
- log.push(`${prettyPrintTreePath()} - broken peer promise: expected ${origDep.ident} but found ${parentDep ? parentDep.ident : parentDep}`);
570
- }
571
- }
572
- else {
573
- const hoistedFrom = parent.hoistedFrom.get(node.name);
574
- const originalHoistedTo = node.hoistedTo.get(origDep.name);
575
- const prettyHoistedFrom = `${hoistedFrom ? ` hoisted from ${hoistedFrom.join(`, `)}` : ``}`;
576
- const prettyOriginalHoistedTo = `${originalHoistedTo ? ` hoisted to ${originalHoistedTo}` : ``}`;
577
- const prettyNodePath = `${prettyPrintTreePath()}${prettyHoistedFrom}`;
578
- if (!dep) {
579
- log.push(`${prettyNodePath} - broken require promise: no required dependency ${origDep.name}${prettyOriginalHoistedTo} found`);
580
- }
581
- else if (dep.ident !== origDep.ident) {
582
- log.push(`${prettyNodePath} - broken require promise for ${origDep.name}${prettyOriginalHoistedTo}: expected ${origDep.ident}, but found: ${dep.ident}`);
583
- }
584
- }
585
- }
586
- parents.add(node);
587
- for (const dep of node.dependencies.values()) {
588
- if (!node.peerNames.has(dep.name)) {
589
- checkNode(dep, dependencies, node);
590
- }
591
- }
592
- parents.delete(node);
593
- };
594
- checkNode(tree, tree.dependencies, tree);
595
- return log.join(`\n`);
596
- };
597
- /**
598
- * Creates a clone of package tree with extra fields used for hoisting purposes.
599
- *
600
- * @param tree package tree clone
601
- */
602
- const cloneTree = (tree, options) => {
603
- const { identName, name, reference, peerNames } = tree;
604
- const treeCopy = {
605
- name,
606
- references: new Set([reference]),
607
- locator: makeLocator(identName, reference),
608
- ident: makeIdent(identName, reference),
609
- dependencies: new Map(),
610
- originalDependencies: new Map(),
611
- hoistedDependencies: new Map(),
612
- peerNames: new Set(peerNames),
613
- reasons: new Map(),
614
- decoupled: true,
615
- isHoistBorder: true,
616
- hoistPriority: 0,
617
- isWorkspace: true,
618
- hoistedFrom: new Map(),
619
- hoistedTo: new Map(),
620
- };
621
- const seenNodes = new Map([[tree, treeCopy]]);
622
- const addNode = (node, parentNode) => {
623
- let workNode = seenNodes.get(node);
624
- const isSeen = !!workNode;
625
- if (!workNode) {
626
- const { name, identName, reference, peerNames, hoistPriority, isWorkspace } = node;
627
- const dependenciesNmHoistingLimits = options.hoistingLimits.get(parentNode.locator);
628
- workNode = {
629
- name,
630
- references: new Set([reference]),
631
- locator: makeLocator(identName, reference),
632
- ident: makeIdent(identName, reference),
633
- dependencies: new Map(),
634
- originalDependencies: new Map(),
635
- hoistedDependencies: new Map(),
636
- peerNames: new Set(peerNames),
637
- reasons: new Map(),
638
- decoupled: true,
639
- isHoistBorder: dependenciesNmHoistingLimits ? dependenciesNmHoistingLimits.has(name) : false,
640
- hoistPriority: hoistPriority || 0,
641
- isWorkspace: isWorkspace || false,
642
- hoistedFrom: new Map(),
643
- hoistedTo: new Map(),
644
- };
645
- seenNodes.set(node, workNode);
646
- }
647
- parentNode.dependencies.set(node.name, workNode);
648
- parentNode.originalDependencies.set(node.name, workNode);
649
- if (!isSeen) {
650
- for (const dep of node.dependencies) {
651
- addNode(dep, workNode);
652
- }
653
- }
654
- else {
655
- const seenCoupledNodes = new Set();
656
- const markNodeCoupled = (node) => {
657
- if (seenCoupledNodes.has(node))
658
- return;
659
- seenCoupledNodes.add(node);
660
- node.decoupled = false;
661
- for (const dep of node.dependencies.values()) {
662
- if (!node.peerNames.has(dep.name)) {
663
- markNodeCoupled(dep);
664
- }
665
- }
666
- };
667
- markNodeCoupled(workNode);
668
- }
669
- };
670
- for (const dep of tree.dependencies)
671
- addNode(dep, treeCopy);
672
- return treeCopy;
673
- };
674
- const getIdentName = (locator) => locator.substring(0, locator.indexOf(`@`, 1));
675
- /**
676
- * Creates a clone of hoisted package tree with extra fields removed
677
- *
678
- * @param tree stripped down hoisted package tree clone
679
- */
680
- const shrinkTree = (tree) => {
681
- const treeCopy = {
682
- name: tree.name,
683
- identName: getIdentName(tree.locator),
684
- references: new Set(tree.references),
685
- dependencies: new Set(),
686
- };
687
- const seenNodes = new Set([tree]);
688
- const addNode = (node, parentWorkNode, parentNode) => {
689
- const isSeen = seenNodes.has(node);
690
- let resultNode;
691
- if (parentWorkNode === node) {
692
- resultNode = parentNode;
693
- }
694
- else {
695
- const { name, references, locator } = node;
696
- resultNode = {
697
- name,
698
- identName: getIdentName(locator),
699
- references,
700
- dependencies: new Set(),
701
- };
702
- }
703
- parentNode.dependencies.add(resultNode);
704
- if (!isSeen) {
705
- seenNodes.add(node);
706
- for (const dep of node.dependencies.values()) {
707
- if (!node.peerNames.has(dep.name)) {
708
- addNode(dep, node, resultNode);
709
- }
710
- }
711
- seenNodes.delete(node);
712
- }
713
- };
714
- for (const dep of tree.dependencies.values())
715
- addNode(dep, tree, treeCopy);
716
- return treeCopy;
717
- };
718
- /**
719
- * Builds mapping, where key is an alias + dependent package ident and the value is the list of
720
- * parent package idents who depend on this package.
721
- *
722
- * @param rootNode package tree root node
723
- *
724
- * @returns preference map
725
- */
726
- const buildPreferenceMap = (rootNode) => {
727
- const preferenceMap = new Map();
728
- const seenNodes = new Set([rootNode]);
729
- const getPreferenceKey = (node) => `${node.name}@${node.ident}`;
730
- const getOrCreatePreferenceEntry = (node) => {
731
- const key = getPreferenceKey(node);
732
- let entry = preferenceMap.get(key);
733
- if (!entry) {
734
- entry = { dependents: new Set(), peerDependents: new Set(), hoistPriority: 0 };
735
- preferenceMap.set(key, entry);
736
- }
737
- return entry;
738
- };
739
- const addDependent = (dependent, node) => {
740
- const isSeen = !!seenNodes.has(node);
741
- const entry = getOrCreatePreferenceEntry(node);
742
- entry.dependents.add(dependent.ident);
743
- if (!isSeen) {
744
- seenNodes.add(node);
745
- for (const dep of node.dependencies.values()) {
746
- const entry = getOrCreatePreferenceEntry(dep);
747
- entry.hoistPriority = Math.max(entry.hoistPriority, dep.hoistPriority);
748
- if (node.peerNames.has(dep.name)) {
749
- entry.peerDependents.add(node.ident);
750
- }
751
- else {
752
- addDependent(node, dep);
753
- }
754
- }
755
- }
756
- };
757
- for (const dep of rootNode.dependencies.values())
758
- if (!rootNode.peerNames.has(dep.name))
759
- addDependent(rootNode, dep);
760
- return preferenceMap;
761
- };
762
- const prettyPrintLocator = (locator) => {
763
- if (!locator)
764
- return `none`;
765
- const idx = locator.indexOf(`@`, 1);
766
- let name = locator.substring(0, idx);
767
- if (name.endsWith(`$wsroot$`))
768
- name = `wh:${name.replace(`$wsroot$`, ``)}`;
769
- const reference = locator.substring(idx + 1);
770
- if (reference === `workspace:.`) {
771
- return `.`;
772
- }
773
- else if (!reference) {
774
- return `${name}`;
775
- }
776
- else {
777
- let version = (reference.indexOf(`#`) > 0 ? reference.split(`#`)[1] : reference).replace(`npm:`, ``);
778
- if (reference.startsWith(`virtual`))
779
- name = `v:${name}`;
780
- if (version.startsWith(`workspace`)) {
781
- name = `w:${name}`;
782
- version = ``;
783
- }
784
- return `${name}${version ? `@${version}` : ``}`;
785
- }
786
- };
787
- const MAX_NODES_TO_DUMP = 50000;
788
- /**
789
- * Pretty-prints dependency tree in the `yarn why`-like format
790
- *
791
- * The function is used for troubleshooting purposes only.
792
- *
793
- * @param pkg node_modules tree
794
- *
795
- * @returns sorted node_modules tree
796
- */
797
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
798
- const dumpDepTree = (tree) => {
799
- let nodeCount = 0;
800
- const dumpPackage = (pkg, parents, prefix = ``) => {
801
- if (nodeCount > MAX_NODES_TO_DUMP || parents.has(pkg))
802
- return ``;
803
- nodeCount++;
804
- const dependencies = Array.from(pkg.dependencies.values()).sort((n1, n2) => {
805
- if (n1.name === n2.name) {
806
- return 0;
807
- }
808
- else {
809
- return n1.name > n2.name ? 1 : -1;
810
- }
811
- });
812
- let str = ``;
813
- parents.add(pkg);
814
- for (let idx = 0; idx < dependencies.length; idx++) {
815
- const dep = dependencies[idx];
816
- if (!pkg.peerNames.has(dep.name) && dep !== pkg) {
817
- const reason = pkg.reasons.get(dep.name);
818
- const identName = getIdentName(dep.locator);
819
- const hoistedFrom = pkg.hoistedFrom.get(dep.name) || [];
820
- str += `${prefix}${idx < dependencies.length - 1 ? `├─` : `└─`}${(parents.has(dep) ? `>` : ``) + (identName !== dep.name ? `a:${dep.name}:` : ``) + prettyPrintLocator(dep.locator) + (reason ? ` ${reason}` : ``) + (dep !== pkg && hoistedFrom.length > 0 ? `, hoisted from: ${hoistedFrom.join(`, `)}` : ``)}\n`;
821
- str += dumpPackage(dep, parents, `${prefix}${idx < dependencies.length - 1 ? `│ ` : ` `}`);
822
- }
823
- }
824
- parents.delete(pkg);
825
- return str;
826
- };
827
- const treeDump = dumpPackage(tree, new Set());
828
- return treeDump + ((nodeCount > MAX_NODES_TO_DUMP) ? `\nTree is too large, part of the tree has been dunped\n` : ``);
829
- };