'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _semver;

function _load_semver() {
  return _semver = _interopRequireDefault(require('semver'));
}

var _groupArray;

function _load_groupArray() {
  return _groupArray = _interopRequireDefault(require('group-array'));
}

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _chalk;

function _load_chalk() {
  return _chalk = _interopRequireDefault(require('chalk'));
}

var _stringFormat;

function _load_stringFormat() {
  return _stringFormat = _interopRequireDefault(require('string-format'));
}

var _lodash;

function _load_lodash() {
  return _lodash = _interopRequireDefault(require('lodash.partition'));
}

var _consumerLocator;

function _load_consumerLocator() {
  return _consumerLocator = require('./consumer-locator');
}

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('./exceptions');
}

var _driver;

function _load_driver() {
  return _driver = require('../driver');
}

var _driverNotFound;

function _load_driverNotFound() {
  return _driverNotFound = _interopRequireDefault(require('../driver/exceptions/driver-not-found'));
}

var _consumerBitJson;

function _load_consumerBitJson() {
  return _consumerBitJson = _interopRequireDefault(require('./bit-json/consumer-bit-json'));
}

var _bitId;

function _load_bitId() {
  return _bitId = require('../bit-id');
}

var _component;

function _load_component() {
  return _component = _interopRequireDefault(require('./component'));
}

var _constants;

function _load_constants() {
  return _constants = require('../constants');
}

var _scope;

function _load_scope() {
  return _scope = require('../scope');
}

var _consumerMigratorManifest;

function _load_consumerMigratorManifest() {
  return _consumerMigratorManifest = _interopRequireDefault(require('./migrations/consumer-migrator-manifest'));
}

var _consumerMigrator;

function _load_consumerMigrator() {
  return _consumerMigrator = _interopRequireDefault(require('./migrations/consumer-migrator'));
}

var _enrichContextFromGlobal;

function _load_enrichContextFromGlobal() {
  return _enrichContextFromGlobal = _interopRequireDefault(require('../hooks/utils/enrich-context-from-global'));
}

var _loader;

function _load_loader() {
  return _loader = _interopRequireDefault(require('../cli/loader'));
}

var _loaderMessages;

function _load_loaderMessages() {
  return _loaderMessages = require('../cli/loader/loader-messages');
}

var _bitMap;

function _load_bitMap() {
  return _bitMap = _interopRequireDefault(require('./bit-map/bit-map'));
}

var _exceptions2;

function _load_exceptions2() {
  return _exceptions2 = require('./bit-map/exceptions');
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../logger/logger'));
}

var _dirStructure;

function _load_dirStructure() {
  return _dirStructure = _interopRequireDefault(require('./dir-structure/dir-structure'));
}

var _utils;

function _load_utils() {
  return _utils = require('../utils');
}

var _dependencyResolver;

function _load_dependencyResolver() {
  return _dependencyResolver = require('./component/dependencies/dependency-resolver');
}

var _models;

function _load_models() {
  return _models = require('../scope/models');
}

var _missingFilesFromComponent;

function _load_missingFilesFromComponent() {
  return _missingFilesFromComponent = _interopRequireDefault(require('./component/exceptions/missing-files-from-component'));
}

var _componentNotFoundInPath;

function _load_componentNotFoundInPath() {
  return _componentNotFoundInPath = _interopRequireDefault(require('./component/exceptions/component-not-found-in-path'));
}

var _installPackages;

function _load_installPackages() {
  return _installPackages = require('../npm-client/install-packages');
}

var _removedComponents;

function _load_removedComponents() {
  return _removedComponents = require('../scope/removed-components');
}

var _packageJson;

function _load_packageJson() {
  return _packageJson = _interopRequireWildcard(require('./component/package-json'));
}

var _dependencies;

function _load_dependencies() {
  return _dependencies = require('./component/dependencies');
}

var _importComponents;

function _load_importComponents() {
  return _importComponents = _interopRequireDefault(require('./component-ops/import-components'));
}

var _compilerExtension;

function _load_compilerExtension() {
  return _compilerExtension = _interopRequireDefault(require('../extensions/compiler-extension'));
}

var _testerExtension;

function _load_testerExtension() {
  return _testerExtension = _interopRequireDefault(require('../extensions/tester-extension'));
}

var _analytics;

function _load_analytics() {
  return _analytics = require('../analytics/analytics');
}

var _generalError;

function _load_generalError() {
  return _generalError = _interopRequireDefault(require('../error/general-error'));
}

var _tagModelComponent;

function _load_tagModelComponent() {
  return _tagModelComponent = _interopRequireDefault(require('../scope/component-ops/tag-model-component'));
}

var _mainFileRemoved;

function _load_mainFileRemoved() {
  return _mainFileRemoved = _interopRequireDefault(require('./component/exceptions/main-file-removed'));
}

var _extensionFileNotFound;

function _load_extensionFileNotFound() {
  return _extensionFileNotFound = _interopRequireDefault(require('../extensions/exceptions/extension-file-not-found'));
}

var _autoTag;

function _load_autoTag() {
  return _autoTag = require('../scope/component-ops/auto-tag');
}

function _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; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Consumer = function () {
  // args entered by the user in the command line after '--'

  // cache loaded components
  function Consumer(_ref) {
    var projectPath = _ref.projectPath,
        bitJson = _ref.bitJson,
        scope = _ref.scope,
        _ref$created = _ref.created,
        created = _ref$created === undefined ? false : _ref$created,
        _ref$isolated = _ref.isolated,
        isolated = _ref$isolated === undefined ? false : _ref$isolated,
        bitMap = _ref.bitMap,
        addedGitHooks = _ref.addedGitHooks,
        existingGitHooks = _ref.existingGitHooks;

    _classCallCheck(this, Consumer);

    this.isolated = false;
    this._componentsCache = {};
    this._componentsStatusCache = {};
    this.packageManagerArgs = [];

    this.projectPath = projectPath;
    this.bitJson = bitJson;
    this.created = created;
    this.isolated = isolated;
    this.scope = scope;
    this.bitMap = bitMap || (_bitMap || _load_bitMap()).default.load(projectPath);
    this.addedGitHooks = addedGitHooks;
    this.existingGitHooks = existingGitHooks;
    this.warnForMissingDriver();
  } // cache loaded components
  // Mark that the consumer instance is of isolated env and not real
  // list of git hooks added during init process
  // list of git hooks already exists during init process


  _createClass(Consumer, [{
    key: 'getTmpFolder',
    value: function getTmpFolder() {
      var fullPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (!fullPath) {
        return (_constants || _load_constants()).BIT_WORKSPACE_TMP_DIRNAME;
      }
      return (_path || _load_path()).default.join(this.getPath(), (_constants || _load_constants()).BIT_WORKSPACE_TMP_DIRNAME);
    }
  }, {
    key: 'cleanTmpFolder',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee() {
        var tmpPath, exists;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                tmpPath = this.getTmpFolder(true);
                _context.next = 3;
                return (_fsExtra || _load_fsExtra()).default.exists(tmpPath);

              case 3:
                exists = _context.sent;

                if (!exists) {
                  _context.next = 6;
                  break;
                }

                return _context.abrupt('return', (_fsExtra || _load_fsExtra()).default.remove(tmpPath));

              case 6:
                return _context.abrupt('return', null);

              case 7:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function cleanTmpFolder() {
        return _ref2.apply(this, arguments);
      }

      return cleanTmpFolder;
    }()

    /**
     * Check if the driver installed and print message if not
     *
     *
     * @param {any} msg msg to print in case the driver not found (use string-format with the err context)
     * @returns {boolean} true if the driver exists, false otherwise
     * @memberof Consumer
     */

  }, {
    key: 'warnForMissingDriver',
    value: function warnForMissingDriver(msg) {
      try {
        this.driver.getDriver(false);
        return true;
      } catch (err) {
        msg = msg ? (0, (_stringFormat || _load_stringFormat()).default)(msg, err) : `Warning: Bit is not able to run the link command. Please install bit-${err.lang} driver and run the link command.`;
        if (err instanceof (_driverNotFound || _load_driverNotFound()).default) {
          console.log((_chalk || _load_chalk()).default.yellow(msg)); // eslint-disable-line
        }
        throw new (_generalError || _load_generalError()).default(`Failed loading the driver for ${this.bitJson.lang}. Got an error from the driver: ${err}`);
      }
    }

    /**
     * Running migration process for consumer to update the stores (.bit.map.json) to the current version
     *
     * @param {any} verbose - print debug logs
     * @returns {Object} - wether the process run and wether it successeded
     * @memberof Consumer
     */

  }, {
    key: 'migrate',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(verbose) {
        var bitmapVersion, result;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                (_logger || _load_logger()).default.debug('running migration process for consumer');
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('migrate', 'running migration process for consumer');

                // Check version of stores (bitmap / bitjson) to check if we need to run migrate
                // If migration is needed add loader - loader.start(BEFORE_MIGRATION);
                // bitmap migrate
                if (verbose) console.log('running migration process for consumer'); // eslint-disable-line
                // We start to use this process after version 0.10.9, so we assume the scope is in the last production version
                bitmapVersion = this.bitMap.version || '0.10.9';

                if (!(_semver || _load_semver()).default.gte(bitmapVersion, (_constants || _load_constants()).BIT_VERSION)) {
                  _context2.next = 7;
                  break;
                }

                (_logger || _load_logger()).default.debug('bit.map version is up to date');
                return _context2.abrupt('return', {
                  run: false
                });

              case 7:

                (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_MIGRATION);

                _context2.next = 10;
                return (0, (_consumerMigrator || _load_consumerMigrator()).default)(bitmapVersion, (_consumerMigratorManifest || _load_consumerMigratorManifest()).default, this.bitMap, verbose);

              case 10:
                result = _context2.sent;

                result.bitMap.version = (_constants || _load_constants()).BIT_VERSION;
                // mark the bitmap as changed to make sure it persist to FS
                result.bitMap.markAsChanged();
                // Update the version of the bitmap instance of the consumer (to prevent duplicate migration)
                this.bitMap.version = result.bitMap.version;
                _context2.next = 16;
                return result.bitMap.write();

              case 16:

                (_loader || _load_loader()).default.stop();

                return _context2.abrupt('return', {
                  run: true,
                  success: true
                });

              case 18:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function migrate(_x2) {
        return _ref3.apply(this, arguments);
      }

      return migrate;
    }()
  }, {
    key: 'write',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(_ref4) {
        var _ref4$overrideBitJson = _ref4.overrideBitJson,
            overrideBitJson = _ref4$overrideBitJson === undefined ? false : _ref4$overrideBitJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return Promise.all([this.bitJson.write({ bitDir: this.projectPath, throws: false, override: overrideBitJson }), this.scope.ensureDir()]);

              case 2:
                this.bitMap.markAsChanged();
                _context3.next = 5;
                return this.bitMap.write();

              case 5:
                return _context3.abrupt('return', this);

              case 6:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function write(_x3) {
        return _ref5.apply(this, arguments);
      }

      return write;
    }()
  }, {
    key: 'getPath',
    value: function getPath() {
      return this.projectPath;
    }
  }, {
    key: 'toAbsolutePath',
    value: function toAbsolutePath(pathStr) {
      if ((_path || _load_path()).default.isAbsolute(pathStr)) throw new Error(`toAbsolutePath expects relative path, got ${pathStr}`);
      return (_path || _load_path()).default.join(this.projectPath, pathStr);
    }
  }, {
    key: 'getPathRelativeToConsumer',
    value: function getPathRelativeToConsumer(pathToCheck) {
      var absolutePath = (_path || _load_path()).default.resolve(pathToCheck); // if pathToCheck was absolute, it returns it back
      return (_path || _load_path()).default.relative(this.getPath(), absolutePath);
    }
  }, {
    key: 'getParsedId',
    value: function getParsedId(id) {
      // $FlowFixMe, bitId is always defined as shouldThrow is true
      var bitId = this.bitMap.getExistingBitId(id);
      var version = (_bitId || _load_bitId()).BitId.getVersionOnlyFromString(id);
      return bitId.changeVersion(version);
    }
  }, {
    key: 'getParsedIdIfExist',
    value: function getParsedIdIfExist(id) {
      var bitId = this.bitMap.getExistingBitId(id, false);
      if (!bitId) return null;
      var version = (_bitId || _load_bitId()).BitId.getVersionOnlyFromString(id);
      return bitId.changeVersion(version);
    }
  }, {
    key: 'loadComponent',
    value: function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(id) {
        var _ref7, components;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return this.loadComponents((_bitId || _load_bitId()).BitIds.fromArray([id]));

              case 2:
                _ref7 = _context4.sent;
                components = _ref7.components;
                return _context4.abrupt('return', components[0]);

              case 5:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function loadComponent(_x4) {
        return _ref6.apply(this, arguments);
      }

      return loadComponent;
    }()
  }, {
    key: 'loadComponents',
    value: function () {
      var _ref8 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(ids) {
        var _this = this;

        var throwOnFailure = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

        var alreadyLoadedComponents, idsToProcess, invalidComponents, driverExists, components, allComponents, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, componentP, component;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`loading consumer-components from the file-system, ids: ${ids.join(', ')}`);
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('load components', `loading consumer-components from the file-system, ids: ${(_analytics || _load_analytics()).Analytics.hashData(ids)}`);
                alreadyLoadedComponents = [];
                idsToProcess = [];
                invalidComponents = [];

                ids.forEach(function (id) {
                  if (!(id instanceof (_bitId || _load_bitId()).BitId)) {
                    throw new TypeError(`consumer.loadComponents expects to get BitId instances, instead, got "${typeof id}"`);
                  }
                  var idWithoutVersion = id.toStringWithoutVersion();
                  if (_this._componentsCache[idWithoutVersion]) {
                    (_logger || _load_logger()).default.debug(`the component ${idWithoutVersion} has been already loaded, use the cached component`);
                    (_analytics || _load_analytics()).Analytics.addBreadCrumb('load components', `the component ${(_analytics || _load_analytics()).Analytics.hashData(idWithoutVersion)} has been already loaded, use the cached component`);
                    alreadyLoadedComponents.push(_this._componentsCache[idWithoutVersion]);
                  } else {
                    idsToProcess.push(id);
                  }
                });

                if (idsToProcess.length) {
                  _context6.next = 8;
                  break;
                }

                return _context6.abrupt('return', { components: alreadyLoadedComponents, invalidComponents });

              case 8:
                driverExists = this.warnForMissingDriver('Warning: Bit is not be able calculate the dependencies tree. Please install bit-{lang} driver and run commit again.');
                components = idsToProcess.map(function () {
                  var _ref9 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(id) {
                    var idWithConcreteVersion, componentMap, bitDir, componentWithDependenciesFromModel, componentFromModel, component;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            idWithConcreteVersion = (0, (_utils || _load_utils()).getLatestVersionNumber)(_this.bitmapIds, id);
                            componentMap = _this.bitMap.getComponent(idWithConcreteVersion);
                            bitDir = _this.getPath();

                            if (componentMap.rootDir) {
                              bitDir = (_path || _load_path()).default.join(bitDir, componentMap.rootDir);
                            }
                            _context5.next = 6;
                            return _this.scope.getFromLocalIfExist(idWithConcreteVersion);

                          case 6:
                            componentWithDependenciesFromModel = _context5.sent;
                            componentFromModel = componentWithDependenciesFromModel ? componentWithDependenciesFromModel.component : undefined;
                            component = void 0;
                            _context5.prev = 9;
                            _context5.next = 12;
                            return (_component || _load_component()).default.loadFromFileSystem({
                              bitDir,
                              componentMap,
                              id: idWithConcreteVersion,
                              consumer: _this,
                              componentFromModel
                            });

                          case 12:
                            component = _context5.sent;
                            _context5.next = 25;
                            break;

                          case 15:
                            _context5.prev = 15;
                            _context5.t0 = _context5['catch'](9);

                            if (!throwOnFailure) {
                              _context5.next = 19;
                              break;
                            }

                            throw _context5.t0;

                          case 19:

                            (_logger || _load_logger()).default.error(`failed loading ${id} from the file-system`);
                            (_analytics || _load_analytics()).Analytics.addBreadCrumb('load components', `failed loading ${(_analytics || _load_analytics()).Analytics.hashData(id.toString())} from the file-system`);

                            if (!(_component || _load_component()).default.isComponentInvalidByErrorType(_context5.t0)) {
                              _context5.next = 24;
                              break;
                            }

                            invalidComponents.push({ id, error: _context5.t0 });
                            return _context5.abrupt('return', null);

                          case 24:
                            throw _context5.t0;

                          case 25:

                            component.loadedFromFileSystem = true;
                            component.originallySharedDir = componentMap.originallySharedDir || null;
                            // reload component map as it may be changed after calling Component.loadFromFileSystem()
                            component.componentMap = _this.bitMap.getComponent(idWithConcreteVersion);
                            component.componentFromModel = componentFromModel;

                            if (!(!driverExists || componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED)) {
                              _context5.next = 31;
                              break;
                            }

                            return _context5.abrupt('return', component);

                          case 31:
                            _context5.next = 33;
                            return (0, (_dependencyResolver || _load_dependencyResolver()).loadDependenciesForComponent)(component, bitDir, _this, idWithConcreteVersion);

                          case 33:
                            _context5.next = 35;
                            return (0, (_dependencyResolver || _load_dependencyResolver()).updateDependenciesVersions)(_this, component);

                          case 35:
                            return _context5.abrupt('return', component);

                          case 36:
                          case 'end':
                            return _context5.stop();
                        }
                      }
                    }, _callee5, _this, [[9, 15]]);
                  }));

                  return function (_x7) {
                    return _ref9.apply(this, arguments);
                  };
                }());
                allComponents = [];
                _iteratorNormalCompletion = true;
                _didIteratorError = false;
                _iteratorError = undefined;
                _context6.prev = 14;
                _iterator = components[Symbol.iterator]();

              case 16:
                if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
                  _context6.next = 25;
                  break;
                }

                componentP = _step.value;
                _context6.next = 20;
                return componentP;

              case 20:
                component = _context6.sent;
                // eslint-disable-line no-await-in-loop
                if (component) {
                  this._componentsCache[component.id.toStringWithoutVersion()] = component;
                  (_logger || _load_logger()).default.debug(`Finished loading the component, ${component.id.toString()}`);
                  (_analytics || _load_analytics()).Analytics.addBreadCrumb(`Finished loading the component, ${(_analytics || _load_analytics()).Analytics.hashData(component.id.toString())}`);
                  allComponents.push(component);
                }

              case 22:
                _iteratorNormalCompletion = true;
                _context6.next = 16;
                break;

              case 25:
                _context6.next = 31;
                break;

              case 27:
                _context6.prev = 27;
                _context6.t0 = _context6['catch'](14);
                _didIteratorError = true;
                _iteratorError = _context6.t0;

              case 31:
                _context6.prev = 31;
                _context6.prev = 32;

                if (!_iteratorNormalCompletion && _iterator.return) {
                  _iterator.return();
                }

              case 34:
                _context6.prev = 34;

                if (!_didIteratorError) {
                  _context6.next = 37;
                  break;
                }

                throw _iteratorError;

              case 37:
                return _context6.finish(34);

              case 38:
                return _context6.finish(31);

              case 39:
                return _context6.abrupt('return', { components: allComponents.concat(alreadyLoadedComponents), invalidComponents });

              case 40:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this, [[14, 27, 31, 39], [32,, 34, 38]]);
      }));

      function loadComponents(_x6) {
        return _ref8.apply(this, arguments);
      }

      return loadComponents;
    }()
  }, {
    key: 'importComponents',
    value: function importComponents(importOptions) {
      var importComponents = new (_importComponents || _load_importComponents()).default(this, importOptions);
      return importComponents.importComponents();
    }
  }, {
    key: 'importEnvironment',
    value: function importEnvironment(bitId, verbose, dontPrintEnvMsg) {
      return this.scope.installEnvironment({ ids: [{ componentId: bitId }], verbose, dontPrintEnvMsg });
    }

    /**
     * By default, the dists paths are inside the component.
     * If dist attribute is populated in bit.json, the paths are in consumer-root/dist-target.
     */

  }, {
    key: 'shouldDistsBeInsideTheComponent',
    value: function shouldDistsBeInsideTheComponent() {
      return !this.bitJson.distEntry && !this.bitJson.distTarget;
    }
  }, {
    key: 'potentialComponentsForAutoTagging',
    value: function () {
      var _ref10 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(modifiedComponents) {
        var candidateComponents, modifiedComponentsWithoutVersions, idsWithoutModified;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                candidateComponents = this.bitMap.getAllBitIds([(_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED, (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED]);
                modifiedComponentsWithoutVersions = modifiedComponents.map(function (modifiedComponent) {
                  return modifiedComponent.toStringWithoutVersion();
                });
                // if a modified component is in candidates array, remove it from the array as it will be already tagged with the
                // correct version

                idsWithoutModified = candidateComponents.filter(function (component) {
                  return !modifiedComponentsWithoutVersions.includes(component.toStringWithoutVersion());
                });
                return _context7.abrupt('return', (_bitId || _load_bitId()).BitIds.fromArray(idsWithoutModified));

              case 4:
              case 'end':
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      function potentialComponentsForAutoTagging(_x8) {
        return _ref10.apply(this, arguments);
      }

      return potentialComponentsForAutoTagging;
    }()
  }, {
    key: 'listComponentsForAutoTagging',
    value: function () {
      var _ref11 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(modifiedComponents) {
        var candidateComponents;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                _context8.next = 2;
                return this.potentialComponentsForAutoTagging(modifiedComponents);

              case 2:
                candidateComponents = _context8.sent;
                return _context8.abrupt('return', (0, (_autoTag || _load_autoTag()).getAutoTagPending)(this.scope, candidateComponents, modifiedComponents));

              case 4:
              case 'end':
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));

      function listComponentsForAutoTagging(_x9) {
        return _ref11.apply(this, arguments);
      }

      return listComponentsForAutoTagging;
    }()

    /**
     * Check whether a model representation and file-system representation of the same component is the same.
     * The way how it is done is by converting the file-system representation of the component into
     * a Version object. Once this is done, we have two Version objects, and we can compare their hashes
     */

  }, {
    key: 'isComponentModified',
    value: function () {
      var _ref12 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(componentFromModel, componentFromFileSystem) {
        var componentMap, _ref13, version, copyDependenciesVersionsFromModelToFS;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                if (!(typeof componentFromFileSystem._isModified === 'undefined')) {
                  _context9.next = 27;
                  break;
                }

                componentMap = this.bitMap.getComponent(componentFromFileSystem.id);

                if (componentMap.originallySharedDir) {
                  componentFromFileSystem.originallySharedDir = componentMap.originallySharedDir;
                }
                _context9.next = 5;
                return this.scope.sources.consumerComponentToVersion({
                  consumerComponent: componentFromFileSystem,
                  versionFromModel: componentFromModel
                });

              case 5:
                _ref13 = _context9.sent;
                version = _ref13.version;


                version.log = componentFromModel.log; // ignore the log, it's irrelevant for the comparison

                // sometime dependencies from the FS don't have an exact version.

                copyDependenciesVersionsFromModelToFS = function copyDependenciesVersionsFromModelToFS(dependenciesFS, dependenciesModel) {
                  dependenciesFS.get().forEach(function (dependency) {
                    var idWithoutVersion = dependency.id.toStringWithoutVersion();
                    var dependencyFromModel = dependenciesModel.get().find(function (modelDependency) {
                      return modelDependency.id.toStringWithoutVersion() === idWithoutVersion;
                    });
                    if (dependencyFromModel && !dependency.id.hasVersion()) {
                      dependency.id = dependencyFromModel.id;
                    }
                  });
                };

                copyDependenciesVersionsFromModelToFS(version.dependencies, componentFromModel.dependencies);
                copyDependenciesVersionsFromModelToFS(version.devDependencies, componentFromModel.devDependencies);
                copyDependenciesVersionsFromModelToFS(version.compilerDependencies, componentFromModel.compilerDependencies);
                copyDependenciesVersionsFromModelToFS(version.testerDependencies, componentFromModel.testerDependencies);

                // sort the files by 'relativePath' because the order can be changed when adding or renaming
                // files in bitmap, which affects later on the model.
                version.files = (_ramda || _load_ramda()).default.sortBy((_ramda || _load_ramda()).default.prop('relativePath'), version.files);
                componentFromModel.files = (_ramda || _load_ramda()).default.sortBy((_ramda || _load_ramda()).default.prop('relativePath'), componentFromModel.files);

                version.packageDependencies = (0, (_utils || _load_utils()).sortObject)(version.packageDependencies);
                version.devPackageDependencies = (0, (_utils || _load_utils()).sortObject)(version.devPackageDependencies);
                version.compilerPackageDependencies = (0, (_utils || _load_utils()).sortObject)(version.compilerPackageDependencies);
                version.testerPackageDependencies = (0, (_utils || _load_utils()).sortObject)(version.testerPackageDependencies);
                version.peerPackageDependencies = (0, (_utils || _load_utils()).sortObject)(version.peerPackageDependencies);
                componentFromModel.packageDependencies = (0, (_utils || _load_utils()).sortObject)(componentFromModel.packageDependencies);
                componentFromModel.devPackageDependencies = (0, (_utils || _load_utils()).sortObject)(componentFromModel.devPackageDependencies);
                componentFromModel.compilerPackageDependencies = (0, (_utils || _load_utils()).sortObject)(componentFromModel.compilerPackageDependencies);
                componentFromModel.testerPackageDependencies = (0, (_utils || _load_utils()).sortObject)(componentFromModel.testerPackageDependencies);
                componentFromModel.peerPackageDependencies = (0, (_utils || _load_utils()).sortObject)(componentFromModel.peerPackageDependencies);
                // prefix your command with "BIT_LOG=*" to see the actual id changes
                if (process.env.BIT_LOG && componentFromModel.hash().hash !== version.hash().hash) {
                  console.log('-------------------componentFromModel------------------------'); // eslint-disable-line no-console
                  console.log(componentFromModel.id()); // eslint-disable-line no-console
                  console.log('------------------------componentFromFileSystem (version)----'); // eslint-disable-line no-console
                  console.log(version.id()); // eslint-disable-line no-console
                  console.log('-------------------------END---------------------------------'); // eslint-disable-line no-console
                }
                componentFromFileSystem._isModified = componentFromModel.hash().hash !== version.hash().hash;

              case 27:
                return _context9.abrupt('return', componentFromFileSystem._isModified);

              case 28:
              case 'end':
                return _context9.stop();
            }
          }
        }, _callee9, this);
      }));

      function isComponentModified(_x10, _x11) {
        return _ref12.apply(this, arguments);
      }

      return isComponentModified;
    }()

    /**
     * Get a component status by ID. Return a ComponentStatus object.
     * Keep in mind that a result can be a partial object of ComponentStatus, e.g. { notExist: true }.
     * Each one of the ComponentStatus properties can be undefined, true or false.
     * As a result, in order to check whether a component is not modified use (status.modified === false).
     * Don't use (!status.modified) because a component may not exist and the status.modified will be undefined.
     *
     * The status may have 'true' for several properties. For example, a component can be staged and modified at the
     * same time.
     *
     * The result is cached per ID and can be called several times with no penalties.
     */

  }, {
    key: 'getComponentStatusById',
    value: function () {
      var _ref14 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11(id) {
        var _this2 = this;

        var getStatus;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                getStatus = function () {
                  var _ref15 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10() {
                    var status, componentFromModel, componentFromFileSystem, versionFromFs, versionRef, versionFromModel;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee10$(_context10) {
                      while (1) {
                        switch (_context10.prev = _context10.next) {
                          case 0:
                            status = {};
                            _context10.next = 3;
                            return _this2.scope.sources.get(id);

                          case 3:
                            componentFromModel = _context10.sent;
                            componentFromFileSystem = void 0;
                            _context10.prev = 5;
                            _context10.next = 8;
                            return _this2.loadComponent(id.changeVersion(null));

                          case 8:
                            componentFromFileSystem = _context10.sent;
                            _context10.next = 17;
                            break;

                          case 11:
                            _context10.prev = 11;
                            _context10.t0 = _context10['catch'](5);

                            if (!(_context10.t0 instanceof (_missingFilesFromComponent || _load_missingFilesFromComponent()).default || _context10.t0 instanceof (_componentNotFoundInPath || _load_componentNotFoundInPath()).default || _context10.t0 instanceof (_exceptions2 || _load_exceptions2()).MissingBitMapComponent)) {
                              _context10.next = 16;
                              break;
                            }

                            // the file/s have been deleted or the component doesn't exist in bit.map file
                            if (componentFromModel) status.deleted = true;else status.notExist = true;
                            return _context10.abrupt('return', status);

                          case 16:
                            throw _context10.t0;

                          case 17:
                            if (componentFromModel) {
                              _context10.next = 20;
                              break;
                            }

                            status.newlyCreated = true;
                            return _context10.abrupt('return', status);

                          case 20:
                            if (!(componentFromFileSystem.componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED)) {
                              _context10.next = 23;
                              break;
                            }

                            status.nested = true;
                            return _context10.abrupt('return', status);

                          case 23:
                            status.staged = componentFromModel.isLocallyChanged();
                            versionFromFs = componentFromFileSystem.id.version;

                            if (!(!status.staged && !componentFromFileSystem.id.hasVersion())) {
                              _context10.next = 27;
                              break;
                            }

                            throw new (_generalError || _load_generalError()).default(`component ${id} has an invalid state.
           1) it has a model instance so it's not new.
           2) it's not in staged state.
           3) it doesn't have a version in the bitmap file.
           Maybe the component was interrupted during the export and as a result the bitmap file wasn't updated with the new version
           `);

                          case 27:
                            // TODO: instead of doing that like this we should use:
                            // const versionFromModel = await componentFromModel.loadVersion(versionFromFs, this.scope.objects);
                            // it looks like it's exactly the same code but it's not working from some reason
                            versionRef = componentFromModel.versions[versionFromFs];

                            if (versionRef) {
                              _context10.next = 30;
                              break;
                            }

                            throw new (_generalError || _load_generalError()).default(`version ${versionFromFs} was not found in ${id}`);

                          case 30:
                            _context10.next = 32;
                            return _this2.scope.getObject(versionRef.hash);

                          case 32:
                            versionFromModel = _context10.sent;
                            _context10.next = 35;
                            return _this2.isComponentModified(versionFromModel, componentFromFileSystem);

                          case 35:
                            status.modified = _context10.sent;
                            return _context10.abrupt('return', status);

                          case 37:
                          case 'end':
                            return _context10.stop();
                        }
                      }
                    }, _callee10, _this2, [[5, 11]]);
                  }));

                  return function getStatus() {
                    return _ref15.apply(this, arguments);
                  };
                }();

                if (this._componentsStatusCache[id.toString()]) {
                  _context11.next = 5;
                  break;
                }

                _context11.next = 4;
                return getStatus();

              case 4:
                this._componentsStatusCache[id.toString()] = _context11.sent;

              case 5:
                return _context11.abrupt('return', this._componentsStatusCache[id.toString()]);

              case 6:
              case 'end':
                return _context11.stop();
            }
          }
        }, _callee11, this);
      }));

      function getComponentStatusById(_x12) {
        return _ref14.apply(this, arguments);
      }

      return getComponentStatusById;
    }()
  }, {
    key: 'tag',
    value: function () {
      var _ref16 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(ids, message, exactVersion, releaseType, force, verbose, ignoreUnresolvedDependencies, ignoreNewestVersion) {
        var _this3 = this;

        var skipTests = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : false;

        var _ref17, components, componentsWithMissingDeps, _ref18, taggedComponents, autoTaggedComponents, taggedComponentIds, autoTaggedComponentIds, allComponentIds, updatePackageJsonP;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee12$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`committing the following components: ${ids.toString()}`);
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('tag', `committing the following components: ${(_analytics || _load_analytics()).Analytics.hashData(ids)}`);
                _context12.next = 4;
                return this.loadComponents(ids);

              case 4:
                _ref17 = _context12.sent;
                components = _ref17.components;

                if (ignoreUnresolvedDependencies) {
                  _context12.next = 10;
                  break;
                }

                componentsWithMissingDeps = components.filter(function (component) {
                  return Boolean(component.issues);
                });

                if ((_ramda || _load_ramda()).default.isEmpty(componentsWithMissingDeps)) {
                  _context12.next = 10;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).MissingDependencies(componentsWithMissingDeps);

              case 10:
                _context12.next = 12;
                return (0, (_tagModelComponent || _load_tagModelComponent()).default)({
                  consumerComponents: components,
                  scope: this.scope,
                  message,
                  exactVersion,
                  releaseType,
                  force,
                  consumer: this,
                  ignoreNewestVersion,
                  skipTests,
                  verbose
                });

              case 12:
                _ref18 = _context12.sent;
                taggedComponents = _ref18.taggedComponents;
                autoTaggedComponents = _ref18.autoTaggedComponents;


                // update bitmap with the new version
                taggedComponentIds = taggedComponents.map(function (component) {
                  _this3.bitMap.updateComponentId(component.id);
                  var _component$pendingVer = component.pendingVersion,
                      detachedCompiler = _component$pendingVer.detachedCompiler,
                      detachedTester = _component$pendingVer.detachedTester;

                  _this3.bitMap.setDetachedCompilerAndTester(component.id, { detachedCompiler, detachedTester });
                  return component.id;
                });
                autoTaggedComponentIds = autoTaggedComponents.map(function (component) {
                  var id = component.toBitId();
                  var newId = id.changeVersion(component.latest());
                  _this3.bitMap.updateComponentId(newId);
                  return newId;
                });

                // update package.json with the new version

                allComponentIds = taggedComponentIds.concat(autoTaggedComponentIds);
                updatePackageJsonP = allComponentIds.map(function (componentId) {
                  var componentMap = _this3.bitMap.getComponent(componentId);
                  if (componentMap.rootDir) {
                    return (_packageJson || _load_packageJson()).updateAttribute(_this3, componentMap.rootDir, 'version', componentId.version);
                  }
                  return null;
                });
                _context12.next = 21;
                return Promise.all(updatePackageJsonP);

              case 21:
                return _context12.abrupt('return', { taggedComponents, autoTaggedComponents });

              case 22:
              case 'end':
                return _context12.stop();
            }
          }
        }, _callee12, this);
      }));

      function tag(_x14, _x15, _x16, _x17, _x18, _x19, _x20, _x21) {
        return _ref16.apply(this, arguments);
      }

      return tag;
    }()
  }, {
    key: 'getComponentIdFromNodeModulesPath',
    value: function getComponentIdFromNodeModulesPath(requirePath, bindingPrefix) {
      requirePath = (0, (_utils || _load_utils()).pathNormalizeToLinux)(requirePath);
      // Temp fix to support old components before the migration has been running
      bindingPrefix = bindingPrefix === 'bit' ? '@bit' : bindingPrefix;
      var prefix = requirePath.includes('node_modules') ? `node_modules/${bindingPrefix}/` : `${bindingPrefix}/`;
      var withoutPrefix = requirePath.substr(requirePath.indexOf(prefix) + prefix.length);
      var componentName = withoutPrefix.includes('/') ? withoutPrefix.substr(0, withoutPrefix.indexOf('/')) : withoutPrefix;
      var pathSplit = componentName.split((_constants || _load_constants()).NODE_PATH_COMPONENT_SEPARATOR);
      if (pathSplit.length < 2) throw new (_generalError || _load_generalError()).default(`component has an invalid require statement: ${requirePath}`);
      // since the dynamic namespaces feature introduced, the require statement doesn't have a fixed
      // number of separators.
      // also, a scope name may or may not include a dot. depends whether it's on bitHub or self hosted.
      // we must check against BitMap to get the correct scope and name of the id.
      if (pathSplit.length === 2) {
        return new (_bitId || _load_bitId()).BitId({ scope: pathSplit[0], name: pathSplit[1] });
      }
      var mightBeScope = (_ramda || _load_ramda()).default.head(pathSplit);
      var mightBeName = (_ramda || _load_ramda()).default.tail(pathSplit).join('/');
      var mightBeId = new (_bitId || _load_bitId()).BitId({ scope: mightBeScope, name: mightBeName });
      var allBitIds = this.bitMap.getAllBitIds();
      if (allBitIds.searchWithoutVersion(mightBeId)) return mightBeId;

      // pathSplit has 3 or more items. the first two are the scope, the rest is the name.
      // for example "user.scopeName.utils.is-string" => scope: user.scopeName, name: utils/is-string
      var scope = pathSplit.splice(0, 2).join('.');
      var name = pathSplit.join('/');
      return new (_bitId || _load_bitId()).BitId({ scope, name });
    }
  }, {
    key: 'composeRelativeBitPath',
    value: function composeRelativeBitPath(bitId) {
      var componentsDefaultDirectory = this.dirStructure.componentsDefaultDirectory;

      return (0, (_stringFormat || _load_stringFormat()).default)(componentsDefaultDirectory, { name: bitId.name, scope: bitId.scope });
    }
  }, {
    key: 'composeComponentPath',
    value: function composeComponentPath(bitId) {
      var addToPath = [this.getPath(), this.composeRelativeBitPath(bitId)];
      (_logger || _load_logger()).default.debug(`component dir path: ${addToPath.join('/')}`);
      (_analytics || _load_analytics()).Analytics.addBreadCrumb('composeComponentPath', `component dir path: ${(_analytics || _load_analytics()).Analytics.hashData(addToPath.join('/'))}`);
      return (_path || _load_path()).default.join.apply((_path || _load_path()).default, addToPath);
    }
  }, {
    key: 'composeDependencyPath',
    value: function composeDependencyPath(bitId) {
      var dependenciesDir = this.dirStructure.dependenciesDirStructure;
      return (_path || _load_path()).default.join(this.getPath(), dependenciesDir, bitId.toFullPath());
    }
  }, {
    key: 'deprecateRemote',
    value: function () {
      var _ref19 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee14(bitIds) {
        var _this4 = this;

        var groupedBitsByScope, remotes, context, deprecateP, deprecatedComponentsResult;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee14$(_context14) {
          while (1) {
            switch (_context14.prev = _context14.next) {
              case 0:
                groupedBitsByScope = (0, (_groupArray || _load_groupArray()).default)(bitIds, 'scope');
                _context14.next = 3;
                return this.scope.remotes();

              case 3:
                remotes = _context14.sent;
                context = {};

                (0, (_enrichContextFromGlobal || _load_enrichContextFromGlobal()).default)(context);
                deprecateP = Object.keys(groupedBitsByScope).map(function () {
                  var _ref20 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee13(scopeName) {
                    var resolvedRemote, idsStr, deprecateResult;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee13$(_context13) {
                      while (1) {
                        switch (_context13.prev = _context13.next) {
                          case 0:
                            _context13.next = 2;
                            return remotes.resolve(scopeName, _this4.scope);

                          case 2:
                            resolvedRemote = _context13.sent;
                            idsStr = groupedBitsByScope[scopeName].map(function (id) {
                              return id.toStringWithoutVersion();
                            });
                            _context13.next = 6;
                            return resolvedRemote.deprecateMany(idsStr, context);

                          case 6:
                            deprecateResult = _context13.sent;
                            return _context13.abrupt('return', deprecateResult);

                          case 8:
                          case 'end':
                            return _context13.stop();
                        }
                      }
                    }, _callee13, _this4);
                  }));

                  return function (_x23) {
                    return _ref20.apply(this, arguments);
                  };
                }());
                _context14.next = 9;
                return Promise.all(deprecateP);

              case 9:
                deprecatedComponentsResult = _context14.sent;
                return _context14.abrupt('return', deprecatedComponentsResult);

              case 11:
              case 'end':
                return _context14.stop();
            }
          }
        }, _callee14, this);
      }));

      function deprecateRemote(_x22) {
        return _ref19.apply(this, arguments);
      }

      return deprecateRemote;
    }()
  }, {
    key: 'deprecateLocal',
    value: function () {
      var _ref21 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee15(bitIds) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee15$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                return _context15.abrupt('return', this.scope.deprecateMany(bitIds));

              case 1:
              case 'end':
                return _context15.stop();
            }
          }
        }, _callee15, this);
      }));

      function deprecateLocal(_x24) {
        return _ref21.apply(this, arguments);
      }

      return deprecateLocal;
    }()
  }, {
    key: 'deprecate',
    value: function () {
      var _ref22 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee16(bitIds, remote) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee16$(_context16) {
          while (1) {
            switch (_context16.prev = _context16.next) {
              case 0:
                return _context16.abrupt('return', remote ? this.deprecateRemote(bitIds) : this.deprecateLocal(bitIds));

              case 1:
              case 'end':
                return _context16.stop();
            }
          }
        }, _callee16, this);
      }));

      function deprecate(_x25, _x26) {
        return _ref22.apply(this, arguments);
      }

      return deprecate;
    }()

    /**
     * Remove components local and remote
     * splits array of ids into local and remote and removes according to flags
     * @param {string[]} ids - list of remote component ids to delete
     * @param {boolean} force - delete component that are used by other components.
     * @param {boolean} remote - delete component from a remote scope
     * @param {boolean} track - keep tracking local staged components in bitmap.
     * @param {boolean} deleteFiles - delete local added files from fs.
     */

  }, {
    key: 'remove',
    value: function () {
      var _ref24 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee17(_ref23) {
        var ids = _ref23.ids,
            force = _ref23.force,
            remote = _ref23.remote,
            track = _ref23.track,
            deleteFiles = _ref23.deleteFiles;

        var bitIds, _partition, _partition2, localIds, remoteIds, remoteResult, localResult;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee17$(_context17) {
          while (1) {
            switch (_context17.prev = _context17.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`consumer.remove: ${ids.toString()}. force: ${force.toString()}`);
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('remove', `consumer.remove: ${(_analytics || _load_analytics()).Analytics.hashData(ids)}. force: ${(_analytics || _load_analytics()).Analytics.hashData(force.toString())}`);
                // added this to remove support for remove version
                bitIds = (_bitId || _load_bitId()).BitIds.fromArray(ids.map(function (id) {
                  return id.changeVersion((_constants || _load_constants()).LATEST_BIT_VERSION);
                }));
                _partition = (0, (_lodash || _load_lodash()).default)(bitIds, function (id) {
                  return id.isLocal();
                }), _partition2 = _slicedToArray(_partition, 2), localIds = _partition2[0], remoteIds = _partition2[1];

                if (!(remote && localIds.length)) {
                  _context17.next = 6;
                  break;
                }

                throw new (_generalError || _load_generalError()).default(`unable to remove the remote components: ${localIds.join(',')} as they don't contain a scope-name`);

              case 6:
                if (!(remote && !(_ramda || _load_ramda()).default.isEmpty(remoteIds))) {
                  _context17.next = 12;
                  break;
                }

                _context17.next = 9;
                return this.removeRemote(remoteIds, force);

              case 9:
                _context17.t0 = _context17.sent;
                _context17.next = 13;
                break;

              case 12:
                _context17.t0 = [];

              case 13:
                remoteResult = _context17.t0;

                if (remote) {
                  _context17.next = 20;
                  break;
                }

                _context17.next = 17;
                return this.removeLocal(bitIds, force, track, deleteFiles);

              case 17:
                _context17.t1 = _context17.sent;
                _context17.next = 21;
                break;

              case 20:
                _context17.t1 = new (_removedComponents || _load_removedComponents()).RemovedLocalObjects();

              case 21:
                localResult = _context17.t1;
                return _context17.abrupt('return', { localResult, remoteResult });

              case 23:
              case 'end':
                return _context17.stop();
            }
          }
        }, _callee17, this);
      }));

      function remove(_x27) {
        return _ref24.apply(this, arguments);
      }

      return remove;
    }()

    /**
     * Remove remote component from ssh server
     * this method groups remote components by remote name and deletes remote components together
     * @param {BitIds} bitIds - list of remote component ids to delete
     * @param {boolean} force - delete component that are used by other components.
     */

  }, {
    key: 'removeRemote',
    value: function () {
      var _ref25 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee19(bitIds, force) {
        var _this5 = this;

        var groupedBitsByScope, remotes, context, removeP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee19$(_context19) {
          while (1) {
            switch (_context19.prev = _context19.next) {
              case 0:
                groupedBitsByScope = (0, (_groupArray || _load_groupArray()).default)(bitIds, 'scope');
                _context19.next = 3;
                return this.scope.remotes();

              case 3:
                remotes = _context19.sent;
                context = {};

                (0, (_enrichContextFromGlobal || _load_enrichContextFromGlobal()).default)(context);
                removeP = Object.keys(groupedBitsByScope).map(function () {
                  var _ref26 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee18(key) {
                    var resolvedRemote, idsStr;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee18$(_context18) {
                      while (1) {
                        switch (_context18.prev = _context18.next) {
                          case 0:
                            _context18.next = 2;
                            return remotes.resolve(key, _this5.scope);

                          case 2:
                            resolvedRemote = _context18.sent;
                            idsStr = groupedBitsByScope[key].map(function (id) {
                              return id.toStringWithoutVersion();
                            });
                            return _context18.abrupt('return', resolvedRemote.deleteMany(idsStr, force, context));

                          case 5:
                          case 'end':
                            return _context18.stop();
                        }
                      }
                    }, _callee18, _this5);
                  }));

                  return function (_x30) {
                    return _ref26.apply(this, arguments);
                  };
                }());
                return _context19.abrupt('return', Promise.all(removeP));

              case 8:
              case 'end':
                return _context19.stop();
            }
          }
        }, _callee19, this);
      }));

      function removeRemote(_x28, _x29) {
        return _ref25.apply(this, arguments);
      }

      return removeRemote;
    }()
    /**
     * delete files from fs according to imported/created
     * @param {BitIds} bitIds - list of remote component ids to delete
     * @param {boolean} deleteFiles - delete component that are used by other components.
     */

  }, {
    key: 'removeComponentFromFs',
    value: function () {
      var _ref27 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee22(bitIds, deleteFiles) {
        var _this6 = this;

        var deletePath;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee22$(_context22) {
          while (1) {
            switch (_context22.prev = _context22.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`consumer.removeComponentFromFs, ids: ${bitIds.toString()}`);

                deletePath = function () {
                  var _ref28 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee20(pathToDelete) {
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee20$(_context20) {
                      while (1) {
                        switch (_context20.prev = _context20.next) {
                          case 0:
                            (_logger || _load_logger()).default.debug(`consumer.removeComponentFromFs deleting the following path: ${pathToDelete}`);
                            return _context20.abrupt('return', (_fsExtra || _load_fsExtra()).default.remove(pathToDelete));

                          case 2:
                          case 'end':
                            return _context20.stop();
                        }
                      }
                    }, _callee20, _this6);
                  }));

                  return function deletePath(_x33) {
                    return _ref28.apply(this, arguments);
                  };
                }();

                return _context22.abrupt('return', Promise.all(bitIds.map(function () {
                  var _ref29 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee21(id) {
                    var ignoreVersion, componentMap;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee21$(_context21) {
                      while (1) {
                        switch (_context21.prev = _context21.next) {
                          case 0:
                            ignoreVersion = id.isLocal() || !id.hasVersion();
                            componentMap = _this6.bitMap.getComponentIfExist(id, { ignoreVersion });

                            if (componentMap) {
                              _context21.next = 5;
                              break;
                            }

                            (_logger || _load_logger()).default.warn(`removeComponentFromFs wasn't able to delete ${id.toString()} because the id is missing from bitmap`);
                            return _context21.abrupt('return', null);

                          case 5:
                            if (!(componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED || componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED)) {
                              _context21.next = 9;
                              break;
                            }

                            return _context21.abrupt('return', deletePath((_path || _load_path()).default.join(_this6.getPath(), componentMap.rootDir)));

                          case 9:
                            if (!(componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED && deleteFiles)) {
                              _context21.next = 11;
                              break;
                            }

                            return _context21.abrupt('return', Promise.all(componentMap.files.map(function (file) {
                              return deletePath(file.relativePath);
                            })));

                          case 11:
                            return _context21.abrupt('return', null);

                          case 12:
                          case 'end':
                            return _context21.stop();
                        }
                      }
                    }, _callee21, _this6);
                  }));

                  return function (_x34) {
                    return _ref29.apply(this, arguments);
                  };
                }())));

              case 3:
              case 'end':
                return _context22.stop();
            }
          }
        }, _callee22, this);
      }));

      function removeComponentFromFs(_x31, _x32) {
        return _ref27.apply(this, arguments);
      }

      return removeComponentFromFs;
    }()
    /**
     * resolveLocalComponentIds - method is used for resolving local component ids
     * imported = bit.remote/utils/is-string
     * local = utils/is-string
     * if component is imported then cant remove version only component
     * @param {BitIds} bitIds - list of remote component ids to delete
     */

  }, {
    key: 'resolveLocalComponentIds',
    value: function resolveLocalComponentIds(bitIds) {
      var _this7 = this;

      return bitIds.map(function (id) {
        var realBitId = _this7.bitMap.getBitIdIfExist(id, { ignoreVersion: true });
        if (!realBitId) return id;
        var componentMap = _this7.bitMap.getComponent(realBitId);
        if (componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED || componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED) {
          return realBitId.changeVersion((_constants || _load_constants()).LATEST_BIT_VERSION);
        }
        return realBitId;
      });
    }

    /**
     * cleanBitMapAndBitJson - clean up removed components from bitmap and bit.json file
     * @param {BitIds} componentsToRemoveFromFs - delete component that are used by other components.
     * @param {BitIds} removedDependencies - delete component that are used by other components.
     */

  }, {
    key: 'cleanBitMapAndBitJson',
    value: function () {
      var _ref30 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee23(componentsToRemoveFromFs, removedDependencies) {
        var bitJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee23$(_context23) {
          while (1) {
            switch (_context23.prev = _context23.next) {
              case 0:
                bitJson = this.bitJson;

                this.bitMap.removeComponents(componentsToRemoveFromFs);
                this.bitMap.removeComponents(removedDependencies);
                componentsToRemoveFromFs.map(function (x) {
                  return delete bitJson.dependencies[x.toStringWithoutVersion()];
                });
                _context23.next = 6;
                return bitJson.write({ bitDir: this.projectPath });

              case 6:
              case 'end':
                return _context23.stop();
            }
          }
        }, _callee23, this);
      }));

      function cleanBitMapAndBitJson(_x35, _x36) {
        return _ref30.apply(this, arguments);
      }

      return cleanBitMapAndBitJson;
    }()
    /**
     * removeLocal - remove local (imported, new staged components) from modules and bitmap according to flags
     * @param {BitIds} bitIds - list of remote component ids to delete
     * @param {boolean} force - delete component that are used by other components.
     * @param {boolean} deleteFiles - delete component that are used by other components.
     */

  }, {
    key: 'removeLocal',
    value: function () {
      var _ref31 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee25(bitIds, force, track, deleteFiles) {
        var _this8 = this;

        var modifiedComponents, regularComponents, resolvedIDs, _ref33, removedComponentIds, missingComponents, dependentBits, removedDependencies, componentsToRemoveFromFs;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee25$(_context25) {
          while (1) {
            switch (_context25.prev = _context25.next) {
              case 0:
                // local remove in case user wants to delete tagged components
                modifiedComponents = new (_bitId || _load_bitId()).BitIds();
                regularComponents = new (_bitId || _load_bitId()).BitIds();
                resolvedIDs = this.resolveLocalComponentIds(bitIds);

                if (!(_ramda || _load_ramda()).default.isEmpty(resolvedIDs)) {
                  _context25.next = 5;
                  break;
                }

                return _context25.abrupt('return', new (_removedComponents || _load_removedComponents()).RemovedLocalObjects());

              case 5:
                if (force) {
                  _context25.next = 8;
                  break;
                }

                _context25.next = 8;
                return Promise.all(resolvedIDs.map(function () {
                  var _ref32 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee24(id) {
                    var componentStatus;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee24$(_context24) {
                      while (1) {
                        switch (_context24.prev = _context24.next) {
                          case 0:
                            _context24.prev = 0;
                            _context24.next = 3;
                            return _this8.getComponentStatusById(id);

                          case 3:
                            componentStatus = _context24.sent;

                            if (componentStatus.modified) modifiedComponents.push(id);else regularComponents.push(id);
                            _context24.next = 14;
                            break;

                          case 7:
                            _context24.prev = 7;
                            _context24.t0 = _context24['catch'](0);

                            if (!(_component || _load_component()).default.isComponentInvalidByErrorType(_context24.t0)) {
                              _context24.next = 13;
                              break;
                            }

                            regularComponents.push(id);
                            _context24.next = 14;
                            break;

                          case 13:
                            throw _context24.t0;

                          case 14:
                          case 'end':
                            return _context24.stop();
                        }
                      }
                    }, _callee24, _this8, [[0, 7]]);
                  }));

                  return function (_x41) {
                    return _ref32.apply(this, arguments);
                  };
                }()));

              case 8:
                _context25.next = 10;
                return this.scope.removeMany(force ? resolvedIDs : regularComponents, force, true, this);

              case 10:
                _ref33 = _context25.sent;
                removedComponentIds = _ref33.removedComponentIds;
                missingComponents = _ref33.missingComponents;
                dependentBits = _ref33.dependentBits;
                removedDependencies = _ref33.removedDependencies;
                componentsToRemoveFromFs = (_bitId || _load_bitId()).BitIds.fromArray(removedComponentIds.filter(function (id) {
                  return id.version === (_constants || _load_constants()).LATEST_BIT_VERSION;
                }));

                if ((_ramda || _load_ramda()).default.isEmpty(removedComponentIds)) {
                  _context25.next = 21;
                  break;
                }

                _context25.next = 19;
                return this.removeComponentFromFs(componentsToRemoveFromFs, deleteFiles);

              case 19:
                _context25.next = 21;
                return this.removeComponentFromFs(removedDependencies, false);

              case 21:
                if (!((!track || deleteFiles) && !(_ramda || _load_ramda()).default.isEmpty(removedComponentIds))) {
                  _context25.next = 26;
                  break;
                }

                _context25.next = 24;
                return (_packageJson || _load_packageJson()).removeComponentsFromWorkspacesAndDependencies(this, this.getPath(), this.bitMap, componentsToRemoveFromFs);

              case 24:
                _context25.next = 26;
                return this.cleanBitMapAndBitJson(componentsToRemoveFromFs, removedDependencies);

              case 26:
                return _context25.abrupt('return', new (_removedComponents || _load_removedComponents()).RemovedLocalObjects(removedComponentIds, missingComponents, modifiedComponents, removedDependencies, dependentBits));

              case 27:
              case 'end':
                return _context25.stop();
            }
          }
        }, _callee25, this);
      }));

      function removeLocal(_x37, _x38, _x39, _x40) {
        return _ref31.apply(this, arguments);
      }

      return removeLocal;
    }()
  }, {
    key: 'addRemoteAndLocalVersionsToDependencies',
    value: function () {
      var _ref34 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee26(component, loadedFromFileSystem) {
        var modelDependencies, modelDevDependencies, modelCompilerDependencies, modelTesterDependencies, mainComponentFromModel;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee26$(_context26) {
          while (1) {
            switch (_context26.prev = _context26.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`addRemoteAndLocalVersionsToDependencies for ${component.id.toString()}`);
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('addRemoteAndLocalVersionsToDependencies', `addRemoteAndLocalVersionsToDependencies for ${(_analytics || _load_analytics()).Analytics.hashData(component.id.toString())}`);
                modelDependencies = new (_dependencies || _load_dependencies()).Dependencies([]);
                modelDevDependencies = new (_dependencies || _load_dependencies()).Dependencies([]);
                modelCompilerDependencies = new (_dependencies || _load_dependencies()).Dependencies([]);
                modelTesterDependencies = new (_dependencies || _load_dependencies()).Dependencies([]);

                if (!loadedFromFileSystem) {
                  _context26.next = 19;
                  break;
                }

                _context26.prev = 7;
                _context26.next = 10;
                return this.scope.loadRemoteComponent(component.id);

              case 10:
                mainComponentFromModel = _context26.sent;

                modelDependencies = mainComponentFromModel.dependencies;
                modelDevDependencies = mainComponentFromModel.devDependencies;
                modelCompilerDependencies = mainComponentFromModel.compilerDependencies;
                modelTesterDependencies = mainComponentFromModel.testerDependencies;
                _context26.next = 19;
                break;

              case 17:
                _context26.prev = 17;
                _context26.t0 = _context26['catch'](7);

              case 19:
                _context26.next = 21;
                return component.dependencies.addRemoteAndLocalVersions(this.scope, modelDependencies);

              case 21:
                _context26.next = 23;
                return component.devDependencies.addRemoteAndLocalVersions(this.scope, modelDevDependencies);

              case 23:
                _context26.next = 25;
                return component.compilerDependencies.addRemoteAndLocalVersions(this.scope, modelCompilerDependencies);

              case 25:
                _context26.next = 27;
                return component.testerDependencies.addRemoteAndLocalVersions(this.scope, modelTesterDependencies);

              case 27:
              case 'end':
                return _context26.stop();
            }
          }
        }, _callee26, this, [[7, 17]]);
      }));

      function addRemoteAndLocalVersionsToDependencies(_x42, _x43) {
        return _ref34.apply(this, arguments);
      }

      return addRemoteAndLocalVersionsToDependencies;
    }()
  }, {
    key: 'eject',
    value: function () {
      var _ref35 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee27(componentsIds) {
        var componentIdsWithoutScope;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee27$(_context27) {
          while (1) {
            switch (_context27.prev = _context27.next) {
              case 0:
                componentIdsWithoutScope = componentsIds.map(function (id) {
                  return id.toStringWithoutScope();
                });
                _context27.next = 3;
                return this.remove({
                  ids: componentIdsWithoutScope,
                  force: true,
                  remote: false,
                  track: false,
                  deleteFiles: true
                });

              case 3:
                _context27.next = 5;
                return (_packageJson || _load_packageJson()).addComponentsWithVersionToRoot(this, componentsIds);

              case 5:
                _context27.next = 7;
                return (_packageJson || _load_packageJson()).removeComponentsFromNodeModules(this, componentsIds);

              case 7:
                _context27.next = 9;
                return (0, (_installPackages || _load_installPackages()).installPackages)(this, [], true, true);

              case 9:
                return _context27.abrupt('return', componentsIds);

              case 10:
              case 'end':
                return _context27.stop();
            }
          }
        }, _callee27, this);
      }));

      function eject(_x44) {
        return _ref35.apply(this, arguments);
      }

      return eject;
    }()
  }, {
    key: 'ejectConf',
    value: function () {
      var _ref37 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee28(componentId, _ref36) {
        var ejectPath = _ref36.ejectPath;
        var component;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee28$(_context28) {
          while (1) {
            switch (_context28.prev = _context28.next) {
              case 0:
                _context28.next = 2;
                return this.loadComponent(componentId);

              case 2:
                component = _context28.sent;
                return _context28.abrupt('return', component.writeConfig(this, ejectPath || this.dirStructure.ejectedEnvsDirStructure));

              case 4:
              case 'end':
                return _context28.stop();
            }
          }
        }, _callee28, this);
      }));

      function ejectConf(_x45, _x46) {
        return _ref37.apply(this, arguments);
      }

      return ejectConf;
    }()
  }, {
    key: 'injectConf',
    value: function () {
      var _ref38 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee29(componentId, force) {
        var component;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee29$(_context29) {
          while (1) {
            switch (_context29.prev = _context29.next) {
              case 0:
                _context29.next = 2;
                return this.loadComponent(componentId);

              case 2:
                component = _context29.sent;
                return _context29.abrupt('return', component.injectConfig(this.getPath(), this.bitMap, force));

              case 4:
              case 'end':
                return _context29.stop();
            }
          }
        }, _callee29, this);
      }));

      function injectConf(_x47, _x48) {
        return _ref38.apply(this, arguments);
      }

      return injectConf;
    }()
  }, {
    key: 'onDestroy',
    value: function () {
      var _ref39 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee30() {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee30$(_context30) {
          while (1) {
            switch (_context30.prev = _context30.next) {
              case 0:
                _context30.next = 2;
                return this.cleanTmpFolder();

              case 2:
                return _context30.abrupt('return', this.bitMap.write());

              case 3:
              case 'end':
                return _context30.stop();
            }
          }
        }, _callee30, this);
      }));

      function onDestroy() {
        return _ref39.apply(this, arguments);
      }

      return onDestroy;
    }()
  }, {
    key: 'compiler',
    get: function get() {
      return this.bitJson.loadCompiler(this.projectPath, this.scope.getPath());
    }
  }, {
    key: 'tester',
    get: function get() {
      return this.bitJson.loadTester(this.projectPath, this.scope.getPath());
    }
  }, {
    key: 'driver',
    get: function get() {
      if (!this._driver) {
        this._driver = (_driver || _load_driver()).Driver.load(this.bitJson.lang);
      }
      return this._driver;
    }
  }, {
    key: 'dirStructure',
    get: function get() {
      if (!this._dirStructure) {
        this._dirStructure = new (_dirStructure || _load_dirStructure()).default(this.bitJson.componentsDefaultDirectory, this.bitJson.dependenciesDirectory, this.bitJson.ejectedEnvsDirectory);
      }
      return this._dirStructure;
    }
  }, {
    key: 'bitmapIds',
    get: function get() {
      return this.bitMap.getAllBitIds();
    }
  }], [{
    key: 'getNodeModulesPathOfComponent',
    value: function getNodeModulesPathOfComponent(bindingPrefix, id) {
      if (!id.scope) {
        throw new (_generalError || _load_generalError()).default(`Failed creating a path in node_modules for ${id.toString()}, as it does not have a scope yet`);
      }
      // Temp fix to support old components before the migration has been running
      bindingPrefix = bindingPrefix === 'bit' ? '@bit' : bindingPrefix;
      var allSlashes = new RegExp('/', 'g');
      var name = id.name.replace(allSlashes, (_constants || _load_constants()).NODE_PATH_COMPONENT_SEPARATOR);
      return (_path || _load_path()).default.join('node_modules', bindingPrefix, [id.scope, name].join((_constants || _load_constants()).NODE_PATH_COMPONENT_SEPARATOR));
    }
  }, {
    key: 'create',
    value: function create(projectPath) {
      var noGit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

      return this.ensure(projectPath, noGit);
    }
  }, {
    key: '_getScopePath',
    value: function _getScopePath(projectPath, noGit) {
      var gitDirPath = (_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).DOT_GIT_DIR);
      var resolvedScopePath = (_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).BIT_HIDDEN_DIR);
      if (!noGit && (_fsExtra || _load_fsExtra()).default.existsSync(gitDirPath) && !(_fsExtra || _load_fsExtra()).default.existsSync(resolvedScopePath)) {
        resolvedScopePath = (_path || _load_path()).default.join(gitDirPath, (_constants || _load_constants()).BIT_GIT_DIR);
      }
      return resolvedScopePath;
    }
  }, {
    key: 'ensure',
    value: function () {
      var _ref40 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee31(projectPath) {
        var noGit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        var resolvedScopePath, existingGitHooks, bitMap, scopeP, bitJsonP, _ref41, _ref42, scope, bitJson;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee31$(_context31) {
          while (1) {
            switch (_context31.prev = _context31.next) {
              case 0:
                resolvedScopePath = Consumer._getScopePath(projectPath, noGit);
                existingGitHooks = void 0;
                bitMap = (_bitMap || _load_bitMap()).default.load(projectPath);
                scopeP = (_scope || _load_scope()).Scope.ensure(resolvedScopePath);
                bitJsonP = (_consumerBitJson || _load_consumerBitJson()).default.ensure(projectPath);
                _context31.next = 7;
                return Promise.all([scopeP, bitJsonP]);

              case 7:
                _ref41 = _context31.sent;
                _ref42 = _slicedToArray(_ref41, 2);
                scope = _ref42[0];
                bitJson = _ref42[1];
                return _context31.abrupt('return', new Consumer({
                  projectPath,
                  created: true,
                  scope,
                  bitJson,
                  bitMap,
                  existingGitHooks
                }));

              case 12:
              case 'end':
                return _context31.stop();
            }
          }
        }, _callee31, this);
      }));

      function ensure(_x51) {
        return _ref40.apply(this, arguments);
      }

      return ensure;
    }()

    /**
     * if resetHard, delete consumer-files: bitMap and bit.json and also the local scope (.bit dir).
     * otherwise, delete the consumer-files only when they are corrupted
     */

  }, {
    key: 'reset',
    value: function () {
      var _ref43 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee32(projectPath, resetHard) {
        var noGit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var resolvedScopePath, scopeP, bitJsonP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee32$(_context32) {
          while (1) {
            switch (_context32.prev = _context32.next) {
              case 0:
                resolvedScopePath = Consumer._getScopePath(projectPath, noGit);

                (_bitMap || _load_bitMap()).default.reset(projectPath, resetHard);
                scopeP = (_scope || _load_scope()).Scope.reset(resolvedScopePath, resetHard);
                bitJsonP = (_consumerBitJson || _load_consumerBitJson()).default.reset(projectPath, resetHard);
                _context32.next = 6;
                return Promise.all([scopeP, bitJsonP]);

              case 6:
              case 'end':
                return _context32.stop();
            }
          }
        }, _callee32, this);
      }));

      function reset(_x53, _x54) {
        return _ref43.apply(this, arguments);
      }

      return reset;
    }()
  }, {
    key: 'createWithExistingScope',
    value: function () {
      var _ref44 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee33(consumerPath, scope) {
        var isolated = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var bitJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee33$(_context33) {
          while (1) {
            switch (_context33.prev = _context33.next) {
              case 0:
                if (!((0, (_consumerLocator || _load_consumerLocator()).pathHasConsumer)(consumerPath) && !isolated)) {
                  _context33.next = 2;
                  break;
                }

                return _context33.abrupt('return', Promise.reject(new (_exceptions || _load_exceptions()).ConsumerAlreadyExists()));

              case 2:
                _context33.next = 4;
                return (_consumerBitJson || _load_consumerBitJson()).default.ensure(consumerPath);

              case 4:
                bitJson = _context33.sent;
                return _context33.abrupt('return', new Consumer({
                  projectPath: consumerPath,
                  created: true,
                  scope,
                  isolated,
                  bitJson
                }));

              case 6:
              case 'end':
                return _context33.stop();
            }
          }
        }, _callee33, this);
      }));

      function createWithExistingScope(_x56, _x57) {
        return _ref44.apply(this, arguments);
      }

      return createWithExistingScope;
    }()
  }, {
    key: 'locateProjectScope',
    value: function locateProjectScope(projectPath) {
      if ((_fsExtra || _load_fsExtra()).default.existsSync((_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).DOT_GIT_DIR, (_constants || _load_constants()).BIT_GIT_DIR))) {
        return (_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).DOT_GIT_DIR, (_constants || _load_constants()).BIT_GIT_DIR);
      }
      if ((_fsExtra || _load_fsExtra()).default.existsSync((_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).BIT_HIDDEN_DIR))) return (_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).BIT_HIDDEN_DIR);
    }
  }, {
    key: 'load',
    value: function () {
      var _ref45 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee34(currentPath) {
        var projectPath, consumer, scopePath, scopeP, bitJsonP, _ref46, _ref47, scope, bitJson;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee34$(_context34) {
          while (1) {
            switch (_context34.prev = _context34.next) {
              case 0:
                projectPath = (0, (_consumerLocator || _load_consumerLocator()).locateConsumer)(currentPath);

                if (projectPath) {
                  _context34.next = 3;
                  break;
                }

                return _context34.abrupt('return', Promise.reject(new (_exceptions || _load_exceptions()).ConsumerNotFound()));

              case 3:
                if (!(!(0, (_consumerLocator || _load_consumerLocator()).pathHasConsumer)(projectPath) && (0, (_consumerLocator || _load_consumerLocator()).pathHasBitMap)(projectPath))) {
                  _context34.next = 9;
                  break;
                }

                _context34.next = 6;
                return Consumer.create(currentPath);

              case 6:
                consumer = _context34.sent;
                _context34.next = 9;
                return Promise.all([consumer.bitJson.write({ bitDir: consumer.projectPath }), consumer.scope.ensureDir()]);

              case 9:
                scopePath = Consumer.locateProjectScope(projectPath);
                scopeP = (_scope || _load_scope()).Scope.load(scopePath);
                bitJsonP = (_consumerBitJson || _load_consumerBitJson()).default.load(projectPath);
                _context34.next = 14;
                return Promise.all([scopeP, bitJsonP]);

              case 14:
                _ref46 = _context34.sent;
                _ref47 = _slicedToArray(_ref46, 2);
                scope = _ref47[0];
                bitJson = _ref47[1];
                return _context34.abrupt('return', new Consumer({
                  projectPath,
                  bitJson,
                  scope
                }));

              case 19:
              case 'end':
                return _context34.stop();
            }
          }
        }, _callee34, this);
      }));

      function load(_x58) {
        return _ref45.apply(this, arguments);
      }

      return load;
    }()
  }]);

  return Consumer;
}();

exports.default = Consumer;