"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _defineProperty2() {
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

  _defineProperty2 = function () {
    return data;
  };

  return data;
}

function _path() {
  const data = _interopRequireDefault(require("path"));

  _path = function () {
    return data;
  };

  return data;
}

function _semver() {
  const data = _interopRequireDefault(require("semver"));

  _semver = function () {
    return data;
  };

  return data;
}

function _groupArray() {
  const data = _interopRequireDefault(require("group-array"));

  _groupArray = function () {
    return data;
  };

  return data;
}

function _fsExtra() {
  const data = _interopRequireDefault(require("fs-extra"));

  _fsExtra = function () {
    return data;
  };

  return data;
}

function _ramda() {
  const data = _interopRequireDefault(require("ramda"));

  _ramda = function () {
    return data;
  };

  return data;
}

function _pMapSeries() {
  const data = _interopRequireDefault(require("p-map-series"));

  _pMapSeries = function () {
    return data;
  };

  return data;
}

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function () {
    return data;
  };

  return data;
}

function _stringFormat() {
  const data = _interopRequireDefault(require("string-format"));

  _stringFormat = function () {
    return data;
  };

  return data;
}

function _lodash() {
  const data = _interopRequireDefault(require("lodash.partition"));

  _lodash = function () {
    return data;
  };

  return data;
}

function _consumerLocator() {
  const data = require("./consumer-locator");

  _consumerLocator = function () {
    return data;
  };

  return data;
}

function _exceptions() {
  const data = require("./exceptions");

  _exceptions = function () {
    return data;
  };

  return data;
}

function _driver() {
  const data = require("../driver");

  _driver = function () {
    return data;
  };

  return data;
}

function _driverNotFound() {
  const data = _interopRequireDefault(require("../driver/exceptions/driver-not-found"));

  _driverNotFound = function () {
    return data;
  };

  return data;
}

function _workspaceConfig() {
  const data = _interopRequireDefault(require("./config/workspace-config"));

  _workspaceConfig = function () {
    return data;
  };

  return data;
}

function _bitId() {
  const data = require("../bit-id");

  _bitId = function () {
    return data;
  };

  return data;
}

function _component() {
  const data = _interopRequireDefault(require("./component"));

  _component = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function _scope() {
  const data = require("../scope");

  _scope = function () {
    return data;
  };

  return data;
}

function _consumerMigratorManifest() {
  const data = _interopRequireDefault(require("./migrations/consumer-migrator-manifest"));

  _consumerMigratorManifest = function () {
    return data;
  };

  return data;
}

function _consumerMigrator() {
  const data = _interopRequireDefault(require("./migrations/consumer-migrator"));

  _consumerMigrator = function () {
    return data;
  };

  return data;
}

function _enrichContextFromGlobal() {
  const data = _interopRequireDefault(require("../hooks/utils/enrich-context-from-global"));

  _enrichContextFromGlobal = function () {
    return data;
  };

  return data;
}

function _loader() {
  const data = _interopRequireDefault(require("../cli/loader"));

  _loader = function () {
    return data;
  };

  return data;
}

function _loaderMessages() {
  const data = require("../cli/loader/loader-messages");

  _loaderMessages = function () {
    return data;
  };

  return data;
}

function _bitMap() {
  const data = _interopRequireDefault(require("./bit-map/bit-map"));

  _bitMap = function () {
    return data;
  };

  return data;
}

function _exceptions2() {
  const data = require("./bit-map/exceptions");

  _exceptions2 = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

function _dirStructure() {
  const data = _interopRequireDefault(require("./dir-structure/dir-structure"));

  _dirStructure = function () {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("../utils");

  _utils = function () {
    return data;
  };

  return data;
}

function _models() {
  const data = require("../scope/models");

  _models = function () {
    return data;
  };

  return data;
}

function _missingFilesFromComponent() {
  const data = _interopRequireDefault(require("./component/exceptions/missing-files-from-component"));

  _missingFilesFromComponent = function () {
    return data;
  };

  return data;
}

function _componentNotFoundInPath() {
  const data = _interopRequireDefault(require("./component/exceptions/component-not-found-in-path"));

  _componentNotFoundInPath = function () {
    return data;
  };

  return data;
}

function _removedComponents() {
  const data = require("../scope/removed-components");

  _removedComponents = function () {
    return data;
  };

  return data;
}

function packageJsonUtils() {
  const data = _interopRequireWildcard(require("./component/package-json-utils"));

  packageJsonUtils = function () {
    return data;
  };

  return data;
}

function _dependencies() {
  const data = require("./component/dependencies");

  _dependencies = function () {
    return data;
  };

  return data;
}

function _compilerExtension() {
  const data = _interopRequireDefault(require("../extensions/compiler-extension"));

  _compilerExtension = function () {
    return data;
  };

  return data;
}

function _testerExtension() {
  const data = _interopRequireDefault(require("../extensions/tester-extension"));

  _testerExtension = function () {
    return data;
  };

  return data;
}

function _analytics() {
  const data = require("../analytics/analytics");

  _analytics = function () {
    return data;
  };

  return data;
}

function _generalError() {
  const data = _interopRequireDefault(require("../error/general-error"));

  _generalError = function () {
    return data;
  };

  return data;
}

function _tagModelComponent() {
  const data = _interopRequireDefault(require("../scope/component-ops/tag-model-component"));

  _tagModelComponent = function () {
    return data;
  };

  return data;
}

function _autoTag() {
  const data = require("../scope/component-ops/auto-tag");

  _autoTag = function () {
    return data;
  };

  return data;
}

function _exceptions3() {
  const data = require("../scope/exceptions");

  _exceptions3 = function () {
    return data;
  };

  return data;
}

function _versionDependencies() {
  const data = _interopRequireDefault(require("../scope/version-dependencies"));

  _versionDependencies = function () {
    return data;
  };

  return data;
}

function _componentVersion() {
  const data = _interopRequireDefault(require("../scope/component-version"));

  _componentVersion = function () {
    return data;
  };

  return data;
}

function _manipulateDir() {
  const data = require("./component-ops/manipulate-dir");

  _manipulateDir = function () {
    return data;
  };

  return data;
}

function _componentLoader() {
  const data = _interopRequireDefault(require("./component/component-loader"));

  _componentLoader = function () {
    return data;
  };

  return data;
}

function _scopeRemotes() {
  const data = require("../scope/scope-remotes");

  _scopeRemotes = function () {
    return data;
  };

  return data;
}

function _scopeComponentsImporter() {
  const data = _interopRequireDefault(require("../scope/component-ops/scope-components-importer"));

  _scopeComponentsImporter = function () {
    return data;
  };

  return data;
}

function _installExtensions() {
  const data = _interopRequireDefault(require("../scope/extensions/install-extensions"));

  _installExtensions = function () {
    return data;
  };

  return data;
}

function _composeComponentPath() {
  const data = require("../utils/bit/compose-component-path");

  _composeComponentPath = function () {
    return data;
  };

  return data;
}

function _componentOutOfSync() {
  const data = _interopRequireDefault(require("./exceptions/component-out-of-sync"));

  _componentOutOfSync = function () {
    return data;
  };

  return data;
}

function _componentNodeModulesPath() {
  const data = _interopRequireDefault(require("../utils/bit/component-node-modules-path"));

  _componentNodeModulesPath = function () {
    return data;
  };

  return data;
}

function _consumerOverrides() {
  const data = require("./config/consumer-overrides");

  _consumerOverrides = function () {
    return data;
  };

  return data;
}

function _envFactory() {
  const data = _interopRequireDefault(require("../extensions/env-factory"));

  _envFactory = function () {
    return data;
  };

  return data;
}

function _envExtension() {
  const data = _interopRequireDefault(require("../extensions/env-extension"));

  _envExtension = function () {
    return data;
  };

  return data;
}

function _deleteComponentFiles() {
  const data = _interopRequireDefault(require("./component-ops/delete-component-files"));

  _deleteComponentFiles = function () {
    return data;
  };

  return data;
}

function _componentsPendingImport() {
  const data = _interopRequireDefault(require("./component-ops/exceptions/components-pending-import"));

  _componentsPendingImport = function () {
    return data;
  };

  return data;
}

function _componentsDeprecation() {
  const data = require("../scope/component-ops/components-deprecation");

  _componentsDeprecation = function () {
    return data;
  };

  return data;
}

/**
 * @todo: change the class name to Workspace
 */
class Consumer {
  // cache loaded components
  constructor({
    projectPath,
    config,
    scope,
    created = false,
    isolated = false,
    bitMap,
    addedGitHooks,
    existingGitHooks
  }) {
    (0, _defineProperty2().default)(this, "isolated", false);
    (0, _defineProperty2().default)(this, "_componentsStatusCache", {});
    (0, _defineProperty2().default)(this, "packageManagerArgs", []);
    this.projectPath = projectPath;
    this.config = config;
    this.created = created;
    this.isolated = isolated;
    this.scope = scope;
    this.bitMap = bitMap || _bitMap().default.load(projectPath);
    this.addedGitHooks = addedGitHooks;
    this.existingGitHooks = existingGitHooks;
    this.warnForMissingDriver();
    this.componentLoader = _componentLoader().default.getInstance(this);
  }

  get compiler() {
    // $FlowFixMe
    return this.getEnv(_constants().COMPILER_ENV_TYPE);
  }

  get tester() {
    // $FlowFixMe
    return this.getEnv(_constants().TESTER_ENV_TYPE);
  }

  get driver() {
    if (!this._driver) {
      this._driver = _driver().Driver.load(this.config.lang);
    }

    return this._driver;
  }

  get dirStructure() {
    if (!this._dirStructure) {
      this._dirStructure = new (_dirStructure().default)(this.config.componentsDefaultDirectory, this.config.dependenciesDirectory, this.config.ejectedEnvsDirectory);
    }

    return this._dirStructure;
  }

  get bitmapIds() {
    return this.bitMap.getAllBitIds();
  }

  getEnv(envType, context) {
    var _this = this;

    return (0, _bluebird().coroutine)(function* () {
      const props = _this._getEnvProps(envType, context);

      if (!props) return null;
      return (0, _envFactory().default)(envType, props);
    })();
  }

  getTmpFolder(fullPath = false) {
    if (!fullPath) {
      return _constants().BIT_WORKSPACE_TMP_DIRNAME;
    }

    return _path().default.join(this.getPath(), _constants().BIT_WORKSPACE_TMP_DIRNAME);
  }

  cleanTmpFolder() {
    var _this2 = this;

    return (0, _bluebird().coroutine)(function* () {
      const tmpPath = _this2.getTmpFolder(true);

      const exists = yield _fsExtra().default.exists(tmpPath);

      if (exists) {
        _logger().default.info(`consumer.cleanTmpFolder, deleting ${tmpPath}`);

        return _fsExtra().default.remove(tmpPath);
      }

      return null;
    })();
  }
  /**
   * 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
   */


  warnForMissingDriver(msg) {
    try {
      this.driver.getDriver(false);
      return true;
    } catch (err) {
      msg = msg ? (0, _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().default) {
        console.log(_chalk().default.yellow(msg)); // eslint-disable-line
      }

      throw new (_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
   */


  migrate(verbose) {
    var _this3 = this;

    return (0, _bluebird().coroutine)(function* () {
      // 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

      const bitmapVersion = _this3.bitMap.version || '0.10.9';

      if (_semver().default.gte(bitmapVersion, _constants().BIT_VERSION)) {
        _logger().default.debug('bit.map version is up to date');

        return {
          run: false
        };
      }

      _loader().default.start(_loaderMessages().BEFORE_MIGRATION);

      _logger().default.debugAndAddBreadCrumb('consumer.migrate', `start consumer migration. bitmapVersion version ${bitmapVersion}, bit version ${_constants().BIT_VERSION}`);

      const result = yield (0, _consumerMigrator().default)(bitmapVersion, _consumerMigratorManifest().default, _this3.bitMap, verbose);
      result.bitMap.version = _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)

      _this3.bitMap.version = result.bitMap.version;
      yield result.bitMap.write();

      _loader().default.stop();

      return {
        run: true,
        success: true
      };
    })();
  }

  write() {
    var _this4 = this;

    return (0, _bluebird().coroutine)(function* () {
      yield Promise.all([_this4.config.write({
        workspaceDir: _this4.projectPath
      }), _this4.scope.ensureDir()]);

      _this4.bitMap.markAsChanged();

      yield _this4.bitMap.write();
      return _this4;
    })();
  }

  getPath() {
    return this.projectPath;
  }

  toAbsolutePath(pathStr) {
    if (_path().default.isAbsolute(pathStr)) throw new Error(`toAbsolutePath expects relative path, got ${pathStr}`);
    return _path().default.join(this.projectPath, pathStr);
  }

  getPathRelativeToConsumer(pathToCheck) {
    const absolutePath = _path().default.resolve(pathToCheck); // if pathToCheck was absolute, it returns it back


    return _path().default.relative(this.getPath(), absolutePath);
  }

  getParsedId(id) {
    // $FlowFixMe, bitId is always defined as shouldThrow is true
    const bitId = this.bitMap.getExistingBitId(id);

    const version = _bitId().BitId.getVersionOnlyFromString(id);

    return bitId.changeVersion(version || _constants().LATEST);
  }

  getParsedIdIfExist(id) {
    const bitId = this.bitMap.getExistingBitId(id, false);
    if (!bitId) return null;

    const version = _bitId().BitId.getVersionOnlyFromString(id);

    return bitId.changeVersion(version);
  }
  /**
   * throws a ComponentNotFound exception if not found in the model
   */


  loadComponentFromModel(id) {
    var _this5 = this;

    return (0, _bluebird().coroutine)(function* () {
      if (!id.version) throw new TypeError('consumer.loadComponentFromModel, version is missing from the id');
      const modelComponent = yield _this5.scope.getModelComponent(id);
      const componentVersion = modelComponent.toComponentVersion(id.version);
      const manipulateDirData = yield (0, _manipulateDir().getManipulateDirForExistingComponents)(_this5, componentVersion);
      return modelComponent.toConsumerComponent(id.version, _this5.scope.name, _this5.scope.objects, manipulateDirData);
    })();
  }
  /**
   * 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.
   */


  loadComponentFromModelIfExist(id) {
    var _this6 = this;

    return (0, _bluebird().coroutine)(function* () {
      if (!id.version) return null;
      return _this6.loadComponentFromModel(id).catch(err => {
        if (err instanceof _exceptions3().ComponentNotFound) return null;
        throw err;
      });
    })();
  }

  loadAllVersionsOfComponentFromModel(id) {
    var _this7 = this;

    return (0, _bluebird().coroutine)(function* () {
      const modelComponent = yield _this7.scope.getModelComponent(id);
      const componentsP = modelComponent.listVersions().map(
      /*#__PURE__*/
      function () {
        var _ref = (0, _bluebird().coroutine)(function* (versionNum) {
          const componentVersion = modelComponent.toComponentVersion(versionNum);
          const manipulateDirData = yield (0, _manipulateDir().getManipulateDirForExistingComponents)(_this7, componentVersion);
          return modelComponent.toConsumerComponent(versionNum, _this7.scope.name, _this7.scope.objects, manipulateDirData);
        });

        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
      return Promise.all(componentsP);
    })();
  }

  loadComponentWithDependenciesFromModel(id) {
    var _this8 = this;

    return (0, _bluebird().coroutine)(function* () {
      const modelComponent = yield _this8.scope.getModelComponent(id);

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

      const scopeComponentsImporter = _scopeComponentsImporter().default.getInstance(_this8.scope);

      const versionDependencies = yield scopeComponentsImporter.componentToVersionDependencies(modelComponent, id);
      const manipulateDirData = yield (0, _manipulateDir().getManipulateDirWhenImportingComponents)(_this8.bitMap, [versionDependencies], _this8.scope.objects);
      return versionDependencies.toConsumer(_this8.scope.objects, manipulateDirData);
    })();
  }

  loadComponent(id) {
    var _this9 = this;

    return (0, _bluebird().coroutine)(function* () {
      const {
        components
      } = yield _this9.loadComponents(_bitId().BitIds.fromArray([id]));
      return components[0];
    })();
  }

  loadComponentForCapsule(id) {
    return this.componentLoader.loadForCapsule(id);
  }

  loadComponents(ids, throwOnFailure = true) {
    var _this10 = this;

    return (0, _bluebird().coroutine)(function* () {
      return _this10.componentLoader.loadMany(ids, throwOnFailure);
    })();
  }

  importEnvironment(bitId, verbose, dontPrintEnvMsg) {
    return (0, _installExtensions().default)({
      ids: [{
        componentId: bitId
      }],
      scope: this.scope,
      verbose,
      dontPrintEnvMsg
    });
  }

  importComponents(ids, withAllVersions, saveDependenciesAsComponents) {
    var _this11 = this;

    return (0, _bluebird().coroutine)(function* () {
      const scopeComponentsImporter = _scopeComponentsImporter().default.getInstance(_this11.scope);

      const versionDependenciesArr = withAllVersions ? yield scopeComponentsImporter.importManyWithAllVersions(ids, false) : yield scopeComponentsImporter.importMany(ids);
      const shouldDependenciesSavedAsComponents = yield _this11.shouldDependenciesSavedAsComponents(versionDependenciesArr.map(v => v.component.id), saveDependenciesAsComponents);
      const manipulateDirData = yield (0, _manipulateDir().getManipulateDirWhenImportingComponents)(_this11.bitMap, versionDependenciesArr, _this11.scope.objects);
      const componentWithDependencies = yield (0, _pMapSeries().default)(versionDependenciesArr, versionDependencies => versionDependencies.toConsumer(_this11.scope.objects, manipulateDirData));
      componentWithDependencies.forEach(componentWithDeps => {
        const shouldSavedAsComponents = shouldDependenciesSavedAsComponents.find(c => 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 componentWithDependencies;
    })();
  }

  shouldDependenciesSavedAsComponents(bitIds, saveDependenciesAsComponents) {
    var _this12 = this;

    return (0, _bluebird().coroutine)(function* () {
      if (saveDependenciesAsComponents === undefined) {
        saveDependenciesAsComponents = _this12.config.saveDependenciesAsComponents;
      }

      const remotes = yield (0, _scopeRemotes().getScopeRemotes)(_this12.scope);
      const shouldDependenciesSavedAsComponents = bitIds.map(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 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.
   */


  shouldDistsBeInsideTheComponent() {
    return !this.config.distEntry && !this.config.distTarget;
  }

  potentialComponentsForAutoTagging(modifiedComponents) {
    const candidateComponents = this.bitMap.getAuthoredAndImportedBitIds();
    const modifiedComponentsWithoutVersions = modifiedComponents.map(modifiedComponent => 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

    const idsWithoutModified = candidateComponents.filter(component => !modifiedComponentsWithoutVersions.includes(component.toStringWithoutVersion()));
    return _bitId().BitIds.fromArray(idsWithoutModified);
  }

  listComponentsForAutoTagging(modifiedComponents) {
    var _this13 = this;

    return (0, _bluebird().coroutine)(function* () {
      const candidateComponents = _this13.potentialComponentsForAutoTagging(modifiedComponents);

      return (0, _autoTag().getAutoTagPending)(_this13.scope, candidateComponents, modifiedComponents);
    })();
  }
  /**
   * 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
   */


  isComponentModified(componentFromModel, componentFromFileSystem) {
    var _this14 = this;

    return (0, _bluebird().coroutine)(function* () {
      if (!(componentFromModel instanceof _models().Version)) {
        throw new TypeError(`isComponentModified expects componentFromModel to be Version, got ${typeof componentFromModel}`);
      }

      if (!(componentFromFileSystem instanceof _component().default)) {
        throw new TypeError(`isComponentModified expects componentFromFileSystem to be ConsumerComponent, got ${typeof componentFromFileSystem}`);
      }

      if (typeof componentFromFileSystem._isModified === 'undefined') {
        const componentMap = _this14.bitMap.getComponent(componentFromFileSystem.id);

        if (componentMap.originallySharedDir) {
          componentFromFileSystem.originallySharedDir = componentMap.originallySharedDir;
        }

        const {
          version
        } = yield _this14.scope.sources.consumerComponentToVersion({
          consumer: _this14,
          consumerComponent: componentFromFileSystem,
          versionFromModel: componentFromModel
        });
        version.log = componentFromModel.log; // ignore the log, it's irrelevant for the comparison
        // sometime dependencies from the FS don't have an exact version.

        const copyDependenciesVersionsFromModelToFS = (dependenciesFS, dependenciesModel) => {
          dependenciesFS.get().forEach(dependency => {
            const dependencyFromModel = dependenciesModel.get().find(modelDependency => 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;
      }

      return componentFromFileSystem._isModified;

      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().default.sortBy(_ramda().default.prop('relativePath'), version.files);
        componentFromModel.files = _ramda().default.sortBy(_ramda().default.prop('relativePath'), componentFromModel.files);
        version.dependencies.sort();
        version.devDependencies.sort();
        version.compilerDependencies.sort();
        version.testerDependencies.sort();
        version.packageDependencies = (0, _utils().sortObject)(version.packageDependencies);
        version.devPackageDependencies = (0, _utils().sortObject)(version.devPackageDependencies);
        version.compilerPackageDependencies = (0, _utils().sortObject)(version.compilerPackageDependencies);
        version.testerPackageDependencies = (0, _utils().sortObject)(version.testerPackageDependencies);
        version.peerPackageDependencies = (0, _utils().sortObject)(version.peerPackageDependencies);
        sortOverrides(version.overrides);
        componentFromModel.dependencies.sort();
        componentFromModel.devDependencies.sort();
        componentFromModel.compilerDependencies.sort();
        componentFromModel.testerDependencies.sort();
        componentFromModel.packageDependencies = (0, _utils().sortObject)(componentFromModel.packageDependencies);
        componentFromModel.devPackageDependencies = (0, _utils().sortObject)(componentFromModel.devPackageDependencies);
        componentFromModel.compilerPackageDependencies = (0, _utils().sortObject)(componentFromModel.compilerPackageDependencies);
        componentFromModel.testerPackageDependencies = (0, _utils().sortObject)(componentFromModel.testerPackageDependencies);
        componentFromModel.peerPackageDependencies = (0, _utils().sortObject)(componentFromModel.peerPackageDependencies);
        sortOverrides(componentFromModel.overrides);
      }

      function sortOverrides(overrides) {
        if (!overrides) return;

        _consumerOverrides().dependenciesFields.forEach(field => {
          if (overrides[field]) overrides[field] = (0, _utils().sortObject)(overrides[field]);
        });
      }
    })();
  }
  /**
   * 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.
   */


  getComponentStatusById(id) {
    var _this15 = this;

    return (0, _bluebird().coroutine)(function* () {
      const getStatus =
      /*#__PURE__*/
      function () {
        var _ref2 = (0, _bluebird().coroutine)(function* () {
          const status = {};
          const componentFromModel = yield _this15.scope.getModelComponentIfExist(id);
          let componentFromFileSystem;

          try {
            // change to 'latest' before loading from FS. don't change to null, otherwise, it'll cause
            // loadOne to not find model component as it assumes there is no version
            // also, don't leave the id as is, otherwise, it'll cause issues with import --merge, when
            // imported version is bigger than .bitmap, it won't find it and will consider as deleted
            componentFromFileSystem = yield _this15.loadComponent(id.changeVersion(_constants().LATEST));
          } catch (err) {
            if (err instanceof _missingFilesFromComponent().default || err instanceof _componentNotFoundInPath().default || err instanceof _exceptions2().MissingBitMapComponent) {
              // 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 status;
            }

            throw err;
          }

          if (componentFromFileSystem.componentMap.origin === _constants().COMPONENT_ORIGINS.NESTED) {
            status.nested = true;
            return status;
          }

          if (!componentFromModel) {
            status.newlyCreated = true;
            return status;
          }

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

          if (!componentFromFileSystem.id.hasVersion()) {
            throw new (_componentOutOfSync().default)(idStr);
          } // 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


          const versionRef = componentFromModel.versions[versionFromFs];
          if (!versionRef) throw new (_generalError().default)(`version ${versionFromFs} was not found in ${idStr}`);
          const versionFromModel = yield _this15.scope.getObject(versionRef.hash);

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

          status.modified = yield _this15.isComponentModified(versionFromModel, componentFromFileSystem);
          return status;
        });

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

      if (!_this15._componentsStatusCache[id.toString()]) {
        _this15._componentsStatusCache[id.toString()] = yield getStatus();
      }

      return _this15._componentsStatusCache[id.toString()];
    })();
  }

  tag(ids, message, exactVersion, releaseType, force, verbose, ignoreUnresolvedDependencies, ignoreNewestVersion, skipTests = false) {
    var _this16 = this;

    return (0, _bluebird().coroutine)(function* () {
      _logger().default.debug(`tagging the following components: ${ids.toString()}`);

      _analytics().Analytics.addBreadCrumb('tag', `tagging the following components: ${_analytics().Analytics.hashData(ids)}`);

      const {
        components
      } = yield _this16.loadComponents(ids); // go through the components list to check if there are missing dependencies
      // if there is at least one we won't tag anything

      if (!ignoreUnresolvedDependencies) {
        const componentsWithMissingDeps = components.filter(component => {
          return Boolean(component.issues);
        });
        if (!_ramda().default.isEmpty(componentsWithMissingDeps)) throw new (_exceptions().MissingDependencies)(componentsWithMissingDeps);
      }

      const areComponentsMissingFromScope = components.some(c => !c.componentFromModel && c.id.hasScope());

      if (areComponentsMissingFromScope) {
        throw new (_componentsPendingImport().default)();
      }

      const {
        taggedComponents,
        autoTaggedResults
      } = yield (0, _tagModelComponent().default)({
        consumerComponents: components,
        scope: _this16.scope,
        message,
        exactVersion,
        releaseType,
        force,
        consumer: _this16,
        ignoreNewestVersion,
        skipTests,
        verbose
      });
      const autoTaggedComponents = autoTaggedResults.map(r => r.component);
      const allComponents = [...taggedComponents, ...autoTaggedComponents];
      yield _this16.updateComponentsVersions(allComponents);
      return {
        taggedComponents,
        autoTaggedResults
      };
    })();
  }

  updateComponentsVersions(components) {
    const getPackageJsonDir = (componentMap, bitId, bindingPrefix) => {
      if (componentMap.rootDir) return componentMap.rootDir; // it's author

      if (!bitId.hasScope()) return null;
      return (0, _componentNodeModulesPath().default)(bindingPrefix, bitId);
    };

    const updateVersionsP = components.map(component => {
      const id = component instanceof _models().ModelComponent ? component.toBitIdWithLatestVersionAllowNull() : component.id;
      this.bitMap.updateComponentId(id);
      const componentMap = this.bitMap.getComponent(id);
      const packageJsonDir = getPackageJsonDir(componentMap, id, component.bindingPrefix);
      return packageJsonDir ? packageJsonUtils().updateAttribute(this, packageJsonDir, 'version', id.version) : Promise.resolve();
    });
    return Promise.all(updateVersionsP);
  }

  getComponentIdFromNodeModulesPath(requirePath, bindingPrefix) {
    requirePath = (0, _utils().pathNormalizeToLinux)(requirePath); // Temp fix to support old components before the migration has been running

    bindingPrefix = bindingPrefix === 'bit' ? '@bit' : bindingPrefix;
    const prefix = requirePath.includes('node_modules') ? `node_modules/${bindingPrefix}/` : `${bindingPrefix}/`;
    const withoutPrefix = requirePath.substr(requirePath.indexOf(prefix) + prefix.length);
    const componentName = withoutPrefix.includes('/') ? withoutPrefix.substr(0, withoutPrefix.indexOf('/')) // the part after the first slash is the path inside the package
    : withoutPrefix;
    const pathSplit = componentName.split(_constants().NODE_PATH_COMPONENT_SEPARATOR);
    if (pathSplit.length < 2) throw new (_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().BitId)({
        scope: pathSplit[0],
        name: pathSplit[1]
      });
    }

    const mightBeScope = _ramda().default.head(pathSplit);

    const mightBeName = _ramda().default.tail(pathSplit).join('/');

    const mightBeId = new (_bitId().BitId)({
      scope: mightBeScope,
      name: mightBeName
    });
    const 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

    const scope = pathSplit.splice(0, 2).join('.');
    const name = pathSplit.join('/');
    return new (_bitId().BitId)({
      scope,
      name
    });
  }

  composeRelativeComponentPath(bitId) {
    const {
      componentsDefaultDirectory
    } = this.dirStructure;
    return (0, _composeComponentPath().composeComponentPath)(bitId, componentsDefaultDirectory);
  }

  composeComponentPath(bitId) {
    const addToPath = [this.getPath(), this.composeRelativeComponentPath(bitId)];

    _logger().default.debug(`component dir path: ${addToPath.join('/')}`);

    _analytics().Analytics.addBreadCrumb('composeComponentPath', `component dir path: ${_analytics().Analytics.hashData(addToPath.join('/'))}`);

    return _path().default.join(...addToPath);
  }

  composeRelativeDependencyPath(bitId) {
    const dependenciesDir = this.dirStructure.dependenciesDirStructure;
    return (0, _composeComponentPath().composeDependencyPath)(bitId, dependenciesDir);
  }

  composeDependencyPath(bitId) {
    const relativeDependencyPath = this.composeRelativeDependencyPath(bitId);
    return _path().default.join(this.getPath(), relativeDependencyPath);
  }

  static create(projectPath, noGit = false) {
    return this.ensure(projectPath, noGit);
  }

  static _getScopePath(projectPath, noGit) {
    const gitDirPath = _path().default.join(projectPath, _constants().DOT_GIT_DIR);

    let resolvedScopePath = _path().default.join(projectPath, _constants().BIT_HIDDEN_DIR);

    if (!noGit && _fsExtra().default.existsSync(gitDirPath) && !_fsExtra().default.existsSync(resolvedScopePath)) {
      resolvedScopePath = _path().default.join(gitDirPath, _constants().BIT_GIT_DIR);
    }

    return resolvedScopePath;
  }

  static ensure(projectPath, standAlone = false) {
    return (0, _bluebird().coroutine)(function* () {
      const resolvedScopePath = Consumer._getScopePath(projectPath, standAlone);

      let existingGitHooks;

      const bitMap = _bitMap().default.load(projectPath);

      const scopeP = _scope().Scope.ensure(resolvedScopePath);

      const configP = _workspaceConfig().default.ensure(projectPath, standAlone);

      const [scope, config] = yield Promise.all([scopeP, configP]);
      return new Consumer({
        projectPath,
        created: true,
        scope,
        config,
        bitMap,
        existingGitHooks
      });
    })();
  }
  /**
   * 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
   */


  static reset(projectPath, resetHard, noGit = false) {
    return (0, _bluebird().coroutine)(function* () {
      const resolvedScopePath = Consumer._getScopePath(projectPath, noGit);

      _bitMap().default.reset(projectPath, resetHard);

      const scopeP = _scope().Scope.reset(resolvedScopePath, resetHard);

      const configP = _workspaceConfig().default.reset(projectPath, resetHard);

      yield Promise.all([scopeP, configP]);
    })();
  }

  static createIsolatedWithExistingScope(consumerPath, scope) {
    return (0, _bluebird().coroutine)(function* () {
      // if it's an isolated environment, it's normal to have already the consumer
      const config = yield _workspaceConfig().default.ensure(consumerPath);
      return new Consumer({
        projectPath: consumerPath,
        created: true,
        scope,
        isolated: true,
        config
      });
    })();
  }

  static locateProjectScope(projectPath) {
    if (_fsExtra().default.existsSync(_path().default.join(projectPath, _constants().DOT_GIT_DIR, _constants().BIT_GIT_DIR))) {
      return _path().default.join(projectPath, _constants().DOT_GIT_DIR, _constants().BIT_GIT_DIR);
    }

    if (_fsExtra().default.existsSync(_path().default.join(projectPath, _constants().BIT_HIDDEN_DIR))) return _path().default.join(projectPath, _constants().BIT_HIDDEN_DIR);
  }

  static load(currentPath) {
    return (0, _bluebird().coroutine)(function* () {
      const consumerInfo = yield (0, _consumerLocator().getConsumerInfo)(currentPath);

      if (!consumerInfo) {
        return Promise.reject(new (_exceptions().ConsumerNotFound)());
      }

      if ((!consumerInfo.consumerConfig || !consumerInfo.hasScope) && consumerInfo.hasBitMap) {
        const consumer = yield Consumer.create(consumerInfo.path);
        yield Promise.all([consumer.config.write({
          workspaceDir: consumer.projectPath
        }), consumer.scope.ensureDir()]);
        consumerInfo.consumerConfig = yield _workspaceConfig().default.load(consumerInfo.path);
      }

      const scopePath = Consumer.locateProjectScope(consumerInfo.path);
      const scope = yield _scope().Scope.load(scopePath);
      return new Consumer({
        projectPath: consumerInfo.path,
        config: consumerInfo.consumerConfig,
        scope
      });
    })();
  }

  deprecate(bitIds, remote) {
    var _this17 = this;

    return (0, _bluebird().coroutine)(function* () {
      return remote ? (0, _componentsDeprecation().deprecateRemote)(_this17.scope, bitIds) : (0, _componentsDeprecation().deprecateMany)(_this17.scope, bitIds);
    })();
  }

  undeprecate(bitIds, remote) {
    var _this18 = this;

    return (0, _bluebird().coroutine)(function* () {
      return remote ? (0, _componentsDeprecation().undeprecateRemote)(_this18.scope, bitIds) : (0, _componentsDeprecation().undeprecateMany)(_this18.scope, bitIds);
    })();
  }
  /**
   * 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.
   */


  remove({
    ids,
    force,
    remote,
    track,
    deleteFiles
  }) {
    var _this19 = this;

    return (0, _bluebird().coroutine)(function* () {
      _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


      const bitIdsLatest = _bitId().BitIds.fromArray(ids.map(id => {
        return id.changeVersion(_constants().LATEST_BIT_VERSION);
      }));

      const [localIds, remoteIds] = (0, _lodash().default)(bitIdsLatest, id => id.isLocal());

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

      const remoteResult = remote && !_ramda().default.isEmpty(remoteIds) ? yield _this19.removeRemote(remoteIds, force) : [];
      const localResult = !remote ? yield _this19.removeLocal(bitIdsLatest, force, track, deleteFiles) : new (_removedComponents().RemovedLocalObjects)();
      return {
        localResult,
        remoteResult
      };
    })();
  }
  /**
   * 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.
   */


  removeRemote(bitIds, force) {
    var _this20 = this;

    return (0, _bluebird().coroutine)(function* () {
      const groupedBitsByScope = (0, _groupArray().default)(bitIds, 'scope');
      const remotes = yield (0, _scopeRemotes().getScopeRemotes)(_this20.scope);
      const context = {};
      (0, _enrichContextFromGlobal().default)(context);
      const removeP = Object.keys(groupedBitsByScope).map(
      /*#__PURE__*/
      function () {
        var _ref3 = (0, _bluebird().coroutine)(function* (key) {
          const resolvedRemote = yield remotes.resolve(key, _this20.scope);
          const idsStr = groupedBitsByScope[key].map(id => id.toStringWithoutVersion());
          return resolvedRemote.deleteMany(idsStr, force, context);
        });

        return function (_x2) {
          return _ref3.apply(this, arguments);
        };
      }());
      return Promise.all(removeP);
    })();
  }
  /**
   * 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.
   */


  cleanFromBitMap(componentsToRemoveFromFs, removedDependencies) {
    var _this21 = this;

    return (0, _bluebird().coroutine)(function* () {
      _logger().default.debug(`consumer.cleanFromBitMap, cleaning ${componentsToRemoveFromFs.toString()} from .bitmap`);

      _this21.bitMap.removeComponents(componentsToRemoveFromFs);

      _this21.bitMap.removeComponents(removedDependencies);
    })();
  }
  /**
   * 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.
   */


  removeLocal(bitIds, force, track, deleteFiles) {
    var _this22 = this;

    return (0, _bluebird().coroutine)(function* () {
      // local remove in case user wants to delete tagged components
      const modifiedComponents = new (_bitId().BitIds)();
      const nonModifiedComponents = new (_bitId().BitIds)();
      if (_ramda().default.isEmpty(bitIds)) return new (_removedComponents().RemovedLocalObjects)();

      if (!force) {
        yield Promise.all(bitIds.map(
        /*#__PURE__*/
        function () {
          var _ref4 = (0, _bluebird().coroutine)(function* (id) {
            try {
              const componentStatus = yield _this22.getComponentStatusById(id);
              if (componentStatus.modified) modifiedComponents.push(id);else nonModifiedComponents.push(id);
            } catch (err) {
              // if a component has an error, such as, missing main file, we do want to allow removing that component
              if (_component().default.isComponentInvalidByErrorType(err)) {
                nonModifiedComponents.push(id);
              } else {
                throw err;
              }
            }
          });

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

      const {
        removedComponentIds,
        missingComponents,
        dependentBits,
        removedDependencies
      } = yield _this22.scope.removeMany(force ? bitIds : nonModifiedComponents, force, true, _this22);

      if (!_ramda().default.isEmpty(removedComponentIds)) {
        yield (0, _deleteComponentFiles().default)(_this22, removedComponentIds, deleteFiles);
        yield (0, _deleteComponentFiles().default)(_this22, removedDependencies, false);

        if (!track) {
          yield packageJsonUtils().removeComponentsFromWorkspacesAndDependencies(_this22, removedComponentIds);
          yield _this22.cleanFromBitMap(removedComponentIds, removedDependencies);
        }
      }

      return new (_removedComponents().RemovedLocalObjects)(removedComponentIds, missingComponents, modifiedComponents, removedDependencies, dependentBits);
    })();
  }

  addRemoteAndLocalVersionsToDependencies(component, loadedFromFileSystem) {
    var _this23 = this;

    return (0, _bluebird().coroutine)(function* () {
      _logger().default.debug(`addRemoteAndLocalVersionsToDependencies for ${component.id.toString()}`);

      _analytics().Analytics.addBreadCrumb('addRemoteAndLocalVersionsToDependencies', `addRemoteAndLocalVersionsToDependencies for ${_analytics().Analytics.hashData(component.id.toString())}`);

      let modelDependencies = new (_dependencies().Dependencies)([]);
      let modelDevDependencies = new (_dependencies().Dependencies)([]);
      let modelCompilerDependencies = new (_dependencies().Dependencies)([]);
      let modelTesterDependencies = new (_dependencies().Dependencies)([]);

      if (loadedFromFileSystem) {
        // when loaded from file-system, the dependencies versions are fetched from bit.map.
        // find the model version of the component and get the stored versions of the dependencies
        const 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;
        }
      }

      yield component.dependencies.addRemoteAndLocalVersions(_this23.scope, modelDependencies);
      yield component.devDependencies.addRemoteAndLocalVersions(_this23.scope, modelDevDependencies);
      yield component.compilerDependencies.addRemoteAndLocalVersions(_this23.scope, modelCompilerDependencies);
      yield component.testerDependencies.addRemoteAndLocalVersions(_this23.scope, modelTesterDependencies);
    })();
  }

  getAuthoredAndImportedDependentsIdsOf(components) {
    var _this24 = this;

    return (0, _bluebird().coroutine)(function* () {
      const authoredAndImportedComponents = _this24.bitMap.getAllBitIds([_constants().COMPONENT_ORIGINS.IMPORTED, _constants().COMPONENT_ORIGINS.AUTHORED]);

      const componentsIds = _bitId().BitIds.fromArray(components.map(c => c.id));

      return _this24.scope.findDirectDependentComponents(authoredAndImportedComponents, componentsIds);
    })();
  }

  getAuthoredAndImportedDependentsComponentsOf(components) {
    var _this25 = this;

    return (0, _bluebird().coroutine)(function* () {
      const dependentsIds = yield _this25.getAuthoredAndImportedDependentsIdsOf(components);

      const scopeComponentsImporter = _scopeComponentsImporter().default.getInstance(_this25.scope);

      const versionDependenciesArr = yield scopeComponentsImporter.importMany(dependentsIds, true, false);
      const manipulateDirData = yield (0, _manipulateDir().getManipulateDirWhenImportingComponents)(_this25.bitMap, versionDependenciesArr, _this25.scope.objects);
      const dependentComponentsP = versionDependenciesArr.map(c => c.component.toConsumer(_this25.scope.objects, manipulateDirData));
      return Promise.all(dependentComponentsP);
    })();
  }

  ejectConf(componentId, {
    ejectPath
  }) {
    var _this26 = this;

    return (0, _bluebird().coroutine)(function* () {
      const component = yield _this26.loadComponent(componentId);
      return component.writeConfig(_this26, ejectPath || _this26.dirStructure.ejectedEnvsDirStructure);
    })();
  }

  injectConf(componentId, force) {
    var _this27 = this;

    return (0, _bluebird().coroutine)(function* () {
      const component = yield _this27.loadComponent(componentId);
      return component.injectConfig(_this27.getPath(), _this27.bitMap, force);
    })();
  }

  _getEnvProps(envType, context) {
    const envs = this.config.getEnvsByType(envType);
    if (!envs) return undefined;
    const envName = Object.keys(envs)[0];
    const envObject = envs[envName];
    return {
      name: envName,
      consumerPath: this.getPath(),
      scopePath: this.scope.getPath(),
      rawConfig: envObject.rawConfig,
      files: envObject.files,
      bitJsonPath: _path().default.dirname(this.config.path),
      options: envObject.options,
      envType,
      context
    };
  }

  onDestroy() {
    var _this28 = this;

    return (0, _bluebird().coroutine)(function* () {
      yield _this28.cleanTmpFolder();
      return _this28.bitMap.write();
    })();
  }

}

exports.default = Consumer;