'use strict';

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

var _regenerator;

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

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

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 _pMapSeries;

function _load_pMapSeries() {
  return _pMapSeries = _interopRequireDefault(require('p-map-series'));
}

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 _workspaceConfig;

function _load_workspaceConfig() {
  return _workspaceConfig = _interopRequireDefault(require('./config/workspace-config'));
}

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 _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 _removedComponents;

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

var _packageJsonUtils;

function _load_packageJsonUtils() {
  return _packageJsonUtils = _interopRequireWildcard(require('./component/package-json-utils'));
}

var _dependencies;

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

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 _autoTag;

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

var _exceptions3;

function _load_exceptions3() {
  return _exceptions3 = require('../scope/exceptions');
}

var _versionDependencies;

function _load_versionDependencies() {
  return _versionDependencies = _interopRequireDefault(require('../scope/version-dependencies'));
}

var _componentVersion;

function _load_componentVersion() {
  return _componentVersion = _interopRequireDefault(require('../scope/component-version'));
}

var _manipulateDir;

function _load_manipulateDir() {
  return _manipulateDir = require('./component-ops/manipulate-dir');
}

var _componentLoader;

function _load_componentLoader() {
  return _componentLoader = _interopRequireDefault(require('./component/component-loader'));
}

var _scopeRemotes;

function _load_scopeRemotes() {
  return _scopeRemotes = require('../scope/scope-remotes');
}

var _scopeComponentsImporter;

function _load_scopeComponentsImporter() {
  return _scopeComponentsImporter = _interopRequireDefault(require('../scope/component-ops/scope-components-importer'));
}

var _installExtensions;

function _load_installExtensions() {
  return _installExtensions = _interopRequireDefault(require('../scope/extensions/install-extensions'));
}

var _composeComponentPath;

function _load_composeComponentPath() {
  return _composeComponentPath = require('../utils/bit/compose-component-path');
}

var _componentOutOfSync;

function _load_componentOutOfSync() {
  return _componentOutOfSync = _interopRequireDefault(require('./exceptions/component-out-of-sync'));
}

var _componentNodeModulesPath;

function _load_componentNodeModulesPath() {
  return _componentNodeModulesPath = _interopRequireDefault(require('../utils/bit/component-node-modules-path'));
}

var _consumerOverrides;

function _load_consumerOverrides() {
  return _consumerOverrides = require('./config/consumer-overrides');
}

var _envFactory;

function _load_envFactory() {
  return _envFactory = _interopRequireDefault(require('../extensions/env-factory'));
}

var _envExtension;

function _load_envExtension() {
  return _envExtension = _interopRequireDefault(require('../extensions/env-extension'));
}

var _deleteComponentFiles;

function _load_deleteComponentFiles() {
  return _deleteComponentFiles = _interopRequireDefault(require('./component-ops/delete-component-files'));
}

var _componentsPendingImport;

function _load_componentsPendingImport() {
  return _componentsPendingImport = _interopRequireDefault(require('./component-ops/exceptions/components-pending-import'));
}

var _componentsDeprecation;

function _load_componentsDeprecation() {
  return _componentsDeprecation = require('../scope/component-ops/components-deprecation');
}

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 _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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

/**
 * @todo: change the class name to Workspace
 */
var Consumer = function () {
  // args entered by the user in the command line after '--'
  // 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
  function Consumer(_ref) {
    var projectPath = _ref.projectPath,
        config = _ref.config,
        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._componentsStatusCache = {};
    this.packageManagerArgs = [];

    this.projectPath = projectPath;
    this.config = config;
    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();
    this.componentLoader = (_componentLoader || _load_componentLoader()).default.getInstance(this);
  } // cache loaded components


  _createClass(Consumer, [{
    key: 'getEnv',
    value: function () {
      var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(envType, context) {
        var props;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                props = this._getEnvProps(envType, context);

                if (props) {
                  _context.next = 3;
                  break;
                }

                return _context.abrupt('return', null);

              case 3:
                return _context.abrupt('return', (0, (_envFactory || _load_envFactory()).default)(envType, props));

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

      function getEnv(_x, _x2) {
        return _ref2.apply(this, arguments);
      }

      return getEnv;
    }()
  }, {
    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 _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2() {
        var tmpPath, exists;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                tmpPath = this.getTmpFolder(true);
                _context2.next = 3;
                return (_fsExtra || _load_fsExtra()).default.exists(tmpPath);

              case 3:
                exists = _context2.sent;

                if (!exists) {
                  _context2.next = 7;
                  break;
                }

                (_logger || _load_logger()).default.info(`consumer.cleanTmpFolder, deleting ${tmpPath}`);
                return _context2.abrupt('return', (_fsExtra || _load_fsExtra()).default.remove(tmpPath));

              case 7:
                return _context2.abrupt('return', null);

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

      function cleanTmpFolder() {
        return _ref3.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.config.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 _ref4 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(verbose) {
        var bitmapVersion, result;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                // 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)) {
                  _context3.next = 5;
                  break;
                }

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

              case 5:
                (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_MIGRATION);
                (_logger || _load_logger()).default.debugAndAddBreadCrumb('consumer.migrate', `start consumer migration. bitmapVersion version ${bitmapVersion}, bit version ${(_constants || _load_constants()).BIT_VERSION}`);

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

              case 9:
                result = _context3.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;
                _context3.next = 15;
                return result.bitMap.write();

              case 15:

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

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

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

      function migrate(_x4) {
        return _ref4.apply(this, arguments);
      }

      return migrate;
    }()
  }, {
    key: 'write',
    value: function () {
      var _ref5 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4() {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return Promise.all([this.config.write({ bitDir: this.projectPath }), this.scope.ensureDir()]);

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

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

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

      function write() {
        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 || (_constants || _load_constants()).LATEST);
    }
  }, {
    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);
    }

    /**
     * throws a ComponentNotFound exception if not found in the model
     */

  }, {
    key: 'loadComponentFromModel',
    value: function () {
      var _ref6 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(id) {
        var modelComponent, componentVersion, manipulateDirData;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                if (id.version) {
                  _context5.next = 2;
                  break;
                }

                throw new TypeError('consumer.loadComponentFromModel, version is missing from the id');

              case 2:
                _context5.next = 4;
                return this.scope.getModelComponent(id);

              case 4:
                modelComponent = _context5.sent;
                componentVersion = modelComponent.toComponentVersion(id.version);
                _context5.next = 8;
                return (0, (_manipulateDir || _load_manipulateDir()).getManipulateDirForExistingComponents)(this, componentVersion);

              case 8:
                manipulateDirData = _context5.sent;
                return _context5.abrupt('return', modelComponent.toConsumerComponent(id.version, this.scope.name, this.scope.objects, manipulateDirData));

              case 10:
              case 'end':
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function loadComponentFromModel(_x5) {
        return _ref6.apply(this, arguments);
      }

      return loadComponentFromModel;
    }()

    /**
     * return a component only when it's stored locally.
     * don't go to any remote server and don't throw an exception if the component is not there.
     */

  }, {
    key: 'loadComponentFromModelIfExist',
    value: function () {
      var _ref7 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(id) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                if (id.version) {
                  _context6.next = 2;
                  break;
                }

                return _context6.abrupt('return', null);

              case 2:
                return _context6.abrupt('return', this.loadComponentFromModel(id).catch(function (err) {
                  if (err instanceof (_exceptions3 || _load_exceptions3()).ComponentNotFound) return null;
                  throw err;
                }));

              case 3:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function loadComponentFromModelIfExist(_x6) {
        return _ref7.apply(this, arguments);
      }

      return loadComponentFromModelIfExist;
    }()
  }, {
    key: 'loadAllVersionsOfComponentFromModel',
    value: function () {
      var _ref8 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(id) {
        var _this = this;

        var modelComponent, componentsP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                _context8.next = 2;
                return this.scope.getModelComponent(id);

              case 2:
                modelComponent = _context8.sent;
                componentsP = modelComponent.listVersions().map(function () {
                  var _ref9 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(versionNum) {
                    var componentVersion, manipulateDirData;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
                      while (1) {
                        switch (_context7.prev = _context7.next) {
                          case 0:
                            componentVersion = modelComponent.toComponentVersion(versionNum);
                            _context7.next = 3;
                            return (0, (_manipulateDir || _load_manipulateDir()).getManipulateDirForExistingComponents)(_this, componentVersion);

                          case 3:
                            manipulateDirData = _context7.sent;
                            return _context7.abrupt('return', modelComponent.toConsumerComponent(versionNum, _this.scope.name, _this.scope.objects, manipulateDirData));

                          case 5:
                          case 'end':
                            return _context7.stop();
                        }
                      }
                    }, _callee7, _this);
                  }));

                  return function (_x8) {
                    return _ref9.apply(this, arguments);
                  };
                }());
                return _context8.abrupt('return', Promise.all(componentsP));

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

      function loadAllVersionsOfComponentFromModel(_x7) {
        return _ref8.apply(this, arguments);
      }

      return loadAllVersionsOfComponentFromModel;
    }()
  }, {
    key: 'loadComponentWithDependenciesFromModel',
    value: function () {
      var _ref10 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(id) {
        var modelComponent, scopeComponentsImporter, versionDependencies, manipulateDirData;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                _context9.next = 2;
                return this.scope.getModelComponent(id);

              case 2:
                modelComponent = _context9.sent;

                if (id.version) {
                  _context9.next = 5;
                  break;
                }

                throw new TypeError('consumer.loadComponentWithDependenciesFromModel, version is missing from the id');

              case 5:
                scopeComponentsImporter = (_scopeComponentsImporter || _load_scopeComponentsImporter()).default.getInstance(this.scope);
                _context9.next = 8;
                return scopeComponentsImporter.componentToVersionDependencies(modelComponent, id);

              case 8:
                versionDependencies = _context9.sent;
                _context9.next = 11;
                return (0, (_manipulateDir || _load_manipulateDir()).getManipulateDirWhenImportingComponents)(this.bitMap, [versionDependencies], this.scope.objects);

              case 11:
                manipulateDirData = _context9.sent;
                return _context9.abrupt('return', versionDependencies.toConsumer(this.scope.objects, manipulateDirData));

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

      function loadComponentWithDependenciesFromModel(_x9) {
        return _ref10.apply(this, arguments);
      }

      return loadComponentWithDependenciesFromModel;
    }()
  }, {
    key: 'loadComponent',
    value: function () {
      var _ref11 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(id) {
        var _ref12, components;

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

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

              case 5:
              case 'end':
                return _context10.stop();
            }
          }
        }, _callee10, this);
      }));

      function loadComponent(_x10) {
        return _ref11.apply(this, arguments);
      }

      return loadComponent;
    }()
  }, {
    key: 'loadComponents',
    value: function () {
      var _ref13 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11(ids) {
        var throwOnFailure = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                return _context11.abrupt('return', this.componentLoader.loadMany(ids, throwOnFailure));

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

      function loadComponents(_x11) {
        return _ref13.apply(this, arguments);
      }

      return loadComponents;
    }()
  }, {
    key: 'importEnvironment',
    value: function importEnvironment(bitId, verbose, dontPrintEnvMsg) {
      return (0, (_installExtensions || _load_installExtensions()).default)({ ids: [{ componentId: bitId }], scope: this.scope, verbose, dontPrintEnvMsg });
    }
  }, {
    key: 'importComponents',
    value: function () {
      var _ref14 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(ids, withAllVersions, saveDependenciesAsComponents) {
        var _this2 = this;

        var scopeComponentsImporter, versionDependenciesArr, shouldDependenciesSavedAsComponents, manipulateDirData, componentWithDependencies;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee12$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                scopeComponentsImporter = (_scopeComponentsImporter || _load_scopeComponentsImporter()).default.getInstance(this.scope);

                if (!withAllVersions) {
                  _context12.next = 7;
                  break;
                }

                _context12.next = 4;
                return scopeComponentsImporter.importManyWithAllVersions(ids, false);

              case 4:
                _context12.t0 = _context12.sent;
                _context12.next = 10;
                break;

              case 7:
                _context12.next = 9;
                return scopeComponentsImporter.importMany(ids);

              case 9:
                _context12.t0 = _context12.sent;

              case 10:
                versionDependenciesArr = _context12.t0;
                _context12.next = 13;
                return this.shouldDependenciesSavedAsComponents(versionDependenciesArr.map(function (v) {
                  return v.component.id;
                }), saveDependenciesAsComponents);

              case 13:
                shouldDependenciesSavedAsComponents = _context12.sent;
                _context12.next = 16;
                return (0, (_manipulateDir || _load_manipulateDir()).getManipulateDirWhenImportingComponents)(this.bitMap, versionDependenciesArr, this.scope.objects);

              case 16:
                manipulateDirData = _context12.sent;
                _context12.next = 19;
                return (0, (_pMapSeries || _load_pMapSeries()).default)(versionDependenciesArr, function (versionDependencies) {
                  return versionDependencies.toConsumer(_this2.scope.objects, manipulateDirData);
                });

              case 19:
                componentWithDependencies = _context12.sent;

                componentWithDependencies.forEach(function (componentWithDeps) {
                  var shouldSavedAsComponents = shouldDependenciesSavedAsComponents.find(function (c) {
                    return c.id.isEqual(componentWithDeps.component.id);
                  });
                  if (!shouldSavedAsComponents) {
                    throw new Error(`saveDependenciesAsComponents is missing for ${componentWithDeps.component.id.toString()}`);
                  }
                  componentWithDeps.component.dependenciesSavedAsComponents = shouldSavedAsComponents.saveDependenciesAsComponents;
                });
                return _context12.abrupt('return', componentWithDependencies);

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

      function importComponents(_x13, _x14, _x15) {
        return _ref14.apply(this, arguments);
      }

      return importComponents;
    }()
  }, {
    key: 'shouldDependenciesSavedAsComponents',
    value: function () {
      var _ref15 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee13(bitIds, saveDependenciesAsComponents) {
        var remotes, shouldDependenciesSavedAsComponents;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee13$(_context13) {
          while (1) {
            switch (_context13.prev = _context13.next) {
              case 0:
                if (saveDependenciesAsComponents === undefined) {
                  saveDependenciesAsComponents = this.config.saveDependenciesAsComponents;
                }
                _context13.next = 3;
                return (0, (_scopeRemotes || _load_scopeRemotes()).getScopeRemotes)(this.scope);

              case 3:
                remotes = _context13.sent;
                shouldDependenciesSavedAsComponents = bitIds.map(function (bitId) {
                  return {
                    id: bitId, // if it doesn't go to the hub, it can't import dependencies as packages
                    saveDependenciesAsComponents: saveDependenciesAsComponents || !remotes.isHub(bitId.scope)
                  };
                });
                return _context13.abrupt('return', shouldDependenciesSavedAsComponents);

              case 6:
              case 'end':
                return _context13.stop();
            }
          }
        }, _callee13, this);
      }));

      function shouldDependenciesSavedAsComponents(_x16, _x17) {
        return _ref15.apply(this, arguments);
      }

      return shouldDependenciesSavedAsComponents;
    }()

    /**
     * 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.config.distEntry && !this.config.distTarget;
    }
  }, {
    key: 'potentialComponentsForAutoTagging',
    value: function potentialComponentsForAutoTagging(modifiedComponents) {
      var candidateComponents = this.bitMap.getAuthoredAndImportedBitIds();
      var 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
      var idsWithoutModified = candidateComponents.filter(function (component) {
        return !modifiedComponentsWithoutVersions.includes(component.toStringWithoutVersion());
      });
      return (_bitId || _load_bitId()).BitIds.fromArray(idsWithoutModified);
    }
  }, {
    key: 'listComponentsForAutoTagging',
    value: function () {
      var _ref16 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee14(modifiedComponents) {
        var candidateComponents;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee14$(_context14) {
          while (1) {
            switch (_context14.prev = _context14.next) {
              case 0:
                candidateComponents = this.potentialComponentsForAutoTagging(modifiedComponents);
                return _context14.abrupt('return', (0, (_autoTag || _load_autoTag()).getAutoTagPending)(this.scope, candidateComponents, modifiedComponents));

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

      function listComponentsForAutoTagging(_x18) {
        return _ref16.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 _ref17 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee15(componentFromModel, componentFromFileSystem) {
        var componentMap, _ref18, version, copyDependenciesVersionsFromModelToFS, sortProperties, sortOverrides;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee15$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                sortOverrides = function sortOverrides(overrides) {
                  if (!overrides) return;
                  (_consumerOverrides || _load_consumerOverrides()).dependenciesFields.forEach(function (field) {
                    if (overrides[field]) overrides[field] = (0, (_utils || _load_utils()).sortObject)(overrides[field]);
                  });
                };

                sortProperties = function sortProperties(version) {
                  // 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.dependencies.sort();
                  version.devDependencies.sort();
                  version.compilerDependencies.sort();
                  version.testerDependencies.sort();
                  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);
                  sortOverrides(version.overrides);
                  componentFromModel.dependencies.sort();
                  componentFromModel.devDependencies.sort();
                  componentFromModel.compilerDependencies.sort();
                  componentFromModel.testerDependencies.sort();
                  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);
                  sortOverrides(componentFromModel.overrides);
                };

                if (componentFromModel instanceof (_models || _load_models()).Version) {
                  _context15.next = 4;
                  break;
                }

                throw new TypeError(`isComponentModified expects componentFromModel to be Version, got ${typeof componentFromModel}`);

              case 4:
                if (componentFromFileSystem instanceof (_component || _load_component()).default) {
                  _context15.next = 6;
                  break;
                }

                throw new TypeError(`isComponentModified expects componentFromFileSystem to be ConsumerComponent, got ${typeof componentFromFileSystem}`);

              case 6:
                if (!(typeof componentFromFileSystem._isModified === 'undefined')) {
                  _context15.next = 22;
                  break;
                }

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

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

              case 11:
                _ref18 = _context15.sent;
                version = _ref18.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 dependencyFromModel = dependenciesModel.get().find(function (modelDependency) {
                      return modelDependency.id.isEqualWithoutVersion(dependency.id);
                    });
                    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);

                sortProperties(version);

                // 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 22:
                return _context15.abrupt('return', componentFromFileSystem._isModified);

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

      function isComponentModified(_x19, _x20) {
        return _ref17.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 _ref19 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee17(id) {
        var _this3 = this;

        var getStatus;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee17$(_context17) {
          while (1) {
            switch (_context17.prev = _context17.next) {
              case 0:
                getStatus = function () {
                  var _ref20 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee16() {
                    var status, componentFromModel, componentFromFileSystem, versionFromFs, idStr, versionRef, versionFromModel;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee16$(_context16) {
                      while (1) {
                        switch (_context16.prev = _context16.next) {
                          case 0:
                            status = {};
                            _context16.next = 3;
                            return _this3.scope.getModelComponentIfExist(id);

                          case 3:
                            componentFromModel = _context16.sent;
                            componentFromFileSystem = void 0;
                            _context16.prev = 5;
                            _context16.next = 8;
                            return _this3.loadComponent(id.changeVersion((_constants || _load_constants()).LATEST));

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

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

                            if (!(_context16.t0 instanceof (_missingFilesFromComponent || _load_missingFilesFromComponent()).default || _context16.t0 instanceof (_componentNotFoundInPath || _load_componentNotFoundInPath()).default || _context16.t0 instanceof (_exceptions2 || _load_exceptions2()).MissingBitMapComponent)) {
                              _context16.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 _context16.abrupt('return', status);

                          case 16:
                            throw _context16.t0;

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

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

                          case 20:
                            if (componentFromModel) {
                              _context16.next = 23;
                              break;
                            }

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

                          case 23:

                            status.staged = componentFromModel.isLocallyChanged();
                            versionFromFs = componentFromFileSystem.id.version;
                            idStr = id.toString();

                            if (componentFromFileSystem.id.hasVersion()) {
                              _context16.next = 28;
                              break;
                            }

                            throw new (_componentOutOfSync || _load_componentOutOfSync()).default(idStr);

                          case 28:
                            // 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) {
                              _context16.next = 31;
                              break;
                            }

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

                          case 31:
                            _context16.next = 33;
                            return _this3.scope.getObject(versionRef.hash);

                          case 33:
                            versionFromModel = _context16.sent;

                            if (versionFromModel) {
                              _context16.next = 36;
                              break;
                            }

                            throw new (_generalError || _load_generalError()).default(`failed loading version ${versionFromFs} of ${idStr} from the scope`);

                          case 36:
                            _context16.next = 38;
                            return _this3.isComponentModified(versionFromModel, componentFromFileSystem);

                          case 38:
                            status.modified = _context16.sent;
                            return _context16.abrupt('return', status);

                          case 40:
                          case 'end':
                            return _context16.stop();
                        }
                      }
                    }, _callee16, _this3, [[5, 11]]);
                  }));

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

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

                _context17.next = 4;
                return getStatus();

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

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

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

      function getComponentStatusById(_x21) {
        return _ref19.apply(this, arguments);
      }

      return getComponentStatusById;
    }()
  }, {
    key: 'tag',
    value: function () {
      var _ref21 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee18(ids, message, exactVersion, releaseType, force, verbose, ignoreUnresolvedDependencies, ignoreNewestVersion) {
        var skipTests = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : false;

        var _ref22, components, componentsWithMissingDeps, areComponentsMissingFromScope, _ref23, taggedComponents, autoTaggedResults, autoTaggedComponents, allComponents;

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

              case 4:
                _ref22 = _context18.sent;
                components = _ref22.components;

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

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

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

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

              case 10:
                areComponentsMissingFromScope = components.some(function (c) {
                  return !c.componentFromModel && c.id.hasScope();
                });

                if (!areComponentsMissingFromScope) {
                  _context18.next = 13;
                  break;
                }

                throw new (_componentsPendingImport || _load_componentsPendingImport()).default();

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

              case 15:
                _ref23 = _context18.sent;
                taggedComponents = _ref23.taggedComponents;
                autoTaggedResults = _ref23.autoTaggedResults;
                autoTaggedComponents = autoTaggedResults.map(function (r) {
                  return r.component;
                });
                allComponents = [].concat(_toConsumableArray(taggedComponents), _toConsumableArray(autoTaggedComponents));
                _context18.next = 22;
                return this._updateComponentsVersions(allComponents);

              case 22:
                return _context18.abrupt('return', { taggedComponents, autoTaggedResults });

              case 23:
              case 'end':
                return _context18.stop();
            }
          }
        }, _callee18, this);
      }));

      function tag(_x22, _x23, _x24, _x25, _x26, _x27, _x28, _x29) {
        return _ref21.apply(this, arguments);
      }

      return tag;
    }()
  }, {
    key: '_updateComponentsVersions',
    value: function _updateComponentsVersions(components) {
      var _this4 = this;

      var getPackageJsonDir = function getPackageJsonDir(componentMap, bitId, bindingPrefix) {
        if (componentMap.rootDir) return componentMap.rootDir;
        // it's author
        if (!bitId.hasScope()) return null;
        return (0, (_componentNodeModulesPath || _load_componentNodeModulesPath()).default)(bindingPrefix, bitId);
      };

      var updateVersionsP = components.map(function (component) {
        var id = component instanceof (_models || _load_models()).ModelComponent ? component.toBitIdWithLatestVersion() : component.id;
        _this4.bitMap.updateComponentId(id);
        var componentMap = _this4.bitMap.getComponent(id);
        var packageJsonDir = getPackageJsonDir(componentMap, id, component.bindingPrefix);
        return packageJsonDir ? (_packageJsonUtils || _load_packageJsonUtils()).updateAttribute(_this4, (_path || _load_path()).default.join(_this4.getPath(), packageJsonDir), 'version', id.version) : Promise.resolve();
      });
      return Promise.all(updateVersionsP);
    }
  }, {
    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('/')) // the part after the first slash is the path inside the package
      : 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;
      // only bit hub has the concept of having the username in the scope name.
      if (bindingPrefix !== 'bit' && bindingPrefix !== '@bit') 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: 'composeRelativeComponentPath',
    value: function composeRelativeComponentPath(bitId) {
      var componentsDefaultDirectory = this.dirStructure.componentsDefaultDirectory;

      return (0, (_composeComponentPath || _load_composeComponentPath()).composeComponentPath)(bitId, componentsDefaultDirectory);
    }
  }, {
    key: 'composeComponentPath',
    value: function composeComponentPath(bitId) {
      var addToPath = [this.getPath(), this.composeRelativeComponentPath(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: 'composeRelativeDependencyPath',
    value: function composeRelativeDependencyPath(bitId) {
      var dependenciesDir = this.dirStructure.dependenciesDirStructure;
      return (0, (_composeComponentPath || _load_composeComponentPath()).composeDependencyPath)(bitId, dependenciesDir);
    }
  }, {
    key: 'composeDependencyPath',
    value: function composeDependencyPath(bitId) {
      var relativeDependencyPath = this.composeRelativeDependencyPath(bitId);
      return (_path || _load_path()).default.join(this.getPath(), relativeDependencyPath);
    }
  }, {
    key: 'deprecate',
    value: function () {
      var _ref24 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee19(bitIds, remote) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee19$(_context19) {
          while (1) {
            switch (_context19.prev = _context19.next) {
              case 0:
                return _context19.abrupt('return', remote ? (0, (_componentsDeprecation || _load_componentsDeprecation()).deprecateRemote)(this.scope, bitIds) : (0, (_componentsDeprecation || _load_componentsDeprecation()).deprecateMany)(this.scope, bitIds));

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

      function deprecate(_x31, _x32) {
        return _ref24.apply(this, arguments);
      }

      return deprecate;
    }()
  }, {
    key: 'undeprecate',
    value: function () {
      var _ref25 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee20(bitIds, remote) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee20$(_context20) {
          while (1) {
            switch (_context20.prev = _context20.next) {
              case 0:
                return _context20.abrupt('return', remote ? (0, (_componentsDeprecation || _load_componentsDeprecation()).undeprecateRemote)(this.scope, bitIds) : (0, (_componentsDeprecation || _load_componentsDeprecation()).undeprecateMany)(this.scope, bitIds));

              case 1:
              case 'end':
                return _context20.stop();
            }
          }
        }, _callee20, this);
      }));

      function undeprecate(_x33, _x34) {
        return _ref25.apply(this, arguments);
      }

      return undeprecate;
    }()

    /**
     * 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 _ref26 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee21(_ref27) {
        var ids = _ref27.ids,
            force = _ref27.force,
            remote = _ref27.remote,
            track = _ref27.track,
            deleteFiles = _ref27.deleteFiles;

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

        return (_regenerator || _load_regenerator()).default.wrap(function _callee21$(_context21) {
          while (1) {
            switch (_context21.prev = _context21.next) {
              case 0:
                (_logger || _load_logger()).default.debugAndAddBreadCrumb('consumer.remove', `{ids}. force: ${force.toString()}`, { ids: ids.toString() });
                // added this to remove support for remove only one version from a component
                bitIdsLatest = (_bitId || _load_bitId()).BitIds.fromArray(ids.map(function (id) {
                  return id.changeVersion((_constants || _load_constants()).LATEST_BIT_VERSION);
                }));
                _partition = (0, (_lodash || _load_lodash()).default)(bitIdsLatest, function (id) {
                  return id.isLocal();
                }), _partition2 = _slicedToArray(_partition, 2), localIds = _partition2[0], remoteIds = _partition2[1];

                if (!(remote && localIds.length)) {
                  _context21.next = 5;
                  break;
                }

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

              case 5:
                if (!(remote && !(_ramda || _load_ramda()).default.isEmpty(remoteIds))) {
                  _context21.next = 11;
                  break;
                }

                _context21.next = 8;
                return this.removeRemote(remoteIds, force);

              case 8:
                _context21.t0 = _context21.sent;
                _context21.next = 12;
                break;

              case 11:
                _context21.t0 = [];

              case 12:
                remoteResult = _context21.t0;

                if (remote) {
                  _context21.next = 19;
                  break;
                }

                _context21.next = 16;
                return this.removeLocal(bitIdsLatest, force, track, deleteFiles);

              case 16:
                _context21.t1 = _context21.sent;
                _context21.next = 20;
                break;

              case 19:
                _context21.t1 = new (_removedComponents || _load_removedComponents()).RemovedLocalObjects();

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

              case 22:
              case 'end':
                return _context21.stop();
            }
          }
        }, _callee21, this);
      }));

      function remove(_x35) {
        return _ref26.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 _ref28 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee23(bitIds, force) {
        var _this5 = this;

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

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

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

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

                          case 5:
                          case 'end':
                            return _context22.stop();
                        }
                      }
                    }, _callee22, _this5);
                  }));

                  return function (_x38) {
                    return _ref29.apply(this, arguments);
                  };
                }());
                return _context23.abrupt('return', Promise.all(removeP));

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

      function removeRemote(_x36, _x37) {
        return _ref28.apply(this, arguments);
      }

      return removeRemote;
    }()

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

  }, {
    key: 'cleanFromBitMap',
    value: function () {
      var _ref30 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee24(componentsToRemoveFromFs, removedDependencies) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee24$(_context24) {
          while (1) {
            switch (_context24.prev = _context24.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`consumer.cleanFromBitMap, cleaning ${componentsToRemoveFromFs.toString()} from .bitmap`);
                this.bitMap.removeComponents(componentsToRemoveFromFs);
                this.bitMap.removeComponents(removedDependencies);

              case 3:
              case 'end':
                return _context24.stop();
            }
          }
        }, _callee24, this);
      }));

      function cleanFromBitMap(_x39, _x40) {
        return _ref30.apply(this, arguments);
      }

      return cleanFromBitMap;
    }()
    /**
     * removeLocal - remove local (imported, new staged components) from modules and bitmap according to flags
     * @param {BitIds} bitIds - list of 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 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee26(bitIds, force, track, deleteFiles) {
        var _this6 = this;

        var modifiedComponents, nonModifiedComponents, _ref33, removedComponentIds, missingComponents, dependentBits, removedDependencies;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee26$(_context26) {
          while (1) {
            switch (_context26.prev = _context26.next) {
              case 0:
                // local remove in case user wants to delete tagged components
                modifiedComponents = new (_bitId || _load_bitId()).BitIds();
                nonModifiedComponents = new (_bitId || _load_bitId()).BitIds();

                if (!(_ramda || _load_ramda()).default.isEmpty(bitIds)) {
                  _context26.next = 4;
                  break;
                }

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

              case 4:
                if (force) {
                  _context26.next = 7;
                  break;
                }

                _context26.next = 7;
                return Promise.all(bitIds.map(function () {
                  var _ref32 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee25(id) {
                    var componentStatus;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee25$(_context25) {
                      while (1) {
                        switch (_context25.prev = _context25.next) {
                          case 0:
                            _context25.prev = 0;
                            _context25.next = 3;
                            return _this6.getComponentStatusById(id);

                          case 3:
                            componentStatus = _context25.sent;

                            if (componentStatus.modified) modifiedComponents.push(id);else nonModifiedComponents.push(id);
                            _context25.next = 14;
                            break;

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

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

                            nonModifiedComponents.push(id);
                            _context25.next = 14;
                            break;

                          case 13:
                            throw _context25.t0;

                          case 14:
                          case 'end':
                            return _context25.stop();
                        }
                      }
                    }, _callee25, _this6, [[0, 7]]);
                  }));

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

              case 7:
                _context26.next = 9;
                return this.scope.removeMany(force ? bitIds : nonModifiedComponents, force, true, this);

              case 9:
                _ref33 = _context26.sent;
                removedComponentIds = _ref33.removedComponentIds;
                missingComponents = _ref33.missingComponents;
                dependentBits = _ref33.dependentBits;
                removedDependencies = _ref33.removedDependencies;

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

                _context26.next = 17;
                return (0, (_deleteComponentFiles || _load_deleteComponentFiles()).default)(this, removedComponentIds, deleteFiles);

              case 17:
                _context26.next = 19;
                return (0, (_deleteComponentFiles || _load_deleteComponentFiles()).default)(this, removedDependencies, false);

              case 19:
                if (track) {
                  _context26.next = 24;
                  break;
                }

                _context26.next = 22;
                return (_packageJsonUtils || _load_packageJsonUtils()).removeComponentsFromWorkspacesAndDependencies(this, removedComponentIds);

              case 22:
                _context26.next = 24;
                return this.cleanFromBitMap(removedComponentIds, removedDependencies);

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

              case 25:
              case 'end':
                return _context26.stop();
            }
          }
        }, _callee26, this);
      }));

      function removeLocal(_x41, _x42, _x43, _x44) {
        return _ref31.apply(this, arguments);
      }

      return removeLocal;
    }()
  }, {
    key: 'addRemoteAndLocalVersionsToDependencies',
    value: function () {
      var _ref34 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee27(component, loadedFromFileSystem) {
        var modelDependencies, modelDevDependencies, modelCompilerDependencies, modelTesterDependencies, mainComponentFromModel;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee27$(_context27) {
          while (1) {
            switch (_context27.prev = _context27.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) {
                  // when loaded from file-system, the dependencies versions are fetched from bit.map.
                  mainComponentFromModel = component.componentFromModel;

                  if (mainComponentFromModel) {
                    // otherwise, the component is probably on the file-system only and not on the model.
                    modelDependencies = mainComponentFromModel.dependencies;
                    modelDevDependencies = mainComponentFromModel.devDependencies;
                    modelCompilerDependencies = mainComponentFromModel.compilerDependencies;
                    modelTesterDependencies = mainComponentFromModel.testerDependencies;
                  }
                }
                _context27.next = 9;
                return component.dependencies.addRemoteAndLocalVersions(this.scope, modelDependencies);

              case 9:
                _context27.next = 11;
                return component.devDependencies.addRemoteAndLocalVersions(this.scope, modelDevDependencies);

              case 11:
                _context27.next = 13;
                return component.compilerDependencies.addRemoteAndLocalVersions(this.scope, modelCompilerDependencies);

              case 13:
                _context27.next = 15;
                return component.testerDependencies.addRemoteAndLocalVersions(this.scope, modelTesterDependencies);

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

      function addRemoteAndLocalVersionsToDependencies(_x46, _x47) {
        return _ref34.apply(this, arguments);
      }

      return addRemoteAndLocalVersionsToDependencies;
    }()
  }, {
    key: 'getAuthoredAndImportedDependentsIdsOf',
    value: function () {
      var _ref35 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee28(components) {
        var authoredAndImportedComponents, componentsIds;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee28$(_context28) {
          while (1) {
            switch (_context28.prev = _context28.next) {
              case 0:
                authoredAndImportedComponents = this.bitMap.getAllBitIds([(_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED, (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED]);
                componentsIds = (_bitId || _load_bitId()).BitIds.fromArray(components.map(function (c) {
                  return c.id;
                }));
                return _context28.abrupt('return', this.scope.findDirectDependentComponents(authoredAndImportedComponents, componentsIds));

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

      function getAuthoredAndImportedDependentsIdsOf(_x48) {
        return _ref35.apply(this, arguments);
      }

      return getAuthoredAndImportedDependentsIdsOf;
    }()
  }, {
    key: 'getAuthoredAndImportedDependentsComponentsOf',
    value: function () {
      var _ref36 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee29(components) {
        var _this7 = this;

        var dependentsIds, scopeComponentsImporter, versionDependenciesArr, manipulateDirData, dependentComponentsP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee29$(_context29) {
          while (1) {
            switch (_context29.prev = _context29.next) {
              case 0:
                _context29.next = 2;
                return this.getAuthoredAndImportedDependentsIdsOf(components);

              case 2:
                dependentsIds = _context29.sent;
                scopeComponentsImporter = (_scopeComponentsImporter || _load_scopeComponentsImporter()).default.getInstance(this.scope);
                _context29.next = 6;
                return scopeComponentsImporter.importMany(dependentsIds, true, false);

              case 6:
                versionDependenciesArr = _context29.sent;
                _context29.next = 9;
                return (0, (_manipulateDir || _load_manipulateDir()).getManipulateDirWhenImportingComponents)(this.bitMap, versionDependenciesArr, this.scope.objects);

              case 9:
                manipulateDirData = _context29.sent;
                dependentComponentsP = versionDependenciesArr.map(function (c) {
                  return c.component.toConsumer(_this7.scope.objects, manipulateDirData);
                });
                return _context29.abrupt('return', Promise.all(dependentComponentsP));

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

      function getAuthoredAndImportedDependentsComponentsOf(_x49) {
        return _ref36.apply(this, arguments);
      }

      return getAuthoredAndImportedDependentsComponentsOf;
    }()
  }, {
    key: 'ejectConf',
    value: function () {
      var _ref37 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee30(componentId, _ref38) {
        var ejectPath = _ref38.ejectPath;
        var component;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee30$(_context30) {
          while (1) {
            switch (_context30.prev = _context30.next) {
              case 0:
                _context30.next = 2;
                return this.loadComponent(componentId);

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

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

      function ejectConf(_x50, _x51) {
        return _ref37.apply(this, arguments);
      }

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

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

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

      function injectConf(_x52, _x53) {
        return _ref39.apply(this, arguments);
      }

      return injectConf;
    }()
  }, {
    key: '_getEnvProps',
    value: function _getEnvProps(envType, context) {
      var envs = this.config.getEnvsByType(envType);
      if (!envs) return undefined;
      var envName = Object.keys(envs)[0];
      var envObject = envs[envName];
      return {
        name: envName,
        consumerPath: this.getPath(),
        scopePath: this.scope.getPath(),
        rawConfig: envObject.rawConfig,
        files: envObject.files,
        bitJsonPath: (_path || _load_path()).default.dirname(this.config.path),
        options: envObject.options,
        envType,
        context
      };
    }
  }, {
    key: 'onDestroy',
    value: function () {
      var _ref40 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee32() {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee32$(_context32) {
          while (1) {
            switch (_context32.prev = _context32.next) {
              case 0:
                _context32.next = 2;
                return this.cleanTmpFolder();

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

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

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

      return onDestroy;
    }()
  }, {
    key: 'compiler',
    get: function get() {
      // $FlowFixMe
      return this.getEnv((_constants || _load_constants()).COMPILER_ENV_TYPE);
    }
  }, {
    key: 'tester',
    get: function get() {
      // $FlowFixMe
      return this.getEnv((_constants || _load_constants()).TESTER_ENV_TYPE);
    }
  }, {
    key: 'driver',
    get: function get() {
      if (!this._driver) {
        this._driver = (_driver || _load_driver()).Driver.load(this.config.lang);
      }
      return this._driver;
    }
  }, {
    key: 'dirStructure',
    get: function get() {
      if (!this._dirStructure) {
        this._dirStructure = new (_dirStructure || _load_dirStructure()).default(this.config.componentsDefaultDirectory, this.config.dependenciesDirectory, this.config.ejectedEnvsDirectory);
      }
      return this._dirStructure;
    }
  }, {
    key: 'bitmapIds',
    get: function get() {
      return this.bitMap.getAllBitIds();
    }
  }], [{
    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 _ref41 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee33(projectPath) {
        var standAlone = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        var resolvedScopePath, existingGitHooks, bitMap, scopeP, configP, _ref42, _ref43, scope, config;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee33$(_context33) {
          while (1) {
            switch (_context33.prev = _context33.next) {
              case 0:
                resolvedScopePath = Consumer._getScopePath(projectPath, standAlone);
                existingGitHooks = void 0;
                bitMap = (_bitMap || _load_bitMap()).default.load(projectPath);
                scopeP = (_scope || _load_scope()).Scope.ensure(resolvedScopePath);
                configP = (_workspaceConfig || _load_workspaceConfig()).default.ensure(projectPath, standAlone);
                _context33.next = 7;
                return Promise.all([scopeP, configP]);

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

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

      function ensure(_x55) {
        return _ref41.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 _ref44 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee34(projectPath, resetHard) {
        var noGit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var resolvedScopePath, scopeP, configP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee34$(_context34) {
          while (1) {
            switch (_context34.prev = _context34.next) {
              case 0:
                resolvedScopePath = Consumer._getScopePath(projectPath, noGit);

                (_bitMap || _load_bitMap()).default.reset(projectPath, resetHard);
                scopeP = (_scope || _load_scope()).Scope.reset(resolvedScopePath, resetHard);
                configP = (_workspaceConfig || _load_workspaceConfig()).default.reset(projectPath, resetHard);
                _context34.next = 6;
                return Promise.all([scopeP, configP]);

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

      function reset(_x57, _x58) {
        return _ref44.apply(this, arguments);
      }

      return reset;
    }()
  }, {
    key: 'createIsolatedWithExistingScope',
    value: function () {
      var _ref45 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee35(consumerPath, scope) {
        var config;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee35$(_context35) {
          while (1) {
            switch (_context35.prev = _context35.next) {
              case 0:
                _context35.next = 2;
                return (_workspaceConfig || _load_workspaceConfig()).default.ensure(consumerPath);

              case 2:
                config = _context35.sent;
                return _context35.abrupt('return', new Consumer({
                  projectPath: consumerPath,
                  created: true,
                  scope,
                  isolated: true,
                  config
                }));

              case 4:
              case 'end':
                return _context35.stop();
            }
          }
        }, _callee35, this);
      }));

      function createIsolatedWithExistingScope(_x60, _x61) {
        return _ref45.apply(this, arguments);
      }

      return createIsolatedWithExistingScope;
    }()
  }, {
    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 _ref46 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee36(currentPath) {
        var consumerInfo, consumer, scopePath, scope;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee36$(_context36) {
          while (1) {
            switch (_context36.prev = _context36.next) {
              case 0:
                _context36.next = 2;
                return (0, (_consumerLocator || _load_consumerLocator()).getConsumerInfo)(currentPath);

              case 2:
                consumerInfo = _context36.sent;

                if (consumerInfo) {
                  _context36.next = 5;
                  break;
                }

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

              case 5:
                if (!((!consumerInfo.consumerConfig || !consumerInfo.hasScope) && consumerInfo.hasBitMap)) {
                  _context36.next = 14;
                  break;
                }

                _context36.next = 8;
                return Consumer.create(consumerInfo.path);

              case 8:
                consumer = _context36.sent;
                _context36.next = 11;
                return Promise.all([consumer.config.write({ bitDir: consumer.projectPath }), consumer.scope.ensureDir()]);

              case 11:
                _context36.next = 13;
                return (_workspaceConfig || _load_workspaceConfig()).default.load(consumerInfo.path);

              case 13:
                consumerInfo.consumerConfig = _context36.sent;

              case 14:
                scopePath = Consumer.locateProjectScope(consumerInfo.path);
                _context36.next = 17;
                return (_scope || _load_scope()).Scope.load(scopePath);

              case 17:
                scope = _context36.sent;
                return _context36.abrupt('return', new Consumer({
                  projectPath: consumerInfo.path,
                  config: consumerInfo.consumerConfig,
                  scope
                }));

              case 19:
              case 'end':
                return _context36.stop();
            }
          }
        }, _callee36, this);
      }));

      function load(_x62) {
        return _ref46.apply(this, arguments);
      }

      return load;
    }()
  }]);

  return Consumer;
}();

exports.default = Consumer;