UNPKG

34.2 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _extends2;
8
9function _load_extends() {
10 return _extends2 = _interopRequireDefault(require('babel-runtime/helpers/extends'));
11}
12
13var _asyncToGenerator2;
14
15function _load_asyncToGenerator() {
16 return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
17}
18
19exports.extractWorkspaces = extractWorkspaces;
20
21var _executeLifecycleScript;
22
23function _load_executeLifecycleScript() {
24 return _executeLifecycleScript = require('./util/execute-lifecycle-script.js');
25}
26
27var _path;
28
29function _load_path() {
30 return _path = require('./util/path.js');
31}
32
33var _conversion;
34
35function _load_conversion() {
36 return _conversion = require('./util/conversion.js');
37}
38
39var _index;
40
41function _load_index() {
42 return _index = _interopRequireDefault(require('./util/normalize-manifest/index.js'));
43}
44
45var _errors;
46
47function _load_errors() {
48 return _errors = require('./errors.js');
49}
50
51var _fs;
52
53function _load_fs() {
54 return _fs = _interopRequireWildcard(require('./util/fs.js'));
55}
56
57var _constants;
58
59function _load_constants() {
60 return _constants = _interopRequireWildcard(require('./constants.js'));
61}
62
63var _packageConstraintResolver;
64
65function _load_packageConstraintResolver() {
66 return _packageConstraintResolver = _interopRequireDefault(require('./package-constraint-resolver.js'));
67}
68
69var _requestManager;
70
71function _load_requestManager() {
72 return _requestManager = _interopRequireDefault(require('./util/request-manager.js'));
73}
74
75var _index2;
76
77function _load_index2() {
78 return _index2 = require('./registries/index.js');
79}
80
81var _index3;
82
83function _load_index3() {
84 return _index3 = require('./reporters/index.js');
85}
86
87var _map;
88
89function _load_map() {
90 return _map = _interopRequireDefault(require('./util/map.js'));
91}
92
93function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
94
95function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
96
97const detectIndent = require('detect-indent');
98const invariant = require('invariant');
99const path = require('path');
100const micromatch = require('micromatch');
101const isCi = require('is-ci');
102
103function sortObject(object) {
104 const sortedObject = {};
105 Object.keys(object).sort().forEach(item => {
106 sortedObject[item] = object[item];
107 });
108 return sortedObject;
109}
110
111class Config {
112 constructor(reporter) {
113 this.constraintResolver = new (_packageConstraintResolver || _load_packageConstraintResolver()).default(this, reporter);
114 this.requestManager = new (_requestManager || _load_requestManager()).default(reporter);
115 this.reporter = reporter;
116 this._init({});
117 }
118
119 //
120
121
122 //
123
124
125 // cache packages in offline mirror folder as new .tgz files
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 // Whether we should ignore executing lifecycle scripts
165
166
167 //
168
169
170 //
171
172
173 //
174
175
176 //
177
178
179 /**
180 * Execute a promise produced by factory if it doesn't exist in our cache with
181 * the associated key.
182 */
183
184 getCache(key, factory) {
185 const cached = this.cache[key];
186 if (cached) {
187 return cached;
188 }
189
190 return this.cache[key] = factory().catch(err => {
191 this.cache[key] = null;
192 throw err;
193 });
194 }
195
196 /**
197 * Get a config option from our yarn config.
198 */
199
200 getOption(key, resolve = false) {
201 const value = this.registries.yarn.getOption(key);
202
203 if (resolve && typeof value === 'string' && value.length) {
204 return (0, (_path || _load_path()).resolveWithHome)(value);
205 }
206
207 return value;
208 }
209
210 /**
211 * Reduce a list of versions to a single one based on an input range.
212 */
213
214 resolveConstraints(versions, range) {
215 return this.constraintResolver.reduce(versions, range);
216 }
217
218 /**
219 * Initialise config. Fetch registry options, find package roots.
220 */
221
222 init(opts = {}) {
223 var _this = this;
224
225 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
226 _this._init(opts);
227
228 _this.workspaceRootFolder = yield _this.findWorkspaceRoot(_this.cwd);
229 _this.lockfileFolder = _this.workspaceRootFolder || _this.cwd;
230
231 // using focus in a workspace root is not allowed
232 if (_this.focus && (!_this.workspaceRootFolder || _this.cwd === _this.workspaceRootFolder)) {
233 throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('workspacesFocusRootCheck'));
234 }
235
236 if (_this.focus) {
237 const focusedWorkspaceManifest = yield _this.readRootManifest();
238 _this.focusedWorkspaceName = focusedWorkspaceManifest.name;
239 }
240
241 _this.linkedModules = [];
242
243 let linkedModules;
244 try {
245 linkedModules = yield (_fs || _load_fs()).readdir(_this.linkFolder);
246 } catch (err) {
247 if (err.code === 'ENOENT') {
248 linkedModules = [];
249 } else {
250 throw err;
251 }
252 }
253
254 for (var _iterator = linkedModules, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
255 var _ref;
256
257 if (_isArray) {
258 if (_i >= _iterator.length) break;
259 _ref = _iterator[_i++];
260 } else {
261 _i = _iterator.next();
262 if (_i.done) break;
263 _ref = _i.value;
264 }
265
266 const dir = _ref;
267
268 const linkedPath = path.join(_this.linkFolder, dir);
269
270 if (dir[0] === '@') {
271 // it's a scope, not a package
272 const scopedLinked = yield (_fs || _load_fs()).readdir(linkedPath);
273 _this.linkedModules.push(...scopedLinked.map(function (scopedDir) {
274 return path.join(dir, scopedDir);
275 }));
276 } else {
277 _this.linkedModules.push(dir);
278 }
279 }
280
281 for (var _iterator2 = Object.keys((_index2 || _load_index2()).registries), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
282 var _ref2;
283
284 if (_isArray2) {
285 if (_i2 >= _iterator2.length) break;
286 _ref2 = _iterator2[_i2++];
287 } else {
288 _i2 = _iterator2.next();
289 if (_i2.done) break;
290 _ref2 = _i2.value;
291 }
292
293 const key = _ref2;
294
295 const Registry = (_index2 || _load_index2()).registries[key];
296
297 const extraneousRcFiles = Registry === (_index2 || _load_index2()).registries.yarn ? _this.extraneousYarnrcFiles : [];
298
299 // instantiate registry
300 const registry = new Registry(_this.cwd, _this.registries, _this.requestManager, _this.reporter, _this.enableDefaultRc, extraneousRcFiles);
301 yield registry.init({
302 registry: opts.registry
303 });
304
305 _this.registries[key] = registry;
306 if (_this.registryFolders.indexOf(registry.folder) === -1) {
307 _this.registryFolders.push(registry.folder);
308 }
309 const rootModuleFolder = path.join(_this.cwd, registry.folder);
310 if (_this.rootModuleFolders.indexOf(rootModuleFolder) === -1) {
311 _this.rootModuleFolders.push(rootModuleFolder);
312 }
313 }
314
315 if (_this.modulesFolder) {
316 _this.registryFolders.push(_this.modulesFolder);
317 }
318
319 _this.networkConcurrency = opts.networkConcurrency || Number(_this.getOption('network-concurrency')) || (_constants || _load_constants()).NETWORK_CONCURRENCY;
320
321 _this.childConcurrency = opts.childConcurrency || Number(_this.getOption('child-concurrency')) || Number(process.env.CHILD_CONCURRENCY) || (_constants || _load_constants()).CHILD_CONCURRENCY;
322
323 _this.networkTimeout = opts.networkTimeout || Number(_this.getOption('network-timeout')) || (_constants || _load_constants()).NETWORK_TIMEOUT;
324
325 const httpProxy = opts.httpProxy || _this.getOption('proxy');
326 const httpsProxy = opts.httpsProxy || _this.getOption('https-proxy');
327 _this.requestManager.setOptions({
328 userAgent: String(_this.getOption('user-agent')),
329 httpProxy: httpProxy === false ? false : String(httpProxy || ''),
330 httpsProxy: httpsProxy === false ? false : String(httpsProxy || ''),
331 strictSSL: Boolean(_this.getOption('strict-ssl')),
332 ca: Array.prototype.concat(opts.ca || _this.getOption('ca') || []).map(String),
333 cafile: String(opts.cafile || _this.getOption('cafile', true) || ''),
334 cert: String(opts.cert || _this.getOption('cert') || ''),
335 key: String(opts.key || _this.getOption('key') || ''),
336 networkConcurrency: _this.networkConcurrency,
337 networkTimeout: _this.networkTimeout
338 });
339
340 let cacheRootFolder = opts.cacheFolder || _this.getOption('cache-folder', true);
341
342 if (!cacheRootFolder) {
343 let preferredCacheFolders = (_constants || _load_constants()).PREFERRED_MODULE_CACHE_DIRECTORIES;
344 const preferredCacheFolder = opts.preferredCacheFolder || _this.getOption('preferred-cache-folder', true);
345
346 if (preferredCacheFolder) {
347 preferredCacheFolders = [String(preferredCacheFolder)].concat(preferredCacheFolders);
348 }
349
350 const cacheFolderQuery = yield (_fs || _load_fs()).getFirstSuitableFolder(preferredCacheFolders, (_fs || _load_fs()).constants.W_OK | (_fs || _load_fs()).constants.X_OK | (_fs || _load_fs()).constants.R_OK // eslint-disable-line no-bitwise
351 );
352 for (var _iterator3 = cacheFolderQuery.skipped, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
353 var _ref3;
354
355 if (_isArray3) {
356 if (_i3 >= _iterator3.length) break;
357 _ref3 = _iterator3[_i3++];
358 } else {
359 _i3 = _iterator3.next();
360 if (_i3.done) break;
361 _ref3 = _i3.value;
362 }
363
364 const skippedEntry = _ref3;
365
366 _this.reporter.warn(_this.reporter.lang('cacheFolderSkipped', skippedEntry.folder));
367 }
368
369 cacheRootFolder = cacheFolderQuery.folder;
370 if (cacheRootFolder && cacheFolderQuery.skipped.length > 0) {
371 _this.reporter.warn(_this.reporter.lang('cacheFolderSelected', cacheRootFolder));
372 }
373 }
374
375 if (!cacheRootFolder) {
376 throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('cacheFolderMissing'));
377 } else {
378 _this._cacheRootFolder = String(cacheRootFolder);
379 }
380
381 const manifest = yield _this.maybeReadManifest(_this.cwd);
382
383 const plugnplayByEnv = _this.getOption('plugnplay-override');
384 if (plugnplayByEnv != null) {
385 _this.plugnplayEnabled = plugnplayByEnv !== 'false' && plugnplayByEnv !== '0';
386 _this.plugnplayPersist = false;
387 } else if (opts.enablePnp || opts.disablePnp) {
388 _this.plugnplayEnabled = !!opts.enablePnp;
389 _this.plugnplayPersist = true;
390 } else if (manifest && manifest.installConfig && manifest.installConfig.pnp) {
391 _this.plugnplayEnabled = !!manifest.installConfig.pnp;
392 _this.plugnplayPersist = false;
393 } else {
394 _this.plugnplayEnabled = false;
395 _this.plugnplayEnabled = false;
396 }
397
398 if (process.platform === 'win32') {
399 const cacheRootFolderDrive = path.parse(_this._cacheRootFolder).root;
400 const lockfileFolderDrive = path.parse(_this.lockfileFolder).root;
401
402 if (cacheRootFolderDrive !== lockfileFolderDrive) {
403 if (_this.plugnplayEnabled) {
404 _this.reporter.warn(_this.reporter.lang('plugnplayWindowsSupport'));
405 }
406 _this.plugnplayEnabled = false;
407 _this.plugnplayPersist = false;
408 }
409 }
410
411 _this.plugnplayShebang = String(_this.getOption('plugnplay-shebang') || '') || '/usr/bin/env node';
412 _this.plugnplayBlacklist = String(_this.getOption('plugnplay-blacklist') || '') || null;
413
414 _this.workspacesEnabled = _this.getOption('workspaces-experimental') !== false;
415 _this.workspacesNohoistEnabled = _this.getOption('workspaces-nohoist-experimental') !== false;
416
417 _this.offlineCacheFolder = String(_this.getOption('offline-cache-folder') || '') || null;
418
419 _this.pruneOfflineMirror = Boolean(_this.getOption('yarn-offline-mirror-pruning'));
420 _this.enableMetaFolder = Boolean(_this.getOption('enable-meta-folder'));
421 _this.enableLockfileVersions = Boolean(_this.getOption('yarn-enable-lockfile-versions'));
422 _this.linkFileDependencies = Boolean(_this.getOption('yarn-link-file-dependencies'));
423 _this.packBuiltPackages = Boolean(_this.getOption('experimental-pack-script-packages-in-mirror'));
424
425 _this.autoAddIntegrity = !(0, (_conversion || _load_conversion()).boolifyWithDefault)(String(_this.getOption('unsafe-disable-integrity-migration')), true);
426
427 //init & create cacheFolder, tempFolder
428 _this.cacheFolder = path.join(_this._cacheRootFolder, 'v' + String((_constants || _load_constants()).CACHE_VERSION));
429 _this.tempFolder = opts.tempFolder || path.join(_this.cacheFolder, '.tmp');
430 yield (_fs || _load_fs()).mkdirp(_this.cacheFolder);
431 yield (_fs || _load_fs()).mkdirp(_this.tempFolder);
432
433 if (opts.production !== undefined) {
434 _this.production = Boolean(opts.production);
435 } else {
436 _this.production = Boolean(_this.getOption('production')) || process.env.NODE_ENV === 'production' && process.env.NPM_CONFIG_PRODUCTION !== 'false' && process.env.YARN_PRODUCTION !== 'false';
437 }
438
439 if (_this.workspaceRootFolder && !_this.workspacesEnabled) {
440 throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('workspacesDisabled'));
441 }
442 })();
443 }
444
445 _init(opts) {
446 this.rootModuleFolders = [];
447 this.registryFolders = [];
448 this.linkedModules = [];
449
450 this.registries = (0, (_map || _load_map()).default)();
451 this.cache = (0, (_map || _load_map()).default)();
452
453 // Ensure the cwd is always an absolute path.
454 this.cwd = path.resolve(opts.cwd || this.cwd || process.cwd());
455
456 this.looseSemver = opts.looseSemver == undefined ? true : opts.looseSemver;
457
458 this.commandName = opts.commandName || '';
459
460 this.enableDefaultRc = opts.enableDefaultRc !== false;
461 this.extraneousYarnrcFiles = opts.extraneousYarnrcFiles || [];
462
463 this.preferOffline = !!opts.preferOffline;
464 this.modulesFolder = opts.modulesFolder;
465 this.globalFolder = opts.globalFolder || (_constants || _load_constants()).GLOBAL_MODULE_DIRECTORY;
466 this.linkFolder = opts.linkFolder || (_constants || _load_constants()).LINK_REGISTRY_DIRECTORY;
467 this.offline = !!opts.offline;
468 this.binLinks = !!opts.binLinks;
469 this.updateChecksums = !!opts.updateChecksums;
470 this.plugnplayUnplugged = [];
471 this.plugnplayPurgeUnpluggedPackages = false;
472
473 this.ignorePlatform = !!opts.ignorePlatform;
474 this.ignoreScripts = !!opts.ignoreScripts;
475
476 this.disablePrepublish = !!opts.disablePrepublish;
477
478 // $FlowFixMe$
479 this.nonInteractive = !!opts.nonInteractive || isCi || !process.stdout.isTTY;
480
481 this.scriptsPrependNodePath = !!opts.scriptsPrependNodePath;
482
483 this.requestManager.setOptions({
484 offline: !!opts.offline && !opts.preferOffline,
485 captureHar: !!opts.captureHar
486 });
487
488 if (this.modulesFolder) {
489 this.rootModuleFolders.push(this.modulesFolder);
490 }
491
492 this.focus = !!opts.focus;
493 this.focusedWorkspaceName = '';
494
495 this.otp = opts.otp || '';
496 }
497
498 /**
499 * Generate a name suitable as unique filesystem identifier for the specified package.
500 */
501
502 generateUniquePackageSlug(pkg) {
503 let slug = pkg.name;
504
505 slug = slug.replace(/[^@a-z0-9]+/g, '-');
506 slug = slug.replace(/^-+|-+$/g, '');
507
508 if (pkg.registry) {
509 slug = `${pkg.registry}-${slug}`;
510 } else {
511 slug = `unknown-${slug}`;
512 }
513
514 const hash = pkg.remote.hash;
515
516
517 if (pkg.version) {
518 slug += `-${pkg.version}`;
519 }
520
521 if (pkg.uid && pkg.version !== pkg.uid) {
522 slug += `-${pkg.uid}`;
523 } else if (hash) {
524 slug += `-${hash}`;
525 }
526
527 return slug;
528 }
529
530 /**
531 * Generate an absolute module path.
532 */
533
534 generateModuleCachePath(pkg) {
535 invariant(this.cacheFolder, 'No package root');
536 invariant(pkg, 'Undefined package');
537
538 const slug = this.generateUniquePackageSlug(pkg);
539 return path.join(this.cacheFolder, slug, 'node_modules', pkg.name);
540 }
541
542 /**
543 */
544
545 getUnpluggedPath() {
546 return path.join(this.lockfileFolder, '.pnp', 'unplugged');
547 }
548
549 /**
550 */
551
552 generatePackageUnpluggedPath(pkg) {
553 const slug = this.generateUniquePackageSlug(pkg);
554 return path.join(this.getUnpluggedPath(), slug, 'node_modules', pkg.name);
555 }
556
557 /**
558 */
559
560 listUnpluggedPackageFolders() {
561 var _this2 = this;
562
563 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
564 const unpluggedPackages = new Map();
565 const unpluggedPath = _this2.getUnpluggedPath();
566
567 if (!(yield (_fs || _load_fs()).exists(unpluggedPath))) {
568 return unpluggedPackages;
569 }
570
571 for (var _iterator4 = yield (_fs || _load_fs()).readdir(unpluggedPath), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
572 var _ref4;
573
574 if (_isArray4) {
575 if (_i4 >= _iterator4.length) break;
576 _ref4 = _iterator4[_i4++];
577 } else {
578 _i4 = _iterator4.next();
579 if (_i4.done) break;
580 _ref4 = _i4.value;
581 }
582
583 const unpluggedName = _ref4;
584
585 const nmListing = yield (_fs || _load_fs()).readdir(path.join(unpluggedPath, unpluggedName, 'node_modules'));
586 invariant(nmListing.length === 1, 'A single folder should be in the unplugged directory');
587
588 const target = path.join(unpluggedPath, unpluggedName, `node_modules`, nmListing[0]);
589 unpluggedPackages.set(unpluggedName, target);
590 }
591
592 return unpluggedPackages;
593 })();
594 }
595
596 /**
597 * Execute lifecycle scripts in the specified directory. Ignoring when the --ignore-scripts flag has been
598 * passed.
599 */
600
601 executeLifecycleScript(commandName, cwd) {
602 if (this.ignoreScripts) {
603 return Promise.resolve();
604 } else {
605 return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execFromManifest)(this, commandName, cwd || this.cwd);
606 }
607 }
608
609 /**
610 * Generate an absolute temporary filename location based on the input filename.
611 */
612
613 getTemp(filename) {
614 invariant(this.tempFolder, 'No temp folder');
615 return path.join(this.tempFolder, filename);
616 }
617
618 /**
619 * Remote packages may be cached in a file system to be available for offline installation.
620 * Second time the same package needs to be installed it will be loaded from there.
621 * Given a package's filename, return a path in the offline mirror location.
622 */
623
624 getOfflineMirrorPath(packageFilename) {
625 let mirrorPath;
626
627 var _arr = ['npm', 'yarn'];
628 for (var _i5 = 0; _i5 < _arr.length; _i5++) {
629 const key = _arr[_i5];
630 const registry = this.registries[key];
631
632 if (registry == null) {
633 continue;
634 }
635
636 const registryMirrorPath = registry.config['yarn-offline-mirror'];
637
638 if (registryMirrorPath === false) {
639 return null;
640 }
641
642 if (registryMirrorPath == null) {
643 continue;
644 }
645
646 mirrorPath = registryMirrorPath;
647 }
648
649 if (mirrorPath == null) {
650 return null;
651 }
652
653 if (packageFilename == null) {
654 return mirrorPath;
655 }
656
657 return path.join(mirrorPath, path.basename(packageFilename));
658 }
659
660 /**
661 * Checker whether the folder input is a valid module folder. We output a yarn metadata
662 * file when we've successfully setup a folder so use this as a marker.
663 */
664
665 isValidModuleDest(dest) {
666 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
667 if (!(yield (_fs || _load_fs()).exists(dest))) {
668 return false;
669 }
670
671 if (!(yield (_fs || _load_fs()).exists(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME)))) {
672 return false;
673 }
674
675 return true;
676 })();
677 }
678
679 /**
680 * Read package metadata and normalized package info.
681 */
682
683 readPackageMetadata(dir) {
684 var _this3 = this;
685
686 return this.getCache(`metadata-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
687 const metadata = yield _this3.readJson(path.join(dir, (_constants || _load_constants()).METADATA_FILENAME));
688 const pkg = yield _this3.readManifest(dir, metadata.registry);
689
690 return {
691 package: pkg,
692 artifacts: metadata.artifacts || [],
693 hash: metadata.hash,
694 remote: metadata.remote,
695 registry: metadata.registry
696 };
697 }));
698 }
699
700 /**
701 * Read normalized package info according yarn-metadata.json
702 * throw an error if package.json was not found
703 */
704
705 readManifest(dir, priorityRegistry, isRoot = false) {
706 var _this4 = this;
707
708 return this.getCache(`manifest-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
709 const manifest = yield _this4.maybeReadManifest(dir, priorityRegistry, isRoot);
710
711 if (manifest) {
712 return manifest;
713 } else {
714 throw new (_errors || _load_errors()).MessageError(_this4.reporter.lang('couldntFindPackagejson', dir), 'ENOENT');
715 }
716 }));
717 }
718
719 /**
720 * try get the manifest file by looking
721 * 1. manifest file in cache
722 * 2. manifest file in registry
723 */
724 maybeReadManifest(dir, priorityRegistry, isRoot = false) {
725 var _this5 = this;
726
727 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
728 const metadataLoc = path.join(dir, (_constants || _load_constants()).METADATA_FILENAME);
729
730 if (yield (_fs || _load_fs()).exists(metadataLoc)) {
731 const metadata = yield _this5.readJson(metadataLoc);
732
733 if (!priorityRegistry) {
734 priorityRegistry = metadata.priorityRegistry;
735 }
736
737 if (typeof metadata.manifest !== 'undefined') {
738 return metadata.manifest;
739 }
740 }
741
742 if (priorityRegistry) {
743 const file = yield _this5.tryManifest(dir, priorityRegistry, isRoot);
744 if (file) {
745 return file;
746 }
747 }
748
749 for (var _iterator5 = Object.keys((_index2 || _load_index2()).registries), _isArray5 = Array.isArray(_iterator5), _i6 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
750 var _ref7;
751
752 if (_isArray5) {
753 if (_i6 >= _iterator5.length) break;
754 _ref7 = _iterator5[_i6++];
755 } else {
756 _i6 = _iterator5.next();
757 if (_i6.done) break;
758 _ref7 = _i6.value;
759 }
760
761 const registry = _ref7;
762
763 if (priorityRegistry === registry) {
764 continue;
765 }
766
767 const file = yield _this5.tryManifest(dir, registry, isRoot);
768 if (file) {
769 return file;
770 }
771 }
772
773 return null;
774 })();
775 }
776
777 /**
778 * Read the root manifest.
779 */
780
781 readRootManifest() {
782 return this.readManifest(this.cwd, 'npm', true);
783 }
784
785 /**
786 * Try and find package info with the input directory and registry.
787 */
788
789 tryManifest(dir, registry, isRoot) {
790 var _this6 = this;
791
792 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
793 const filename = (_index2 || _load_index2()).registries[registry].filename;
794
795 const loc = path.join(dir, filename);
796 if (yield (_fs || _load_fs()).exists(loc)) {
797 const data = yield _this6.readJson(loc);
798 data._registry = registry;
799 data._loc = loc;
800 return (0, (_index || _load_index()).default)(data, dir, _this6, isRoot);
801 } else {
802 return null;
803 }
804 })();
805 }
806
807 findManifest(dir, isRoot) {
808 var _this7 = this;
809
810 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
811 for (var _iterator6 = (_index2 || _load_index2()).registryNames, _isArray6 = Array.isArray(_iterator6), _i7 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
812 var _ref8;
813
814 if (_isArray6) {
815 if (_i7 >= _iterator6.length) break;
816 _ref8 = _iterator6[_i7++];
817 } else {
818 _i7 = _iterator6.next();
819 if (_i7.done) break;
820 _ref8 = _i7.value;
821 }
822
823 const registry = _ref8;
824
825 const manifest = yield _this7.tryManifest(dir, registry, isRoot);
826
827 if (manifest) {
828 return manifest;
829 }
830 }
831
832 return null;
833 })();
834 }
835
836 findWorkspaceRoot(initial) {
837 var _this8 = this;
838
839 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
840 let previous = null;
841 let current = path.normalize(initial);
842 if (!(yield (_fs || _load_fs()).exists(current))) {
843 throw new (_errors || _load_errors()).MessageError(_this8.reporter.lang('folderMissing', current));
844 }
845
846 do {
847 const manifest = yield _this8.findManifest(current, true);
848 const ws = extractWorkspaces(manifest);
849 if (ws && ws.packages) {
850 const relativePath = path.relative(current, initial);
851 if (relativePath === '' || micromatch([relativePath], ws.packages).length > 0) {
852 return current;
853 } else {
854 return null;
855 }
856 }
857
858 previous = current;
859 current = path.dirname(current);
860 } while (current !== previous);
861
862 return null;
863 })();
864 }
865
866 resolveWorkspaces(root, rootManifest) {
867 var _this9 = this;
868
869 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
870 const workspaces = {};
871 if (!_this9.workspacesEnabled) {
872 return workspaces;
873 }
874
875 const ws = _this9.getWorkspaces(rootManifest, true);
876 const patterns = ws && ws.packages ? ws.packages : [];
877
878 if (!Array.isArray(patterns)) {
879 throw new (_errors || _load_errors()).MessageError(_this9.reporter.lang('workspacesSettingMustBeArray'));
880 }
881
882 const registryFilenames = (_index2 || _load_index2()).registryNames.map(function (registryName) {
883 return _this9.registries[registryName].constructor.filename;
884 }).join('|');
885 const trailingPattern = `/+(${registryFilenames})`;
886 // anything under folder (node_modules) should be ignored, thus use the '**' instead of shallow match "*"
887 const ignorePatterns = _this9.registryFolders.map(function (folder) {
888 return `/${folder}/**/+(${registryFilenames})`;
889 });
890
891 const files = yield Promise.all(patterns.map(function (pattern) {
892 return (_fs || _load_fs()).glob(pattern.replace(/\/?$/, trailingPattern), {
893 cwd: root,
894 ignore: ignorePatterns.map(function (ignorePattern) {
895 return pattern.replace(/\/?$/, ignorePattern);
896 })
897 });
898 }));
899
900 for (var _iterator7 = new Set([].concat(...files)), _isArray7 = Array.isArray(_iterator7), _i8 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
901 var _ref9;
902
903 if (_isArray7) {
904 if (_i8 >= _iterator7.length) break;
905 _ref9 = _iterator7[_i8++];
906 } else {
907 _i8 = _iterator7.next();
908 if (_i8.done) break;
909 _ref9 = _i8.value;
910 }
911
912 const file = _ref9;
913
914 const loc = path.join(root, path.dirname(file));
915 const manifest = yield _this9.findManifest(loc, false);
916
917 if (!manifest) {
918 continue;
919 }
920
921 if (!manifest.name) {
922 _this9.reporter.warn(_this9.reporter.lang('workspaceNameMandatory', loc));
923 continue;
924 }
925 if (!manifest.version) {
926 _this9.reporter.warn(_this9.reporter.lang('workspaceVersionMandatory', loc));
927 continue;
928 }
929
930 if (Object.prototype.hasOwnProperty.call(workspaces, manifest.name)) {
931 throw new (_errors || _load_errors()).MessageError(_this9.reporter.lang('workspaceNameDuplicate', manifest.name));
932 }
933
934 workspaces[manifest.name] = { loc, manifest };
935 }
936
937 return workspaces;
938 })();
939 }
940
941 // workspaces functions
942 getWorkspaces(manifest, shouldThrow = false) {
943 if (!manifest || !this.workspacesEnabled) {
944 return undefined;
945 }
946
947 const ws = extractWorkspaces(manifest);
948
949 if (!ws) {
950 return ws;
951 }
952
953 // validate eligibility
954 let wsCopy = (0, (_extends2 || _load_extends()).default)({}, ws);
955 const warnings = [];
956 const errors = [];
957
958 // packages
959 if (wsCopy.packages && wsCopy.packages.length > 0 && !manifest.private) {
960 errors.push(this.reporter.lang('workspacesRequirePrivateProjects'));
961 wsCopy = undefined;
962 }
963 // nohoist
964 if (wsCopy && wsCopy.nohoist && wsCopy.nohoist.length > 0) {
965 if (!this.workspacesNohoistEnabled) {
966 warnings.push(this.reporter.lang('workspacesNohoistDisabled', manifest.name));
967 wsCopy.nohoist = undefined;
968 } else if (!manifest.private) {
969 errors.push(this.reporter.lang('workspacesNohoistRequirePrivatePackages', manifest.name));
970 wsCopy.nohoist = undefined;
971 }
972 }
973
974 if (errors.length > 0 && shouldThrow) {
975 throw new (_errors || _load_errors()).MessageError(errors.join('\n'));
976 }
977
978 const msg = errors.concat(warnings).join('\n');
979 if (msg.length > 0) {
980 this.reporter.warn(msg);
981 }
982
983 return wsCopy;
984 }
985
986 /**
987 * Description
988 */
989
990 getFolder(pkg) {
991 let registryName = pkg._registry;
992 if (!registryName) {
993 const ref = pkg._reference;
994 invariant(ref, 'expected reference');
995 registryName = ref.registry;
996 }
997 return this.registries[registryName].folder;
998 }
999
1000 /**
1001 * Get root manifests.
1002 */
1003
1004 getRootManifests() {
1005 var _this10 = this;
1006
1007 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
1008 const manifests = {};
1009 for (var _iterator8 = (_index2 || _load_index2()).registryNames, _isArray8 = Array.isArray(_iterator8), _i9 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
1010 var _ref10;
1011
1012 if (_isArray8) {
1013 if (_i9 >= _iterator8.length) break;
1014 _ref10 = _iterator8[_i9++];
1015 } else {
1016 _i9 = _iterator8.next();
1017 if (_i9.done) break;
1018 _ref10 = _i9.value;
1019 }
1020
1021 const registryName = _ref10;
1022
1023 const registry = (_index2 || _load_index2()).registries[registryName];
1024 const jsonLoc = path.join(_this10.cwd, registry.filename);
1025
1026 let object = {};
1027 let exists = false;
1028 let indent;
1029 if (yield (_fs || _load_fs()).exists(jsonLoc)) {
1030 exists = true;
1031
1032 const info = yield _this10.readJson(jsonLoc, (_fs || _load_fs()).readJsonAndFile);
1033 object = info.object;
1034 indent = detectIndent(info.content).indent || undefined;
1035 }
1036 manifests[registryName] = { loc: jsonLoc, object, exists, indent };
1037 }
1038 return manifests;
1039 })();
1040 }
1041
1042 /**
1043 * Save root manifests.
1044 */
1045
1046 saveRootManifests(manifests) {
1047 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
1048 for (var _iterator9 = (_index2 || _load_index2()).registryNames, _isArray9 = Array.isArray(_iterator9), _i10 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
1049 var _ref11;
1050
1051 if (_isArray9) {
1052 if (_i10 >= _iterator9.length) break;
1053 _ref11 = _iterator9[_i10++];
1054 } else {
1055 _i10 = _iterator9.next();
1056 if (_i10.done) break;
1057 _ref11 = _i10.value;
1058 }
1059
1060 const registryName = _ref11;
1061 var _manifests$registryNa = manifests[registryName];
1062 const loc = _manifests$registryNa.loc,
1063 object = _manifests$registryNa.object,
1064 exists = _manifests$registryNa.exists,
1065 indent = _manifests$registryNa.indent;
1066
1067 if (!exists && !Object.keys(object).length) {
1068 continue;
1069 }
1070
1071 for (var _iterator10 = (_constants || _load_constants()).DEPENDENCY_TYPES, _isArray10 = Array.isArray(_iterator10), _i11 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) {
1072 var _ref12;
1073
1074 if (_isArray10) {
1075 if (_i11 >= _iterator10.length) break;
1076 _ref12 = _iterator10[_i11++];
1077 } else {
1078 _i11 = _iterator10.next();
1079 if (_i11.done) break;
1080 _ref12 = _i11.value;
1081 }
1082
1083 const field = _ref12;
1084
1085 if (object[field]) {
1086 object[field] = sortObject(object[field]);
1087 }
1088 }
1089
1090 yield (_fs || _load_fs()).writeFilePreservingEol(loc, JSON.stringify(object, null, indent || (_constants || _load_constants()).DEFAULT_INDENT) + '\n');
1091 }
1092 })();
1093 }
1094
1095 /**
1096 * Call the passed factory (defaults to fs.readJson) and rethrow a pretty error message if it was the result
1097 * of a syntax error.
1098 */
1099
1100 readJson(loc, factory = (_fs || _load_fs()).readJson) {
1101 try {
1102 return factory(loc);
1103 } catch (err) {
1104 if (err instanceof SyntaxError) {
1105 throw new (_errors || _load_errors()).MessageError(this.reporter.lang('jsonError', loc, err.message));
1106 } else {
1107 throw err;
1108 }
1109 }
1110 }
1111
1112 static create(opts = {}, reporter = new (_index3 || _load_index3()).NoopReporter()) {
1113 return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
1114 const config = new Config(reporter);
1115 yield config.init(opts);
1116 return config;
1117 })();
1118 }
1119}
1120
1121exports.default = Config;
1122function extractWorkspaces(manifest) {
1123 if (!manifest || !manifest.workspaces) {
1124 return undefined;
1125 }
1126
1127 if (Array.isArray(manifest.workspaces)) {
1128 return { packages: manifest.workspaces };
1129 }
1130
1131 if (manifest.workspaces.packages && Array.isArray(manifest.workspaces.packages) || manifest.workspaces.nohoist && Array.isArray(manifest.workspaces.nohoist)) {
1132 return manifest.workspaces;
1133 }
1134
1135 return undefined;
1136}
\No newline at end of file