'use strict';

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

var _regenerator;

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

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

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

var _path;

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

var _semver;

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

var _groupArray;

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

var _fsExtra;

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

var _ramda;

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

var _chalk;

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

var _stringFormat;

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

var _lodash;

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

var _consumerLocator;

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

var _exceptions;

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

var _driver;

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

var _driverNotFound;

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

var _consumerBitJson;

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

var _bitId;

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

var _component;

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

var _constants;

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

var _scope;

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

var _consumerMigratorManifest;

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

var _consumerMigrator;

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

var _enrichContextFromGlobal;

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

var _loader;

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

var _loaderMessages;

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

var _bitMap;

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

var _exceptions2;

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

var _logger;

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

var _dirStructure;

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

var _utils;

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

var _dependencyResolver;

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

var _models;

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

var _missingFilesFromComponent;

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

var _componentNotFoundInPath;

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

var _installPackages;

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

var _removedComponents;

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

var _packageJson;

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

var _dependencies;

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

var _importComponents;

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

var _compilerExtension;

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

var _testerExtension;

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

var _analytics;

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

var _generalError;

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

var _tagModelComponent;

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

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

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

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

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

    _classCallCheck(this, Consumer);

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

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


  _createClass(Consumer, [{
    key: 'warnForMissingDriver',


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

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

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

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

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

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

              case 7:

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

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

              case 10:
                result = _context.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;
                _context.next = 16;
                return result.bitMap.write();

              case 16:

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

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

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

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

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

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

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

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

      function write(_x2) {
        return _ref4.apply(this, arguments);
      }

      return write;
    }()
  }, {
    key: 'getComponentsPath',
    value: function getComponentsPath() {
      return (_path || _load_path()).default.join(this.projectPath, (_constants || _load_constants()).BITS_DIRNAME);
    }
  }, {
    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: 'loadComponent',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(id) {
        var _ref6, components;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return this.loadComponents([id]);

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

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

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

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

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

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

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

                ids.forEach(function (id) {
                  if (_this._componentsCache[id.toString()]) {
                    (_logger || _load_logger()).default.debug(`the component ${id.toString()} has been already loaded, use the cached component`);
                    (_analytics || _load_analytics()).Analytics.addBreadCrumb('load components', `the component ${(_analytics || _load_analytics()).Analytics.hashData(id.toString())} has been already loaded, use the cached component`);
                    alreadyLoadedComponents.push(_this._componentsCache[id.toString()]);
                  } else {
                    idsToProcess.push(id);
                  }
                });

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

                return _context5.abrupt('return', { components: alreadyLoadedComponents, deletedComponents });

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

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

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

                          case 13:
                            component = _context4.sent;
                            _context4.next = 26;
                            break;

                          case 16:
                            _context4.prev = 16;
                            _context4.t0 = _context4['catch'](10);

                            if (!throwOnFailure) {
                              _context4.next = 20;
                              break;
                            }

                            throw _context4.t0;

                          case 20:

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

                            if (!(_context4.t0 instanceof (_missingFilesFromComponent || _load_missingFilesFromComponent()).default || _context4.t0 instanceof (_componentNotFoundInPath || _load_componentNotFoundInPath()).default)) {
                              _context4.next = 25;
                              break;
                            }

                            deletedComponents.push(id);
                            return _context4.abrupt('return', null);

                          case 25:
                            throw _context4.t0;

                          case 26:

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

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

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

                          case 32:
                            _context4.next = 34;
                            return (0, (_dependencyResolver || _load_dependencyResolver()).loadDependenciesForComponent)(component, bitDir, _this, idWithConcreteVersionString);

                          case 34:
                            _context4.next = 36;
                            return (0, (_dependencyResolver || _load_dependencyResolver()).updateDependenciesVersions)(_this, component);

                          case 36:
                            return _context4.abrupt('return', component);

                          case 37:
                          case 'end':
                            return _context4.stop();
                        }
                      }
                    }, _callee4, _this, [[10, 16]]);
                  }));

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

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

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

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

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

              case 25:
                _context5.next = 31;
                break;

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

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

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

              case 34:
                _context5.prev = 34;

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

                throw _iteratorError;

              case 37:
                return _context5.finish(34);

              case 38:
                return _context5.finish(31);

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

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

      function loadComponents(_x5) {
        return _ref7.apply(this, arguments);
      }

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

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

  }, {
    key: 'shouldDistsBeInsideTheComponent',
    value: function shouldDistsBeInsideTheComponent() {
      return !this.bitJson.distEntry && !this.bitJson.distTarget;
    }
  }, {
    key: 'candidateComponentsForAutoTagging',
    value: function () {
      var _ref9 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(modifiedComponents) {
        var candidateComponents, modifiedComponentsWithoutVersions, candidateComponentsIds;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                candidateComponents = this.bitMap.getAllComponents([(_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED, (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED]);

                if (candidateComponents) {
                  _context6.next = 3;
                  break;
                }

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

              case 3:
                modifiedComponentsWithoutVersions = modifiedComponents.map(function (modifiedComponent) {
                  return modifiedComponent.toStringWithoutVersion();
                });
                candidateComponentsIds = Object.keys(candidateComponents).map(function (id) {
                  return (_bitId || _load_bitId()).BitId.parse(id);
                });
                // if a modified component is in candidates array, remove it from the array as it will be already tagged with the
                // correct version

                return _context6.abrupt('return', candidateComponentsIds.filter(function (component) {
                  return !modifiedComponentsWithoutVersions.includes(component.toStringWithoutVersion());
                }));

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

      function candidateComponentsForAutoTagging(_x7) {
        return _ref9.apply(this, arguments);
      }

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

              case 2:
                candidateComponents = _context7.sent;
                return _context7.abrupt('return', this.scope.bumpDependenciesVersions(candidateComponents, modifiedComponents, false));

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

      function listComponentsForAutoTagging(_x8) {
        return _ref10.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 _ref11 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(componentFromModel, componentFromFileSystem) {
        var componentMap, _ref12, version, copyDependenciesVersionsFromModelToFS, sortObject;

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

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

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

              case 5:
                _ref12 = _context8.sent;
                version = _ref12.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() {
                  var dev = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

                  var dependenciesFS = dev ? version.devDependencies : version.dependencies;
                  var dependenciesModel = dev ? componentFromModel.devDependencies : componentFromModel.dependencies;
                  dependenciesFS.get().forEach(function (dependency) {
                    var idWithoutVersion = dependency.id.toStringWithoutVersion();
                    var dependencyFromModel = dependenciesModel.get().find(function (modelDependency) {
                      return modelDependency.id.toStringWithoutVersion() === idWithoutVersion;
                    });
                    if (dependencyFromModel && !dependency.id.hasVersion()) {
                      dependency.id = dependencyFromModel.id;
                    }
                  });
                };

                copyDependenciesVersionsFromModelToFS();
                copyDependenciesVersionsFromModelToFS(true);

                /*
                 sort packageDependencies for comparing
                 */

                sortObject = function sortObject(obj) {
                  return Object.keys(obj).sort().reduce(function (result, key) {
                    result[key] = obj[key];
                    return result;
                  }, {});
                };

                // sort the files by 'relativePath' because the order can be changed when adding or renaming
                // files in bitmap, which affects later on the model.


                version.files = (_ramda || _load_ramda()).default.sortBy((_ramda || _load_ramda()).default.prop('relativePath'), version.files);
                componentFromModel.files = (_ramda || _load_ramda()).default.sortBy((_ramda || _load_ramda()).default.prop('relativePath'), componentFromModel.files);

                version.packageDependencies = sortObject(version.packageDependencies);
                componentFromModel.packageDependencies = sortObject(componentFromModel.packageDependencies);
                // uncomment to easily understand why two components are considered as modified
                // if (componentFromModel.hash().hash !== version.hash().hash) {
                //   console.log('-------------------componentFromModel------------------------');
                //   console.log(componentFromModel.id());
                //   console.log('------------------------version------------------------------');
                //   console.log(version.id());
                //   console.log('-------------------------END---------------------------------');
                // }
                componentFromFileSystem._isModified = componentFromModel.hash().hash !== version.hash().hash;

              case 17:
                return _context8.abrupt('return', componentFromFileSystem._isModified);

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

      function isComponentModified(_x9, _x10) {
        return _ref11.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 _ref13 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(id) {
        var _this2 = this;

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

                          case 3:
                            componentFromModel = _context9.sent;
                            componentFromFileSystem = void 0;
                            _context9.prev = 5;
                            _context9.next = 8;
                            return _this2.loadComponent((_bitId || _load_bitId()).BitId.parse(id.toStringWithoutVersion()));

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

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

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

                          case 16:
                            throw _context9.t0;

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

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

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

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

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

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

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

                          case 27:
                            versionRef = componentFromModel.versions[versionFromFs];

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

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

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

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

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

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

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

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

                _context10.next = 4;
                return getStatus();

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

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

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

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

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

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

        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`committing the following components: ${ids.join(', ')}`);
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('tag', `committing the following components: ${(_analytics || _load_analytics()).Analytics.hashData(ids)}`);
                componentsIds = ids.map(function (componentId) {
                  return (_bitId || _load_bitId()).BitId.parse(componentId);
                });
                _context11.next = 5;
                return this.loadComponents(componentsIds);

              case 5:
                _ref16 = _context11.sent;
                components = _ref16.components;

                if (ignoreMissingDependencies) {
                  _context11.next = 11;
                  break;
                }

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

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

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

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

              case 13:
                _ref17 = _context11.sent;
                taggedComponents = _ref17.taggedComponents;
                autoTaggedComponents = _ref17.autoTaggedComponents;


                // update bitmap with the new version
                taggedComponentIds = taggedComponents.map(function (component) {
                  _this3.bitMap.updateComponentId(component.id);
                  return component.id;
                });
                autoTaggedComponentIds = autoTaggedComponents.map(function (component) {
                  var id = component.toBitId();
                  id.version = component.latest();
                  _this3.bitMap.updateComponentId(id);
                  return id;
                });

                // update package.json with the new version

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

              case 22:
                return _context11.abrupt('return', { taggedComponents, autoTaggedComponents });

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

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

      return tag;
    }()
  }, {
    key: 'composeRelativeBitPath',
    value: function composeRelativeBitPath(bitId) {
      var componentsDefaultDirectory = this.dirStructure.componentsDefaultDirectory;

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

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

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

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

                          case 2:
                            resolvedRemote = _context12.sent;
                            _context12.next = 5;
                            return resolvedRemote.deprecateMany(groupedBitsByScope[scopeName], context);

                          case 5:
                            deprecateResult = _context12.sent;
                            return _context12.abrupt('return', deprecateResult);

                          case 7:
                          case 'end':
                            return _context12.stop();
                        }
                      }
                    }, _callee12, _this4);
                  }));

                  return function (_x22) {
                    return _ref19.apply(this, arguments);
                  };
                }());
                _context13.next = 9;
                return Promise.all(deprecateP);

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

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

      function deprecateRemote(_x21) {
        return _ref18.apply(this, arguments);
      }

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

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

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

      return deprecateLocal;
    }()
  }, {
    key: 'deprecate',
    value: function () {
      var _ref21 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee15(ids, remote) {
        var bitIds;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee15$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                bitIds = ids.map(function (bitId) {
                  return (_bitId || _load_bitId()).BitId.parse(bitId);
                });
                return _context15.abrupt('return', remote ? this.deprecateRemote(bitIds) : this.deprecateLocal(bitIds));

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

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

      return deprecate;
    }()

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

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

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

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

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

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

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

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

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

              case 12:
                _context16.t0 = [];

              case 13:
                remoteResult = _context16.t0;

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

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

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

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

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

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

      function remove(_x26) {
        return _ref23.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 _ref24 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee18(bitIds, force) {
        var _this5 = this;

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

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

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

                          case 2:
                            resolvedRemote = _context17.sent;
                            return _context17.abrupt('return', resolvedRemote.deleteMany(groupedBitsByScope[key], force, context));

                          case 4:
                          case 'end':
                            return _context17.stop();
                        }
                      }
                    }, _callee17, _this5);
                  }));

                  return function (_x29) {
                    return _ref25.apply(this, arguments);
                  };
                }());
                return _context18.abrupt('return', Promise.all(removeP));

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

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

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

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

        return (_regenerator || _load_regenerator()).default.wrap(function _callee20$(_context20) {
          while (1) {
            switch (_context20.prev = _context20.next) {
              case 0:
                return _context20.abrupt('return', Promise.all(bitIds.map(function () {
                  var _ref27 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee19(id) {
                    var component;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee19$(_context19) {
                      while (1) {
                        switch (_context19.prev = _context19.next) {
                          case 0:
                            component = id.isLocal() ? _this6.bitMap.getComponent(_this6.bitMap.getExistingComponentId(id.toStringWithoutVersion())) : _this6.bitMap.getComponent(id);

                            if (component) {
                              _context19.next = 3;
                              break;
                            }

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

                          case 3:
                            if (!(component.origin && component.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED || component.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED)) {
                              _context19.next = 7;
                              break;
                            }

                            return _context19.abrupt('return', (_fsExtra || _load_fsExtra()).default.remove((_path || _load_path()).default.join(_this6.getPath(), component.rootDir)));

                          case 7:
                            if (!(component.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED && deleteFiles)) {
                              _context19.next = 9;
                              break;
                            }

                            return _context19.abrupt('return', Promise.all(component.files.map(function (file) {
                              return (_fsExtra || _load_fsExtra()).default.remove(file.relativePath);
                            })));

                          case 9:
                            return _context19.abrupt('return', null);

                          case 10:
                          case 'end':
                            return _context19.stop();
                        }
                      }
                    }, _callee19, _this6);
                  }));

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

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

      function removeComponentFromFs(_x30, _x31) {
        return _ref26.apply(this, arguments);
      }

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

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

      return bitIds.map(function (id) {
        var realName = _this7.bitMap.getExistingComponentId(id.toStringWithoutVersion());
        if (!realName) return id;
        var component = _this7.bitMap.getComponent(realName);
        if (component && (component.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED || component.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED)) {
          var realId = (_bitId || _load_bitId()).BitId.parse(realName);
          realId.version = (_constants || _load_constants()).LATEST_BIT_VERSION;
          return realId;
        }
        if (component) return (_bitId || _load_bitId()).BitId.parse(realName);
        return id;
      });
    }

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

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

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

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

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

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

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

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

        return (_regenerator || _load_regenerator()).default.wrap(function _callee23$(_context23) {
          while (1) {
            switch (_context23.prev = _context23.next) {
              case 0:
                // local remove in case user wants to delete tagged components
                modifiedComponents = [];
                regularComponents = [];
                resolvedIDs = this.resolveLocalComponentIds(bitIds);

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

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

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

                _context23.next = 8;
                return Promise.all(resolvedIDs.map(function () {
                  var _ref30 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee22(id) {
                    var componentStatus;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee22$(_context22) {
                      while (1) {
                        switch (_context22.prev = _context22.next) {
                          case 0:
                            _context22.next = 2;
                            return _this8.getComponentStatusById(id);

                          case 2:
                            componentStatus = _context22.sent;

                            if (componentStatus.modified) modifiedComponents.push(id);else regularComponents.push(id);

                          case 4:
                          case 'end':
                            return _context22.stop();
                        }
                      }
                    }, _callee22, _this8);
                  }));

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

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

              case 10:
                _ref31 = _context23.sent;
                removedComponentIds = _ref31.removedComponentIds;
                missingComponents = _ref31.missingComponents;
                dependentBits = _ref31.dependentBits;
                removedDependencies = _ref31.removedDependencies;
                componentsToRemoveFromFs = removedComponentIds.filter(function (id) {
                  return id.version === (_constants || _load_constants()).LATEST_BIT_VERSION;
                });

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

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

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

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

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

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

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

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

      function removeLocal(_x35, _x36, _x37, _x38) {
        return _ref29.apply(this, arguments);
      }

      return removeLocal;
    }()
  }, {
    key: 'addRemoteAndLocalVersionsToDependencies',
    value: function () {
      var _ref32 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee24(component, loadedFromFileSystem) {
        var modelDependencies, modelDevDependencies, mainComponentFromModel;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee24$(_context24) {
          while (1) {
            switch (_context24.prev = _context24.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([]);

                if (!loadedFromFileSystem) {
                  _context24.next = 15;
                  break;
                }

                _context24.prev = 5;
                _context24.next = 8;
                return this.scope.loadRemoteComponent(component.id);

              case 8:
                mainComponentFromModel = _context24.sent;

                modelDependencies = mainComponentFromModel.dependencies;
                modelDevDependencies = mainComponentFromModel.devDependencies;
                _context24.next = 15;
                break;

              case 13:
                _context24.prev = 13;
                _context24.t0 = _context24['catch'](5);

              case 15:
                _context24.next = 17;
                return component.dependencies.addRemoteAndLocalVersions(this.scope, modelDependencies);

              case 17:
                _context24.next = 19;
                return component.devDependencies.addRemoteAndLocalVersions(this.scope, modelDevDependencies);

              case 19:
              case 'end':
                return _context24.stop();
            }
          }
        }, _callee24, this, [[5, 13]]);
      }));

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

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

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

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

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

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

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

      function eject(_x42) {
        return _ref33.apply(this, arguments);
      }

      return eject;
    }()
  }, {
    key: 'onDestroy',
    value: function () {
      var _ref34 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee26() {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee26$(_context26) {
          while (1) {
            switch (_context26.prev = _context26.next) {
              case 0:
                return _context26.abrupt('return', this.bitMap.write());

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

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

      return onDestroy;
    }()
  }, {
    key: 'compiler',
    get: function get() {
      return this.bitJson.loadCompiler(this.projectPath, this.scope.getPath());
    }
  }, {
    key: 'tester',
    get: function get() {
      return this.bitJson.loadTester(this.projectPath, this.scope.getPath());
    }
  }, {
    key: 'driver',
    get: function get() {
      if (!this._driver) {
        this._driver = (_driver || _load_driver()).Driver.load(this.bitJson.lang);
      }
      return this._driver;
    }
  }, {
    key: 'dirStructure',
    get: function get() {
      if (!this._dirStructure) {
        this._dirStructure = new (_dirStructure || _load_dirStructure()).default(this.bitJson.componentsDefaultDirectory, this.bitJson.dependenciesDirectory, this.bitJson.ejectedEnvsDirectory);
      }
      return this._dirStructure;
    }
  }], [{
    key: 'getNodeModulesPathOfComponent',
    value: function getNodeModulesPathOfComponent(bindingPrefix, id) {
      if (!id.scope) {
        throw new (_generalError || _load_generalError()).default(`Failed creating a path in node_modules for ${id}, as it does not have a scope yet`);
      }
      // Temp fix to support old components before the migration has been running
      bindingPrefix = bindingPrefix === 'bit' ? '@bit' : bindingPrefix;
      return (_path || _load_path()).default.join('node_modules', bindingPrefix, [id.scope, id.box, id.name].join((_constants || _load_constants()).NODE_PATH_SEPARATOR));
    }
  }, {
    key: 'getComponentIdFromNodeModulesPath',
    value: function getComponentIdFromNodeModulesPath(requirePath, bindingPrefix) {
      requirePath = (0, (_utils || _load_utils()).pathNormalizeToLinux)(requirePath);
      // Temp fix to support old components before the migration has been running
      bindingPrefix = bindingPrefix === 'bit' ? '@bit' : bindingPrefix;
      var prefix = requirePath.includes('node_modules') ? `node_modules/${bindingPrefix}/` : `${bindingPrefix}/`;
      var withoutPrefix = requirePath.substr(requirePath.indexOf(prefix) + prefix.length);
      var componentName = withoutPrefix.includes('/') ? withoutPrefix.substr(0, withoutPrefix.indexOf('/')) : withoutPrefix;
      var pathSplit = componentName.split((_constants || _load_constants()).NODE_PATH_SEPARATOR);
      if (pathSplit.length < 3) throw new (_generalError || _load_generalError()).default(`component has an invalid require statement: ${requirePath}`);

      var name = pathSplit[pathSplit.length - 1];
      var box = pathSplit[pathSplit.length - 2];
      var scope = pathSplit.length === 3 ? pathSplit[0] : `${pathSplit[0]}.${pathSplit[1]}`;
      return new (_bitId || _load_bitId()).BitId({ scope, box, name }).toString();
    }
  }, {
    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 _ref35 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee27(projectPath) {
        var noGit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        var resolvedScopePath, existingGitHooks, bitMap, scopeP, bitJsonP, _ref36, _ref37, scope, bitJson;

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

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

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

      function ensure(_x45) {
        return _ref35.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 _ref38 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee28(projectPath, resetHard) {
        var noGit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var resolvedScopePath, scopeP, bitJsonP;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee28$(_context28) {
          while (1) {
            switch (_context28.prev = _context28.next) {
              case 0:
                resolvedScopePath = Consumer._getScopePath(projectPath, noGit);

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

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

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

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

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

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

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

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

      function createWithExistingScope(_x50, _x51) {
        return _ref39.apply(this, arguments);
      }

      return createWithExistingScope;
    }()
  }, {
    key: 'locateProjectScope',
    value: function locateProjectScope(projectPath) {
      if ((_fsExtra || _load_fsExtra()).default.existsSync((_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).DOT_GIT_DIR, (_constants || _load_constants()).BIT_GIT_DIR))) {
        return (_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).DOT_GIT_DIR, (_constants || _load_constants()).BIT_GIT_DIR);
      }
      if ((_fsExtra || _load_fsExtra()).default.existsSync((_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).BIT_HIDDEN_DIR))) return (_path || _load_path()).default.join(projectPath, (_constants || _load_constants()).BIT_HIDDEN_DIR);
    }
  }, {
    key: 'load',
    value: function () {
      var _ref40 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee30(currentPath) {
        var throws = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

        var projectPath, consumer, scopePath, scopeP, bitJsonP, _ref41, _ref42, scope, bitJson;

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

                if (projectPath) {
                  _context30.next = 5;
                  break;
                }

                if (!throws) {
                  _context30.next = 4;
                  break;
                }

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

              case 4:
                return _context30.abrupt('return', Promise.resolve(null));

              case 5:
                if (!(!(0, (_consumerLocator || _load_consumerLocator()).pathHasConsumer)(projectPath) && (0, (_consumerLocator || _load_consumerLocator()).pathHasBitMap)(projectPath))) {
                  _context30.next = 11;
                  break;
                }

                _context30.next = 8;
                return Consumer.create(currentPath);

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

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

              case 16:
                _ref41 = _context30.sent;
                _ref42 = _slicedToArray(_ref41, 2);
                scope = _ref42[0];
                bitJson = _ref42[1];
                return _context30.abrupt('return', new Consumer({
                  projectPath,
                  bitJson,
                  scope
                }));

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

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

      return load;
    }()
  }]);

  return Consumer;
}();

exports.default = Consumer;