UNPKG

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