'use strict';

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

var _regenerator;

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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

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

var _bitJson;

function _load_bitJson() {
  return _bitJson = _interopRequireDefault(require('../bit-json'));
}

var _sources;

function _load_sources() {
  return _sources = require('../component/sources');
}

var _consumerBitJson;

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

var _consumer;

function _load_consumer() {
  return _consumer = _interopRequireDefault(require('../consumer'));
}

var _bitId;

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

var _scope;

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

var _bitIds;

function _load_bitIds() {
  return _bitIds = _interopRequireDefault(require('../../bit-id/bit-ids'));
}

var _parser;

function _load_parser() {
  return _parser = _interopRequireDefault(require('../../jsdoc/parser'));
}

var _specsResults;

function _load_specsResults() {
  return _specsResults = _interopRequireDefault(require('../specs-results'));
}

var _ejectConf;

function _load_ejectConf() {
  return _ejectConf = _interopRequireDefault(require('../component-ops/eject-conf'));
}

var _ejectConf2;

function _load_ejectConf2() {
  return _ejectConf2 = require('../component-ops/eject-conf');
}

var _injectConf;

function _load_injectConf() {
  return _injectConf = _interopRequireDefault(require('../component-ops/inject-conf'));
}

var _componentSpecsFailed;

function _load_componentSpecsFailed() {
  return _componentSpecsFailed = _interopRequireDefault(require('../exceptions/component-specs-failed'));
}

var _missingFilesFromComponent;

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

var _componentNotFoundInPath;

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

var _environment;

function _load_environment() {
  return _environment = _interopRequireDefault(require('../../environment'));
}

var _environment2;

function _load_environment2() {
  return _environment2 = require('../../environment');
}

var _bitMap;

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

var _componentMap;

function _load_componentMap() {
  return _componentMap = _interopRequireDefault(require('../bit-map/component-map'));
}

var _logger;

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

var _loader;

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

var _compilerExtension;

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

var _compilerExtension2;

function _load_compilerExtension2() {
  return _compilerExtension2 = require('../../extensions/compiler-extension');
}

var _testerExtension;

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

var _testerExtension2;

function _load_testerExtension2() {
  return _testerExtension2 = require('../../extensions/tester-extension');
}

var _driver;

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

var _loaderMessages;

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

var _fileSourceNotFound;

function _load_fileSourceNotFound() {
  return _fileSourceNotFound = _interopRequireDefault(require('./exceptions/file-source-not-found'));
}

var _constants;

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

var _componentDependencies;

function _load_componentDependencies() {
  return _componentDependencies = _interopRequireDefault(require('../../scope/component-dependencies'));
}

var _packageJson;

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

var _dependencies;

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

var _dists;

function _load_dists() {
  return _dists = _interopRequireDefault(require('./sources/dists'));
}

var _chalkBox;

function _load_chalkBox() {
  return _chalkBox = require('../../cli/chalk-box');
}

var _externalTestError;

function _load_externalTestError() {
  return _externalTestError = _interopRequireDefault(require('./exceptions/external-test-error'));
}

var _generalError;

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

var _abstractBitJson;

function _load_abstractBitJson() {
  return _abstractBitJson = _interopRequireDefault(require('../bit-json/abstract-bit-json'));
}

var _analytics;

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

var _;

function _load_() {
  return _ = _interopRequireDefault(require('.'));
}

var _componentIssuesTemplate;

function _load_componentIssuesTemplate() {
  return _componentIssuesTemplate = require('../../cli/templates/component-issues-template');
}

var _mainFileRemoved;

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

var _envExtension;

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

var _ejectToWorkspace;

function _load_ejectToWorkspace() {
  return _ejectToWorkspace = _interopRequireDefault(require('./exceptions/eject-to-workspace'));
}

var _ejectBoundToWorkspace;

function _load_ejectBoundToWorkspace() {
  return _ejectBoundToWorkspace = _interopRequireDefault(require('./exceptions/eject-bound-to-workspace'));
}

var _version;

function _load_version() {
  return _version = _interopRequireDefault(require('../../version'));
}

var _injectNonEjected;

function _load_injectNonEjected() {
  return _injectNonEjected = _interopRequireDefault(require('./exceptions/inject-non-ejected'));
}

var _configDir;

function _load_configDir() {
  return _configDir = _interopRequireDefault(require('../bit-map/config-dir'));
}

var _buildComponent;

function _load_buildComponent() {
  return _buildComponent = _interopRequireDefault(require('../component-ops/build-component'));
}

var _extensionFileNotFound;

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

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

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _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 Component = function () {
  _createClass(Component, [{
    key: 'id',
    // used during tagging process. It's the version that going to be saved or saved already in the model

    // whether a component was loaded from the filesystem or converted from the model
    // always populated when the loadedFromFileSystem is true
    // populated when loadedFromFileSystem is true and it exists in the model
    // used by listScope functionality
    // needed for generate links
    get: function get() {
      return new (_bitId || _load_bitId()).default({
        scope: this.scope,
        name: this.name,
        version: this.version
      });
    } // whether stripOriginallySharedDir() method had been called, we don't want to strip it twice
    // otherwise they're saved as npm packages
    // needed to reduce a potentially long path that was used by the author

  }, {
    key: 'docs',
    get: function get() {
      if (!this._docs) {
        this._docs = this.files ? (_ramda || _load_ramda()).default.flatten(this.files.map(function (file) {
          return (0, (_parser || _load_parser()).default)(file.contents.toString(), file.relative);
        })) : [];
      }
      return this._docs;
    }
  }, {
    key: 'driver',
    get: function get() {
      if (!this._driver) {
        this._driver = (_driver || _load_driver()).Driver.load(this.lang);
      }
      return this._driver;
    }
  }]);

  function Component(_ref) {
    var name = _ref.name,
        version = _ref.version,
        scope = _ref.scope,
        files = _ref.files,
        lang = _ref.lang,
        bindingPrefix = _ref.bindingPrefix,
        mainFile = _ref.mainFile,
        compiler = _ref.compiler,
        tester = _ref.tester,
        bitJson = _ref.bitJson,
        dependencies = _ref.dependencies,
        devDependencies = _ref.devDependencies,
        compilerDependencies = _ref.compilerDependencies,
        testerDependencies = _ref.testerDependencies,
        flattenedDependencies = _ref.flattenedDependencies,
        flattenedDevDependencies = _ref.flattenedDevDependencies,
        flattenedCompilerDependencies = _ref.flattenedCompilerDependencies,
        flattenedTesterDependencies = _ref.flattenedTesterDependencies,
        packageDependencies = _ref.packageDependencies,
        devPackageDependencies = _ref.devPackageDependencies,
        peerPackageDependencies = _ref.peerPackageDependencies,
        compilerPackageDependencies = _ref.compilerPackageDependencies,
        testerPackageDependencies = _ref.testerPackageDependencies,
        docs = _ref.docs,
        dists = _ref.dists,
        specsResults = _ref.specsResults,
        license = _ref.license,
        log = _ref.log,
        deprecated = _ref.deprecated,
        origin = _ref.origin,
        detachedCompiler = _ref.detachedCompiler,
        detachedTester = _ref.detachedTester,
        customResolvedPaths = _ref.customResolvedPaths;

    _classCallCheck(this, Component);

    this.dependenciesSavedAsComponents = true;
    this.loadedFromFileSystem = false;

    this.name = name;
    this.version = version;
    this.scope = scope;
    this.files = files;
    this.lang = lang || (_constants || _load_constants()).DEFAULT_LANGUAGE;
    this.bindingPrefix = bindingPrefix || (_constants || _load_constants()).DEFAULT_BINDINGS_PREFIX;
    this.mainFile = (_path || _load_path()).default.normalize(mainFile);
    this.compiler = compiler;
    this.tester = tester;
    this.bitJson = bitJson;
    this.setDependencies(dependencies);
    this.setDevDependencies(devDependencies);
    this.setCompilerDependencies(compilerDependencies);
    this.setTesterDependencies(testerDependencies);
    this.flattenedDependencies = flattenedDependencies || new (_bitIds || _load_bitIds()).default();
    this.flattenedDevDependencies = flattenedDevDependencies || new (_bitIds || _load_bitIds()).default();
    this.flattenedCompilerDependencies = flattenedCompilerDependencies || new (_bitIds || _load_bitIds()).default();
    this.flattenedTesterDependencies = flattenedTesterDependencies || new (_bitIds || _load_bitIds()).default();
    this.packageDependencies = packageDependencies || {};
    this.devPackageDependencies = devPackageDependencies || {};
    this.peerPackageDependencies = peerPackageDependencies || {};
    this.compilerPackageDependencies = compilerPackageDependencies || {};
    this.testerPackageDependencies = testerPackageDependencies || {};
    this._docs = docs;
    this.setDists(dists);
    this.specsResults = specsResults;
    this.license = license;
    this.log = log;
    this.deprecated = deprecated || false;
    this.origin = origin;
    this.detachedCompiler = detachedCompiler;
    this.detachedTester = detachedTester;
    this.customResolvedPaths = customResolvedPaths || [];
    this.validateComponent();
  }

  _createClass(Component, [{
    key: 'validateComponent',
    value: function validateComponent() {
      var _this = this;

      var nonEmptyFields = ['name', 'mainFile'];
      nonEmptyFields.forEach(function (field) {
        if (!_this[field]) {
          throw new (_generalError || _load_generalError()).default(`failed loading a component ${_this.id}, the field "${field}" can't be empty`);
        }
      });
    }

    /**
     * Warning: this method does not return a deep copy for objects properties except dependencies and devDependencies
     * Implement deep copy of other properties if needed
     */

  }, {
    key: 'clone',
    value: function clone() {
      // $FlowFixMe
      var newInstance = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
      newInstance.setDependencies(this.dependencies.getClone());
      newInstance.setDevDependencies(this.devDependencies.getClone());
      newInstance.setCompilerDependencies(this.compilerDependencies.getClone());
      newInstance.setTesterDependencies(this.testerDependencies.getClone());
      return newInstance;
    }
  }, {
    key: 'getTmpFolder',
    value: function getTmpFolder() {
      var workspacePrefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

      var folder = (_path || _load_path()).default.join(workspacePrefix, (_constants || _load_constants()).BIT_WORKSPACE_TMP_DIRNAME, this.id.name);
      if (this.componentMap) {
        var componentDir = this.componentMap.getComponentDir();
        if (componentDir) {
          folder = (_path || _load_path()).default.join(workspacePrefix, componentDir, (_constants || _load_constants()).BIT_WORKSPACE_TMP_DIRNAME);
        }
      }
      // Isolated components (for ci-update for example)
      if (this.isolatedEnvironment && this.writtenPath) {
        // Do not join the workspacePrefix since the written path is already a full path
        folder = (_path || _load_path()).default.join(this.writtenPath, (_constants || _load_constants()).BIT_WORKSPACE_TMP_DIRNAME);
      }
      return folder;
    }
  }, {
    key: 'setDependencies',
    value: function setDependencies(dependencies) {
      this.dependencies = new (_dependencies || _load_dependencies()).Dependencies(dependencies);
    }
  }, {
    key: 'setDevDependencies',
    value: function setDevDependencies(devDependencies) {
      this.devDependencies = new (_dependencies || _load_dependencies()).Dependencies(devDependencies);
    }
  }, {
    key: 'setCompilerDependencies',
    value: function setCompilerDependencies(compilerDependencies) {
      this.compilerDependencies = new (_dependencies || _load_dependencies()).Dependencies(compilerDependencies);
    }
  }, {
    key: 'setTesterDependencies',
    value: function setTesterDependencies(testerDependencies) {
      this.testerDependencies = new (_dependencies || _load_dependencies()).Dependencies(testerDependencies);
    }
  }, {
    key: 'setDists',
    value: function setDists(dists) {
      this.dists = new (_dists || _load_dists()).default(dists);
    }
  }, {
    key: 'getFileExtension',
    value: function getFileExtension() {
      switch (this.lang) {
        case (_constants || _load_constants()).DEFAULT_LANGUAGE:
        default:
          return 'js';
      }
    }
  }, {
    key: 'getDetachedCompiler',
    value: function getDetachedCompiler() {
      return _calculateDetachByOrigin(this.detachedCompiler, this.origin);
    }
  }, {
    key: 'getDetachedTester',
    value: function getDetachedTester() {
      return _calculateDetachByOrigin(this.detachedTester, this.origin);
    }
  }, {
    key: '_getHomepage',
    value: function _getHomepage() {
      // TODO: Validate somehow that this scope is really on bitsrc (maybe check if it contains . ?)
      var homepage = this.scope ? `https://bitsrc.io/${this.scope.replace('.', '/')}/${this.name}` : undefined;
      return homepage;
    }
  }, {
    key: 'writeConfig',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(consumer, configDir) {
        var override = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
        var bitMap, componentMap, configDirInstance, res;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                bitMap = consumer.bitMap;

                this.componentMap = this.componentMap || bitMap.getComponentIfExist(this.id);
                componentMap = this.componentMap;

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

                throw new (_generalError || _load_generalError()).default('could not find component in the .bitmap file');

              case 5:
                configDirInstance = typeof configDir === 'string' ? new (_configDir || _load_configDir()).default(configDir) : configDir.clone();

                if (!configDirInstance.isWorkspaceRoot) {
                  _context.next = 8;
                  break;
                }

                throw new (_ejectToWorkspace || _load_ejectToWorkspace()).default();

              case 8:
                if (!(componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED && !componentMap.detachedCompiler && !componentMap.detachedTester ||
                // Need to be check for false and not falsy for imported components
                componentMap.detachedCompiler === false && componentMap.detachedTester === false)) {
                  _context.next = 10;
                  break;
                }

                throw new (_ejectBoundToWorkspace || _load_ejectBoundToWorkspace()).default();

              case 10:
                _context.next = 12;
                return (0, (_ejectConf || _load_ejectConf()).default)(this, consumer, configDirInstance, override);

              case 12:
                res = _context.sent;

                if (this.componentMap) {
                  this.componentMap.setConfigDir(res.ejectedPath);
                }
                return _context.abrupt('return', res);

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

      function writeConfig(_x3, _x4) {
        return _ref2.apply(this, arguments);
      }

      return writeConfig;
    }()
  }, {
    key: 'injectConfig',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(consumerPath, bitMap) {
        var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var componentMap, configDir, res;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                this.componentMap = this.componentMap || bitMap.getComponentIfExist(this.id);
                componentMap = this.componentMap;

                if (componentMap) {
                  _context2.next = 4;
                  break;
                }

                throw new (_generalError || _load_generalError()).default('could not find component in the .bitmap file');

              case 4:
                configDir = componentMap.configDir;

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

                throw new (_injectNonEjected || _load_injectNonEjected()).default();

              case 7:
                _context2.next = 9;
                return (0, (_injectConf || _load_injectConf()).default)(this, consumerPath, bitMap, configDir, force);

              case 9:
                res = _context2.sent;

                if (this.componentMap) {
                  this.componentMap.setConfigDir();
                }
                return _context2.abrupt('return', res);

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

      function injectConfig(_x6, _x7) {
        return _ref3.apply(this, arguments);
      }

      return injectConfig;
    }()
  }, {
    key: 'getPackageNameAndPath',
    value: function getPackageNameAndPath() {
      var packagePath = `${this.bindingPrefix}/${this.id.name}`;
      var packageName = this.id.toStringWithoutVersion();
      return { packageName, packagePath };
    }
  }, {
    key: 'writePackageJson',
    value: function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(consumer, bitDir) {
        var override = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
        var writeBitDependencies = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
        var excludeRegistryPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
        var packageJsonInstance;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return (_packageJson || _load_packageJson()).write(consumer, this, bitDir, override, writeBitDependencies, excludeRegistryPrefix);

              case 2:
                packageJsonInstance = _context3.sent;

                this.packageJsonInstance = packageJsonInstance;

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

      function writePackageJson(_x11, _x12) {
        return _ref4.apply(this, arguments);
      }

      return writePackageJson;
    }()
  }, {
    key: 'flattenedDependencies',
    value: function flattenedDependencies() {
      return (_bitIds || _load_bitIds()).default.fromObject(this.flattenedDependencies);
    }
  }, {
    key: 'flattenedDevDependencies',
    value: function flattenedDevDependencies() {
      return (_bitIds || _load_bitIds()).default.fromObject(this.flattenedDevDependencies);
    }
  }, {
    key: 'flattenedCompilerDependencies',
    value: function flattenedCompilerDependencies() {
      return (_bitIds || _load_bitIds()).default.fromObject(this.flattenedCompilerDependencies);
    }
  }, {
    key: 'flattenedTesterDependencies',
    value: function flattenedTesterDependencies() {
      return (_bitIds || _load_bitIds()).default.fromObject(this.flattenedTesterDependencies);
    }
  }, {
    key: 'getAllDependencies',
    value: function getAllDependencies() {
      return [].concat(_toConsumableArray(this.dependencies.dependencies), _toConsumableArray(this.devDependencies.dependencies), _toConsumableArray(this.compilerDependencies.dependencies), _toConsumableArray(this.testerDependencies.dependencies));
    }
  }, {
    key: 'getAllNonEnvsDependencies',
    value: function getAllNonEnvsDependencies() {
      return [].concat(_toConsumableArray(this.dependencies.dependencies), _toConsumableArray(this.devDependencies.dependencies));
    }
  }, {
    key: 'getAllDependenciesIds',
    value: function getAllDependenciesIds() {
      var allDependencies = this.getAllDependencies();
      return (_bitIds || _load_bitIds()).default.fromArray(allDependencies.map(function (dependency) {
        return dependency.id;
      }));
    }
  }, {
    key: 'hasDependencies',
    value: function hasDependencies() {
      var allDependencies = this.getAllDependencies();
      return Boolean(allDependencies.length);
    }
  }, {
    key: 'getAllFlattenedDependencies',
    value: function getAllFlattenedDependencies() {
      return [].concat(_toConsumableArray(this.flattenedDependencies), _toConsumableArray(this.flattenedDevDependencies), _toConsumableArray(this.flattenedCompilerDependencies), _toConsumableArray(this.flattenedTesterDependencies));
    }
  }, {
    key: 'getAllNonEnvsFlattenedDependencies',
    value: function getAllNonEnvsFlattenedDependencies() {
      return [].concat(_toConsumableArray(this.flattenedDependencies), _toConsumableArray(this.flattenedDevDependencies));
    }
  }, {
    key: '_writeToComponentDir',
    value: function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(_ref5) {
        var bitDir = _ref5.bitDir,
            writeConfig = _ref5.writeConfig,
            configDir = _ref5.configDir,
            writePackageJson = _ref5.writePackageJson,
            consumer = _ref5.consumer,
            _ref5$override = _ref5.override,
            override = _ref5$override === undefined ? true : _ref5$override,
            _ref5$writeBitDepende = _ref5.writeBitDependencies,
            writeBitDependencies = _ref5$writeBitDepende === undefined ? false : _ref5$writeBitDepende,
            _ref5$deleteBitDirCon = _ref5.deleteBitDirContent,
            deleteBitDirContent = _ref5$deleteBitDirCon === undefined ? false : _ref5$deleteBitDirCon,
            _ref5$excludeRegistry = _ref5.excludeRegistryPrefix,
            excludeRegistryPrefix = _ref5$excludeRegistry === undefined ? false : _ref5$excludeRegistry;
        var resolvedConfigDir;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                if (!deleteBitDirContent) {
                  _context4.next = 4;
                  break;
                }

                (_fsExtra || _load_fsExtra()).default.emptyDirSync(bitDir);
                _context4.next = 6;
                break;

              case 4:
                _context4.next = 6;
                return (0, (_utils || _load_utils()).mkdirp)(bitDir);

              case 6:
                if (!this.files) {
                  _context4.next = 9;
                  break;
                }

                _context4.next = 9;
                return Promise.all(this.files.map(function (file) {
                  return file.write(undefined, override);
                }));

              case 9:
                _context4.next = 11;
                return this.dists.writeDists(this, consumer, false);

              case 11:
                if (!(writeConfig && consumer)) {
                  _context4.next = 15;
                  break;
                }

                resolvedConfigDir = configDir || consumer.dirStructure.ejectedEnvsDirStructure;
                _context4.next = 15;
                return this.writeConfig(consumer, resolvedConfigDir, override);

              case 15:
                if (!(writePackageJson && (consumer.isolated || bitDir !== consumer.getPath()))) {
                  _context4.next = 18;
                  break;
                }

                _context4.next = 18;
                return this.writePackageJson(consumer, bitDir, override, writeBitDependencies, excludeRegistryPrefix);

              case 18:
                if (!(this.license && this.license.src)) {
                  _context4.next = 21;
                  break;
                }

                _context4.next = 21;
                return this.license.write(bitDir, override);

              case 21:
                (_logger || _load_logger()).default.debug('component has been written successfully');
                return _context4.abrupt('return', this);

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

      function _writeToComponentDir(_x13) {
        return _ref6.apply(this, arguments);
      }

      return _writeToComponentDir;
    }()
  }, {
    key: '_addComponentToBitMap',
    value: function _addComponentToBitMap(bitMap, rootDir, origin, parent, configDir) {
      var filesForBitMap = this.files.map(function (file) {
        return { name: file.basename, relativePath: (0, (_utils || _load_utils()).pathNormalizeToLinux)(file.relative), test: file.test };
      });

      return bitMap.addComponent({
        componentId: this.id,
        files: filesForBitMap,
        mainFile: this.mainFile,
        rootDir,
        configDir,
        detachedCompiler: this.detachedCompiler,
        detachedTester: this.detachedTester,
        origin,
        parent,
        originallySharedDir: this.originallySharedDir
      });
    }

    /**
     * Before writing the files into the file-system, remove the path-prefix that is shared among the main component files
     * and its dependencies. It helps to avoid large file-system paths.
     *
     * This is relevant for IMPORTED components only as the author may have long paths that are not needed for whoever
     * imports it. NESTED and AUTHORED components are written as is.
     */

  }, {
    key: 'stripOriginallySharedDir',
    value: function stripOriginallySharedDir(bitMap) {
      if (this._wasOriginallySharedDirStripped) return;
      this.setOriginallySharedDir();
      var originallySharedDir = this.originallySharedDir;
      if (originallySharedDir) {
        (_logger || _load_logger()).default.debug(`stripping originallySharedDir "${originallySharedDir}" from ${this.id}`);
      }
      var pathWithoutSharedDir = function pathWithoutSharedDir(pathStr, sharedDir) {
        if (!sharedDir) return pathStr;
        var partToRemove = (_path || _load_path()).default.normalize(sharedDir) + (_path || _load_path()).default.sep;
        return pathStr.replace(partToRemove, '');
      };
      this.files.forEach(function (file) {
        var newRelative = pathWithoutSharedDir(file.relative, originallySharedDir);
        file.updatePaths({ newBase: file.base, newRelative });
      });
      this.dists.stripOriginallySharedDir(originallySharedDir, pathWithoutSharedDir);
      this.mainFile = pathWithoutSharedDir(this.mainFile, originallySharedDir);
      this.dependencies.stripOriginallySharedDir(bitMap, originallySharedDir);
      this.devDependencies.stripOriginallySharedDir(bitMap, originallySharedDir);
      this.compilerDependencies.stripOriginallySharedDir(bitMap, originallySharedDir);
      this.testerDependencies.stripOriginallySharedDir(bitMap, originallySharedDir);
      this.customResolvedPaths.forEach(function (customPath) {
        customPath.destinationPath = (0, (_utils || _load_utils()).pathNormalizeToLinux)(pathWithoutSharedDir((_path || _load_path()).default.normalize(customPath.destinationPath), originallySharedDir));
      });
      this._wasOriginallySharedDirStripped = true;
    }
  }, {
    key: 'addSharedDir',
    value: function addSharedDir(pathStr) {
      var withSharedDir = this.originallySharedDir ? (_path || _load_path()).default.join(this.originallySharedDir, pathStr) : pathStr;
      return (0, (_utils || _load_utils()).pathNormalizeToLinux)(withSharedDir);
    }
  }, {
    key: 'cloneFilesWithSharedDir',
    value: function cloneFilesWithSharedDir() {
      var _this2 = this;

      return this.files.map(function (file) {
        var newFile = file.clone();
        var newRelative = _this2.addSharedDir(file.relative);
        newFile.updatePaths({ newBase: file.base, newRelative });
        return newFile;
      });
    }

    /**
     * When using this function please check if you really need to pass the bitDir or not
     * It's better to init the files with the correct base, cwd and path than pass it here
     * It's mainly here for cases when we write from the model so this is the first point we actually have the dir
     */

  }, {
    key: 'write',
    value: function () {
      var _ref8 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(_ref7) {
        var bitDir = _ref7.bitDir,
            _ref7$writeConfig = _ref7.writeConfig,
            writeConfig = _ref7$writeConfig === undefined ? false : _ref7$writeConfig,
            configDir = _ref7.configDir,
            _ref7$writePackageJso = _ref7.writePackageJson,
            writePackageJson = _ref7$writePackageJso === undefined ? true : _ref7$writePackageJso,
            _ref7$override = _ref7.override,
            override = _ref7$override === undefined ? true : _ref7$override,
            origin = _ref7.origin,
            parent = _ref7.parent,
            consumer = _ref7.consumer,
            _ref7$writeBitDepende = _ref7.writeBitDependencies,
            writeBitDependencies = _ref7$writeBitDepende === undefined ? false : _ref7$writeBitDepende,
            deleteBitDirContent = _ref7.deleteBitDirContent,
            componentMap = _ref7.componentMap,
            _ref7$excludeRegistry = _ref7.excludeRegistryPrefix,
            excludeRegistryPrefix = _ref7$excludeRegistry === undefined ? false : _ref7$excludeRegistry;
        var consumerPath, bitMap, calculatedBitDir, oldLocation, newBase, rootDir, resolvedConfigDir, componentMapExistWithSameVersion, updateBitMap, actualWithPackageJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                (_logger || _load_logger()).default.debug(`consumer-component.write, id: ${this.id.toString()}`);
                consumerPath = consumer ? consumer.getPath() : undefined;
                bitMap = consumer ? consumer.bitMap : undefined;

                if (this.files) {
                  _context5.next = 5;
                  break;
                }

                throw new (_generalError || _load_generalError()).default(`Component ${this.id.toString()} is invalid as it has no files`);

              case 5:
                // Take the bitdir from the files (it will be the same for all the files of course)
                calculatedBitDir = bitDir || this.files[0].base;
                // Update files base dir according to bitDir

                if (this.files && bitDir) this.files.forEach(function (file) {
                  return file.updatePaths({ newBase: bitDir });
                });
                if (!this.dists.isEmpty() && bitDir) this.dists.get().forEach(function (dist) {
                  return dist.updatePaths({ newBase: bitDir });
                });

                // if bitMap parameter is empty, for instance, when it came from the scope, ignore bitMap altogether.
                // otherwise, check whether this component is in bitMap:
                // if it's there, write the files according to the paths in bit.map.
                // Otherwise, write to bitDir and update bitMap with the new paths.

                if (bitMap) {
                  _context5.next = 10;
                  break;
                }

                return _context5.abrupt('return', this._writeToComponentDir({
                  bitDir: calculatedBitDir,
                  writeConfig,
                  writePackageJson,
                  consumer,
                  override,
                  writeBitDependencies,
                  excludeRegistryPrefix
                }));

              case 10:
                if (!componentMap) {
                  // if there is no componentMap, the component is new to this project and should be written to bit.map
                  componentMap = this._addComponentToBitMap(bitMap, calculatedBitDir, origin, parent, configDir);
                }
                if (!consumer.shouldDistsBeInsideTheComponent() && this.dists.isEmpty()) {
                  // since the dists are set to be outside the components dir, the source files must be saved there
                  // otherwise, other components in dists won't be able to link to this component
                  this.copyFilesIntoDists();
                }
                // For IMPORTED component we have to delete the content of the directory before importing.
                // Otherwise, when the author adds new files outside of the previous originallySharedDir and this user imports them
                // the environment will contain both copies, the old one with the old originallySharedDir and the new one.
                // If a user made changes to the imported component, it will show a warning and stop the process.
                if (typeof deleteBitDirContent === 'undefined') {
                  deleteBitDirContent = origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED;
                }
                // when there is componentMap, this component (with this version or other version) is already part of the project.
                // There are several options as to what was the origin before and what is the origin now and according to this,
                // we update/remove/don't-touch the record in bit.map.
                // The current origin can't be AUTHORED because when the author creates a component for the first time,
                // 1) current origin is AUTHORED - If the version is the same as before, don't update bit.map. Otherwise, update.
                // 2) current origin is IMPORTED - If the version is the same as before, don't update bit.map. Otherwise, update.
                // one exception is where the origin was NESTED before, in this case, remove the current record and add a new one.
                // 3) current origin is NESTED - the version can't be the same as before (otherwise it would be ignored before and
                // never reach this function, see @write-components.writeToComponentsDir). Therefore, always add to bit.map.
                if (origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED && componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED) {
                  // when a user imports a component that was a dependency before, write the component directly into the components
                  // directory for an easy access/change. Then, remove the current record from bit.map and add an updated one.
                  oldLocation = (_path || _load_path()).default.join(consumerPath, componentMap.rootDir);

                  (_logger || _load_logger()).default.debug(`deleting the old directory of a component at ${oldLocation}, the new directory is ${calculatedBitDir}`);
                  (_fsExtra || _load_fsExtra()).default.removeSync(oldLocation);
                  bitMap.removeComponent(this.id);
                  componentMap = this._addComponentToBitMap(bitMap, calculatedBitDir, origin, parent, configDir);
                }
                (_logger || _load_logger()).default.debug('component is in bit.map, write the files according to bit.map');
                if (componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED) writeConfig = false;
                newBase = componentMap.rootDir ? (_path || _load_path()).default.join(consumerPath, componentMap.rootDir) : consumerPath;

                this.writtenPath = newBase;
                this.files.forEach(function (file) {
                  return file.updatePaths({ newBase });
                });
                rootDir = componentMap.rootDir;
                resolvedConfigDir = configDir || componentMap.configDir;
                componentMapExistWithSameVersion = bitMap.isExistWithSameVersion(this.id);
                updateBitMap = !componentMapExistWithSameVersion || componentMap.originallySharedDir !== this.originallySharedDir;
                // update bitMap before writing the files to the filesystem, because as part of writing the
                // package-json file, the componentMap is needed to be stored with the updated version

                if (updateBitMap) {
                  if (componentMapExistWithSameVersion) {
                    // originallySharedDir has been changed. it affects also the relativePath of the files
                    // so it's better to just remove the old record and add a new one
                    bitMap.removeComponent(this.id);
                  }
                  this._addComponentToBitMap(bitMap, rootDir, origin, parent, resolvedConfigDir);
                }

                // Don't write the package.json for an authored component, because it's dependencies probably managed
                // By the root package.json
                actualWithPackageJson = writePackageJson && origin !== (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED;
                _context5.next = 27;
                return this._writeToComponentDir({
                  bitDir: newBase,
                  writeConfig,
                  configDir: resolvedConfigDir,
                  writePackageJson: actualWithPackageJson,
                  consumer,
                  override,
                  writeBitDependencies,
                  deleteBitDirContent,
                  excludeRegistryPrefix
                });

              case 27:
                return _context5.abrupt('return', this);

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

      function write(_x14) {
        return _ref8.apply(this, arguments);
      }

      return write;
    }()
  }, {
    key: 'build',
    value: function () {
      var _ref10 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(_ref9) {
        var scope = _ref9.scope,
            save = _ref9.save,
            consumer = _ref9.consumer,
            noCache = _ref9.noCache,
            verbose = _ref9.verbose,
            keep = _ref9.keep;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                return _context6.abrupt('return', (0, (_buildComponent || _load_buildComponent()).default)({
                  component: this,
                  scope,
                  save,
                  consumer,
                  noCache,
                  verbose,
                  keep
                }));

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

      function build(_x15) {
        return _ref10.apply(this, arguments);
      }

      return build;
    }()
  }, {
    key: 'runSpecs',
    value: function () {
      var _ref12 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(_ref11) {
        var _this3 = this;

        var scope = _ref11.scope,
            _ref11$rejectOnFailur = _ref11.rejectOnFailure,
            rejectOnFailure = _ref11$rejectOnFailur === undefined ? false : _ref11$rejectOnFailur,
            consumer = _ref11.consumer,
            save = _ref11.save,
            verbose = _ref11.verbose,
            isolated = _ref11.isolated,
            directory = _ref11.directory,
            keep = _ref11.keep;
        var testFiles, consumerPath, tester, testerFilePath, run, isolatedEnvironment, isolateOpts, localTesterPath, componentWithDependencies, component, specDistWrite, results;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                testFiles = this.files.filter(function (file) {
                  return file.test;
                });
                consumerPath = consumer ? consumer.getPath() : '';

                if (!(!this.tester || !testFiles || (_ramda || _load_ramda()).default.isEmpty(testFiles))) {
                  _context9.next = 4;
                  break;
                }

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

              case 4:

                (_logger || _load_logger()).default.debug('tester found, start running tests');
                (_analytics || _load_analytics()).Analytics.addBreadCrumb('runSpecs', 'tester found, start running tests');
                tester = this.tester;

                if (tester.loaded) {
                  _context9.next = 12;
                  break;
                }

                (_analytics || _load_analytics()).Analytics.addBreadCrumb('runSpecs', 'installing missing tester');
                _context9.next = 11;
                return tester.install(scope, { verbose });

              case 11:
                (_logger || _load_logger()).default.debug('Environment components are installed');

              case 12:
                testerFilePath = tester.filePath;

                run = function () {
                  var _ref13 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(component, cwd) {
                    var testFilesList, specsResults, tmpFolderFullPath, contextPaths, shouldWriteConfig, context, actionParams, oneFileSpecResult, specsResultsP, specsResultsPretty, componentIdPretty, specsResultsAndIdPretty;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
                      while (1) {
                        switch (_context8.prev = _context8.next) {
                          case 0:
                            if (cwd) {
                              (_logger || _load_logger()).default.debug(`changing process cwd to ${cwd}`);
                              (_analytics || _load_analytics()).Analytics.addBreadCrumb('runSpecs.run', 'changing process cwd');
                              process.chdir(cwd);
                            }
                            (_loader || _load_loader()).default.start((_loaderMessages || _load_loaderMessages()).BEFORE_RUNNING_SPECS);
                            testFilesList = !component.dists.isEmpty() ? component.dists.get().filter(function (dist) {
                              return dist.test;
                            }) : component.files.filter(function (file) {
                              return file.test;
                            });
                            specsResults = void 0;
                            tmpFolderFullPath = void 0;
                            contextPaths = void 0;

                            if (_this3.tester && _this3.tester.context) {
                              contextPaths = _this3.tester.context;
                            } else if (consumer && consumer.bitMap) {
                              contextPaths = {
                                workspaceDir: consumer.bitMap.projectRoot
                              };
                            }
                            _context8.prev = 7;

                            if (!(tester && tester.action)) {
                              _context8.next = 29;
                              break;
                            }

                            (_logger || _load_logger()).default.debug('running tests using new format');
                            (_analytics || _load_analytics()).Analytics.addBreadCrumb('runSpecs.run', 'running tests using new format');
                            shouldWriteConfig = tester.writeConfigFilesOnAction && component.getDetachedTester();

                            if (!shouldWriteConfig) {
                              _context8.next = 17;
                              break;
                            }

                            tmpFolderFullPath = component.getTmpFolder(consumerPath);
                            if (verbose) {
                              console.log(`\nwriting config files to ${tmpFolderFullPath}`); // eslint-disable-line no-console
                            }
                            _context8.next = 17;
                            return (0, (_ejectConf2 || _load_ejectConf2()).writeEnvFiles)({
                              fullConfigDir: tmpFolderFullPath,
                              env: tester,
                              consumer,
                              component,
                              deleteOldFiles: false,
                              verbose: !!verbose
                            });

                          case 17:
                            context = {
                              componentObject: component.toObject()
                            };


                            contextPaths && Object.assign(context, contextPaths);

                            actionParams = {
                              testFiles: testFilesList,
                              rawConfig: tester.rawConfig,
                              dynamicConfig: tester.dynamicConfig,
                              configFiles: tester.files,
                              api: tester.api,
                              context
                            };
                            _context8.next = 22;
                            return tester.action(actionParams);

                          case 22:
                            specsResults = _context8.sent;

                            if (!tmpFolderFullPath) {
                              _context8.next = 27;
                              break;
                            }

                            if (verbose) {
                              console.log(`deleting tmp directory ${tmpFolderFullPath}`); // eslint-disable-line no-console
                            }
                            _context8.next = 27;
                            return (_fsExtra || _load_fsExtra()).default.remove(tmpFolderFullPath);

                          case 27:
                            _context8.next = 36;
                            break;

                          case 29:
                            (_logger || _load_logger()).default.debug('running tests using old format');
                            (_analytics || _load_analytics()).Analytics.addBreadCrumb('runSpecs.run', 'running tests using old format');

                            oneFileSpecResult = function () {
                              var _ref14 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(testFile) {
                                var testFilePath, results, failures, _results;

                                return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
                                  while (1) {
                                    switch (_context7.prev = _context7.next) {
                                      case 0:
                                        testFilePath = testFile.path;
                                        _context7.prev = 1;
                                        _context7.next = 4;
                                        return tester.oldAction(testFilePath);

                                      case 4:
                                        results = _context7.sent;

                                        results.specPath = testFile.relative;
                                        return _context7.abrupt('return', results);

                                      case 9:
                                        _context7.prev = 9;
                                        _context7.t0 = _context7['catch'](1);
                                        failures = [{
                                          title: _context7.t0.message,
                                          err: _context7.t0
                                        }];
                                        _results = {
                                          specPath: testFile.relative,
                                          pass: false,
                                          tests: [],
                                          failures
                                        };
                                        return _context7.abrupt('return', _results);

                                      case 14:
                                      case 'end':
                                        return _context7.stop();
                                    }
                                  }
                                }, _callee7, _this3, [[1, 9]]);
                              }));

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

                            specsResultsP = testFilesList.map(oneFileSpecResult);
                            _context8.next = 35;
                            return Promise.all(specsResultsP);

                          case 35:
                            specsResults = _context8.sent;

                          case 36:
                            _context8.next = 42;
                            break;

                          case 38:
                            _context8.prev = 38;
                            _context8.t0 = _context8['catch'](7);

                            if (tmpFolderFullPath) {
                              (_fsExtra || _load_fsExtra()).default.removeSync(tmpFolderFullPath);
                            }
                            throw new (_externalTestError || _load_externalTestError()).default(_context8.t0, _this3.id.toString());

                          case 42:

                            _this3.specsResults = specsResults.map(function (specRes) {
                              return (_specsResults || _load_specsResults()).default.createFromRaw(specRes);
                            });

                            if (!(rejectOnFailure && !_this3.specsResults.every(function (element) {
                              return element.pass;
                            }))) {
                              _context8.next = 51;
                              break;
                            }

                            // some or all the tests were failed.
                            (_loader || _load_loader()).default.stop();

                            if (!verbose) {
                              _context8.next = 50;
                              break;
                            }

                            // $FlowFixMe this.specsResults is not null at this point
                            specsResultsPretty = (0, (_chalkBox || _load_chalkBox()).paintSpecsResults)(_this3.specsResults).join('\n');
                            componentIdPretty = (_chalk || _load_chalk()).default.bold.white(_this3.id.toString());
                            specsResultsAndIdPretty = `${componentIdPretty}${specsResultsPretty}\n`;
                            return _context8.abrupt('return', Promise.reject(new (_componentSpecsFailed || _load_componentSpecsFailed()).default(specsResultsAndIdPretty)));

                          case 50:
                            return _context8.abrupt('return', Promise.reject(new (_componentSpecsFailed || _load_componentSpecsFailed()).default()));

                          case 51:
                            if (!save) {
                              _context8.next = 54;
                              break;
                            }

                            _context8.next = 54;
                            return scope.sources.modifySpecsResults({
                              source: _this3,
                              specsResults: _this3.specsResults
                            });

                          case 54:
                            return _context8.abrupt('return', _this3.specsResults);

                          case 55:
                          case 'end':
                            return _context8.stop();
                        }
                      }
                    }, _callee8, _this3, [[7, 38]]);
                  }));

                  return function run(_x17, _x18) {
                    return _ref13.apply(this, arguments);
                  };
                }();

                if (!(!isolated && consumer)) {
                  _context9.next = 21;
                  break;
                }

                (_logger || _load_logger()).default.debug('Building the component before running the tests');
                _context9.next = 18;
                return this.build({ scope, verbose, consumer });

              case 18:
                _context9.next = 20;
                return this.dists.writeDists(this, consumer);

              case 20:
                return _context9.abrupt('return', run(this, consumer.getPath()));

              case 21:
                isolatedEnvironment = new (_environment || _load_environment()).default(scope, directory);
                _context9.prev = 22;
                _context9.next = 25;
                return isolatedEnvironment.create();

              case 25:
                isolateOpts = {
                  verbose,
                  dist: true,
                  installPackages: true,
                  installPeerDependencies: true,
                  noPackageJson: false
                };
                localTesterPath = (_path || _load_path()).default.join(isolatedEnvironment.getPath(), 'tester');
                _context9.next = 29;
                return isolatedEnvironment.isolateComponent(this.id, isolateOpts);

              case 29:
                componentWithDependencies = _context9.sent;


                (0, (_utils || _load_utils()).createSymlinkOrCopy)(testerFilePath, localTesterPath);
                component = componentWithDependencies.component;

                component.isolatedEnvironment = isolatedEnvironment;
                (_logger || _load_logger()).default.debug(`the component ${this.id.toString()} has been imported successfully into an isolated environment`);

                _context9.next = 36;
                return component.build({ scope, verbose });

              case 36:
                if (component.dists.isEmpty()) {
                  _context9.next = 40;
                  break;
                }

                specDistWrite = component.dists.get().map(function (file) {
                  return file.write();
                });
                _context9.next = 40;
                return Promise.all(specDistWrite);

              case 40:
                _context9.next = 42;
                return run(component);

              case 42:
                results = _context9.sent;

                if (keep) {
                  _context9.next = 46;
                  break;
                }

                _context9.next = 46;
                return isolatedEnvironment.destroy();

              case 46:
                return _context9.abrupt('return', results);

              case 49:
                _context9.prev = 49;
                _context9.t0 = _context9['catch'](22);
                _context9.next = 53;
                return isolatedEnvironment.destroy();

              case 53:
                return _context9.abrupt('return', Promise.reject(_context9.t0));

              case 54:
              case 'end':
                return _context9.stop();
            }
          }
        }, _callee9, this, [[22, 49]]);
      }));

      function runSpecs(_x16) {
        return _ref12.apply(this, arguments);
      }

      return runSpecs;
    }()
  }, {
    key: 'isolate',
    value: function () {
      var _ref15 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(scope, opts) {
        var isolatedEnvironment;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee10$(_context10) {
          while (1) {
            switch (_context10.prev = _context10.next) {
              case 0:
                isolatedEnvironment = new (_environment || _load_environment()).default(scope, opts.writeToPath);
                _context10.prev = 1;
                _context10.next = 4;
                return isolatedEnvironment.create();

              case 4:
                _context10.next = 6;
                return isolatedEnvironment.isolateComponent(this.id, opts);

              case 6:
                return _context10.abrupt('return', isolatedEnvironment.path);

              case 9:
                _context10.prev = 9;
                _context10.t0 = _context10['catch'](1);
                _context10.next = 13;
                return isolatedEnvironment.destroy();

              case 13:
                throw new (_generalError || _load_generalError()).default(_context10.t0);

              case 14:
              case 'end':
                return _context10.stop();
            }
          }
        }, _callee10, this, [[1, 9]]);
      }));

      function isolate(_x20, _x21) {
        return _ref15.apply(this, arguments);
      }

      return isolate;
    }()
  }, {
    key: 'toObject',
    value: function toObject() {
      return {
        name: this.name,
        version: this.version,
        mainFile: this.mainFile,
        scope: this.scope,
        lang: this.lang,
        bindingPrefix: this.bindingPrefix,
        compiler: this.compiler ? this.compiler.toObject() : null,
        tester: this.tester ? this.tester.toObject() : null,
        detachedCompiler: this.detachedCompiler,
        detachedTester: this.detachedTester,
        dependencies: this.dependencies.serialize(),
        devDependencies: this.devDependencies.serialize(),
        compilerDependencies: this.compilerDependencies.serialize(),
        testerDependencies: this.testerDependencies.serialize(),
        packageDependencies: this.packageDependencies,
        devPackageDependencies: this.devPackageDependencies,
        peerPackageDependencies: this.peerPackageDependencies,
        compilerPackageDependencies: this.compilerPackageDependencies,
        testerPackageDependencies: this.testerPackageDependencies,
        files: this.files,
        docs: this.docs,
        dists: this.dists,
        specsResults: this.specsResults ? this.specsResults.map(function (res) {
          return res.serialize();
        }) : null,
        license: this.license ? this.license.serialize() : null,
        log: this.log,
        deprecated: this.deprecated
      };
    }
  }, {
    key: 'toString',
    value: function toString() {
      return JSON.stringify(this.toObject());
    }
  }, {
    key: 'copyFilesIntoDists',
    value: function copyFilesIntoDists() {
      var dists = this.files.map(function (file) {
        return new (_sources || _load_sources()).Dist({ base: file.base, path: file.path, contents: file.contents });
      });
      this.setDists(dists);
    }

    /**
     * find a shared directory among the files of the main component and its dependencies
     */

  }, {
    key: 'setOriginallySharedDir',
    value: function setOriginallySharedDir() {
      if (this.originallySharedDir !== undefined) return;
      var pathSep = '/'; // it works for Windows as well as all paths are normalized to Linux
      var filePaths = this.files.map(function (file) {
        return (0, (_utils || _load_utils()).pathNormalizeToLinux)(file.relative);
      });
      var dependenciesPaths = this.dependencies.getSourcesPaths();
      var devDependenciesPaths = this.devDependencies.getSourcesPaths();
      var compilerDependenciesPaths = this.compilerDependencies.getSourcesPaths();
      var testerDependenciesPaths = this.testerDependencies.getSourcesPaths();
      var allPaths = [].concat(_toConsumableArray(filePaths), _toConsumableArray(dependenciesPaths), _toConsumableArray(devDependenciesPaths), _toConsumableArray(compilerDependenciesPaths), _toConsumableArray(testerDependenciesPaths));
      var sharedStart = (0, (_utils || _load_utils()).sharedStartOfArray)(allPaths);
      if (!sharedStart || !sharedStart.includes(pathSep)) return;
      var lastPathSeparator = sharedStart.lastIndexOf(pathSep);
      this.originallySharedDir = sharedStart.substring(0, lastPathSeparator);
    }
  }, {
    key: 'toComponentWithDependencies',
    value: function () {
      var _ref16 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11(consumer) {
        var _this4 = this;

        var getFlatten, getDependenciesComponents, dependencies, devDependencies, compilerDependencies, testerDependencies;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                getFlatten = function getFlatten(field) {
                  // when loaded from filesystem, it doesn't have the flatten, fetch them from model.
                  return _this4.loadedFromFileSystem ? _this4.componentFromModel[field] : _this4[field];
                };

                getDependenciesComponents = function getDependenciesComponents(ids) {
                  return Promise.all(ids.map(function (dependencyId) {
                    if (consumer.bitMap.isExistWithSameVersion(dependencyId)) {
                      return consumer.loadComponent(dependencyId);
                    }
                    // when dependencies are imported as npm packages, they are not in bit.map
                    _this4.dependenciesSavedAsComponents = false;
                    return consumer.scope.loadComponent(dependencyId, false);
                  }));
                };

                _context11.next = 4;
                return getDependenciesComponents(getFlatten('flattenedDependencies'));

              case 4:
                dependencies = _context11.sent;
                _context11.next = 7;
                return getDependenciesComponents(getFlatten('flattenedDevDependencies'));

              case 7:
                devDependencies = _context11.sent;
                _context11.next = 10;
                return getDependenciesComponents(getFlatten('flattenedCompilerDependencies'));

              case 10:
                compilerDependencies = _context11.sent;
                _context11.next = 13;
                return getDependenciesComponents(getFlatten('flattenedTesterDependencies'));

              case 13:
                testerDependencies = _context11.sent;
                return _context11.abrupt('return', new (_componentDependencies || _load_componentDependencies()).default({
                  component: this,
                  dependencies,
                  devDependencies,
                  compilerDependencies,
                  testerDependencies
                }));

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

      function toComponentWithDependencies(_x22) {
        return _ref16.apply(this, arguments);
      }

      return toComponentWithDependencies;
    }()
  }, {
    key: 'copyDependenciesFromModel',
    value: function copyDependenciesFromModel(ids) {
      var _this5 = this;

      var componentFromModel = this.componentFromModel;
      if (!componentFromModel) throw new Error('copyDependenciesFromModel: component is missing from the model');
      ids.forEach(function (id) {
        var addDependency = function addDependency(modelDependencies, dependencies) {
          var dependency = modelDependencies.getByIdStr(id);
          if (dependency) dependencies.add(dependency);
          return Boolean(dependency);
        };
        var addedDep = addDependency(componentFromModel.dependencies, _this5.dependencies);
        if (addedDep) return;
        var addedDevDep = addDependency(componentFromModel.devDependencies, _this5.devDependencies);
        if (addedDevDep) return;
        var addedCompilerDep = addDependency(componentFromModel.compilerDependencies, _this5.compilerDependencies);
        if (addedCompilerDep) return;
        var addedTesterDep = addDependency(componentFromModel.testerDependencies, _this5.testerDependencies);
        if (addedTesterDep) return;
        throw new Error(`copyDependenciesFromModel unable to find dependency ${id} in the model`);
      });
    }
  }], [{
    key: 'isComponentInvalidByErrorType',
    value: function isComponentInvalidByErrorType(err) {
      var invalidComponentErrors = [(_mainFileRemoved || _load_mainFileRemoved()).default, (_missingFilesFromComponent || _load_missingFilesFromComponent()).default, (_componentNotFoundInPath || _load_componentNotFoundInPath()).default, (_extensionFileNotFound || _load_extensionFileNotFound()).default];
      return invalidComponentErrors.some(function (errorType) {
        return err instanceof errorType;
      });
    }
  }, {
    key: 'fromObject',
    value: function () {
      var _ref17 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(object) {
        var name, box, version, scope, lang, bindingPrefix, compiler, tester, detachedCompiler, detachedTester, dependencies, devDependencies, compilerDependencies, testerDependencies, packageDependencies, devPackageDependencies, peerPackageDependencies, compilerPackageDependencies, testerPackageDependencies, docs, mainFile, dists, files, specsResults, license, deprecated;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee12$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                name = object.name, box = object.box, version = object.version, scope = object.scope, lang = object.lang, bindingPrefix = object.bindingPrefix, compiler = object.compiler, tester = object.tester, detachedCompiler = object.detachedCompiler, detachedTester = object.detachedTester, dependencies = object.dependencies, devDependencies = object.devDependencies, compilerDependencies = object.compilerDependencies, testerDependencies = object.testerDependencies, packageDependencies = object.packageDependencies, devPackageDependencies = object.devPackageDependencies, peerPackageDependencies = object.peerPackageDependencies, compilerPackageDependencies = object.compilerPackageDependencies, testerPackageDependencies = object.testerPackageDependencies, docs = object.docs, mainFile = object.mainFile, dists = object.dists, files = object.files, specsResults = object.specsResults, license = object.license, deprecated = object.deprecated;
                _context12.t0 = Component;
                _context12.t1 = box ? `${box}/${name}` : name;
                _context12.t2 = version;
                _context12.t3 = scope;
                _context12.t4 = lang;
                _context12.t5 = bindingPrefix;

                if (!compiler) {
                  _context12.next = 13;
                  break;
                }

                _context12.next = 10;
                return (_compilerExtension || _load_compilerExtension()).default.loadFromModelObject(compiler);

              case 10:
                _context12.t6 = _context12.sent;
                _context12.next = 14;
                break;

              case 13:
                _context12.t6 = null;

              case 14:
                _context12.t7 = _context12.t6;

                if (!tester) {
                  _context12.next = 21;
                  break;
                }

                _context12.next = 18;
                return (_testerExtension || _load_testerExtension()).default.loadFromModelObject(tester);

              case 18:
                _context12.t8 = _context12.sent;
                _context12.next = 22;
                break;

              case 21:
                _context12.t8 = null;

              case 22:
                _context12.t9 = _context12.t8;
                _context12.t10 = detachedCompiler;
                _context12.t11 = detachedTester;
                _context12.t12 = dependencies;
                _context12.t13 = devDependencies;
                _context12.t14 = compilerDependencies;
                _context12.t15 = testerDependencies;
                _context12.t16 = packageDependencies;
                _context12.t17 = devPackageDependencies;
                _context12.t18 = peerPackageDependencies;
                _context12.t19 = compilerPackageDependencies;
                _context12.t20 = testerPackageDependencies;
                _context12.t21 = mainFile;
                _context12.t22 = files;
                _context12.t23 = docs;
                _context12.t24 = dists;
                _context12.t25 = specsResults ? (_specsResults || _load_specsResults()).default.deserialize(specsResults) : null;
                _context12.t26 = license ? (_sources || _load_sources()).License.deserialize(license) : null;
                _context12.t27 = deprecated || false;
                _context12.t28 = {
                  name: _context12.t1,
                  version: _context12.t2,
                  scope: _context12.t3,
                  lang: _context12.t4,
                  bindingPrefix: _context12.t5,
                  compiler: _context12.t7,
                  tester: _context12.t9,
                  detachedCompiler: _context12.t10,
                  detachedTester: _context12.t11,
                  dependencies: _context12.t12,
                  devDependencies: _context12.t13,
                  compilerDependencies: _context12.t14,
                  testerDependencies: _context12.t15,
                  packageDependencies: _context12.t16,
                  devPackageDependencies: _context12.t17,
                  peerPackageDependencies: _context12.t18,
                  compilerPackageDependencies: _context12.t19,
                  testerPackageDependencies: _context12.t20,
                  mainFile: _context12.t21,
                  files: _context12.t22,
                  docs: _context12.t23,
                  dists: _context12.t24,
                  specsResults: _context12.t25,
                  license: _context12.t26,
                  deprecated: _context12.t27
                };
                return _context12.abrupt('return', new _context12.t0(_context12.t28));

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

      function fromObject(_x23) {
        return _ref17.apply(this, arguments);
      }

      return fromObject;
    }()
  }, {
    key: 'fromString',
    value: function () {
      var _ref18 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee13(str) {
        var object;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee13$(_context13) {
          while (1) {
            switch (_context13.prev = _context13.next) {
              case 0:
                object = JSON.parse(str);

                object.files = (_sources || _load_sources()).SourceFile.loadFromParsedStringArray(object.files);

                // added if statement to support new and old version of remote ls
                // old version of bit returns from server array of dists  and new version return object
                if (object.dists && Array.isArray(object.dists)) {
                  object.dists = (_sources || _load_sources()).Dist.loadFromParsedStringArray(object.dists);
                } else if (object.dists && object.dists.dists) {
                  object.dists = (_sources || _load_sources()).Dist.loadFromParsedStringArray(object.dists.dists);
                }
                return _context13.abrupt('return', this.fromObject(object));

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

      function fromString(_x24) {
        return _ref18.apply(this, arguments);
      }

      return fromString;
    }()
  }, {
    key: 'loadFromFileSystem',
    value: function () {
      var _ref20 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee15(_ref19) {
        var _this6 = this;

        var bitDir = _ref19.bitDir,
            componentMap = _ref19.componentMap,
            id = _ref19.id,
            consumer = _ref19.consumer,
            componentFromModel = _ref19.componentFromModel;

        var consumerPath, consumerBitJson, bitMap, deprecated, configDir, componentDir, dists, packageDependencies, devPackageDependencies, peerPackageDependencies, getLoadedFiles, resolvedBaseConfigDir, componentBitJson, componentBitJsonFileExist, rawComponentBitJson, bitJson, envsContext, propsToLoadEnvs, compilerP, testerP, _ref22, _ref23, compiler, tester, compilerDynamicPackageDependencies, testerDynamicPackageDependencies, modelCompilerPackageDependencies, modelTesterPackageDependencies, compilerPackageDependencies, testerPackageDependencies;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee15$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                consumerPath = consumer.getPath();
                consumerBitJson = consumer.bitJson;
                bitMap = consumer.bitMap;
                deprecated = componentFromModel ? componentFromModel.deprecated : false;
                configDir = consumer.getPath();
                componentDir = componentMap.getComponentDir();

                configDir = componentDir ? (_path || _load_path()).default.join(configDir, componentDir) : configDir;
                dists = componentFromModel ? componentFromModel.dists.get() : undefined;
                packageDependencies = void 0;
                devPackageDependencies = void 0;
                peerPackageDependencies = void 0;

                getLoadedFiles = function () {
                  var _ref21 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee14() {
                    var sourceFiles, filesToDelete, origin;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee14$(_context14) {
                      while (1) {
                        switch (_context14.prev = _context14.next) {
                          case 0:
                            sourceFiles = [];
                            _context14.next = 3;
                            return componentMap.trackDirectoryChanges(consumer, id);

                          case 3:
                            filesToDelete = [];
                            origin = componentMap.origin;

                            componentMap.files.forEach(function (file) {
                              var filePath = (_path || _load_path()).default.join(bitDir, file.relativePath);
                              try {
                                var sourceFile = (_sources || _load_sources()).SourceFile.load(filePath, consumerBitJson.distTarget, bitDir, consumerPath, {
                                  test: file.test
                                });
                                sourceFiles.push(sourceFile);
                              } catch (err) {
                                if (!(err instanceof (_fileSourceNotFound || _load_fileSourceNotFound()).default)) throw err;
                                (_logger || _load_logger()).default.warn(`a file ${filePath} will be deleted from bit.map as it does not exist on the file system`);
                                filesToDelete.push(file);
                              }
                            });

                            if (!filesToDelete.length) {
                              _context14.next = 12;
                              break;
                            }

                            if (sourceFiles.length) {
                              _context14.next = 9;
                              break;
                            }

                            throw new (_missingFilesFromComponent || _load_missingFilesFromComponent()).default(id.toString());

                          case 9:
                            filesToDelete.forEach(function (fileToDelete) {
                              if (fileToDelete.relativePath === componentMap.mainFile) {
                                throw new (_mainFileRemoved || _load_mainFileRemoved()).default(componentMap.mainFile, id.toString());
                              }
                            });
                            componentMap.removeFiles(filesToDelete);
                            bitMap.hasChanged = true;

                          case 12:
                            return _context14.abrupt('return', sourceFiles);

                          case 13:
                          case 'end':
                            return _context14.stop();
                        }
                      }
                    }, _callee14, _this6);
                  }));

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

                if ((_fsExtra || _load_fsExtra()).default.existsSync(bitDir)) {
                  _context15.next = 14;
                  break;
                }

                throw new (_componentNotFoundInPath || _load_componentNotFoundInPath()).default(bitDir);

              case 14:
                if (!componentMap.configDir) {
                  _context15.next = 19;
                  break;
                }

                _context15.next = 17;
                return componentMap.deleteConfigDirIfNotExists();

              case 17:
                resolvedBaseConfigDir = componentMap.getBaseConfigDir();

                if (resolvedBaseConfigDir) {
                  configDir = (_path || _load_path()).default.join(consumerPath, resolvedBaseConfigDir);
                }

              case 19:
                // Load the base entry from the root dir in map file in case it was imported using -path
                // Or created using bit create so we don't want all the path but only the relative one
                // Check that bitDir isn't the same as consumer path to make sure we are not loading global stuff into component
                componentBitJson = void 0;
                componentBitJsonFileExist = false;
                rawComponentBitJson = void 0;

                if (!(configDir !== consumerPath)) {
                  _context15.next = 32;
                  break;
                }

                componentBitJson = (_bitJson || _load_bitJson()).default.loadSync(configDir, consumerBitJson);
                packageDependencies = componentBitJson.packageDependencies;
                devPackageDependencies = componentBitJson.devPackageDependencies;
                peerPackageDependencies = componentBitJson.peerPackageDependencies;
                // by default, imported components are not written with bit.json file.
                // use the component from the model to get their bit.json values
                _context15.next = 29;
                return (_abstractBitJson || _load_abstractBitJson()).default.hasExisting(configDir);

              case 29:
                componentBitJsonFileExist = _context15.sent;

                if (componentBitJsonFileExist) {
                  rawComponentBitJson = componentBitJson;
                }
                if (!componentBitJsonFileExist && componentFromModel) {
                  componentBitJson.mergeWithComponentData(componentFromModel);
                }

              case 32:
                // for authored componentBitJson is normally undefined
                bitJson = componentBitJson || consumerBitJson;

                // Remove dists if compiler has been deleted

                if (dists && !bitJson.hasCompiler()) {
                  dists = undefined;
                }

                envsContext = {
                  componentDir: bitDir,
                  workspaceDir: consumerPath
                };
                propsToLoadEnvs = {
                  consumerPath,
                  envType: (_compilerExtension2 || _load_compilerExtension2()).COMPILER_ENV_TYPE,
                  scopePath: consumer.scope.getPath(),
                  componentOrigin: componentMap.origin,
                  componentFromModel,
                  consumerBitJson,
                  componentBitJson: rawComponentBitJson,
                  context: envsContext,
                  detached: componentMap.detachedCompiler
                };
                compilerP = (_envExtension || _load_envExtension()).default.loadFromCorrectSource(propsToLoadEnvs);

                propsToLoadEnvs.detached = componentMap.detachedTester;
                propsToLoadEnvs.envType = (_testerExtension2 || _load_testerExtension2()).TESTER_ENV_TYPE;
                testerP = (_envExtension || _load_envExtension()).default.loadFromCorrectSource(propsToLoadEnvs);
                _context15.next = 42;
                return Promise.all([compilerP, testerP]);

              case 42:
                _ref22 = _context15.sent;
                _ref23 = _slicedToArray(_ref22, 2);
                compiler = _ref23[0];
                tester = _ref23[1];


                // Load the compilerPackageDependencies/testerPackageDependencies from the actual compiler / tester or from the model
                // if they are not loaded (aka not installed)
                // We load it from model to prevent case when component is modified becasue changes in envsPackageDependencies
                // That occur as a result that we import component but didn't import its envs so we can't
                // calculate the envsPackageDependencies (without install the env, which we don't want)
                compilerDynamicPackageDependencies = compiler && compiler.loaded ? compiler.dynamicPackageDependencies : {};
                testerDynamicPackageDependencies = tester && tester.loaded ? tester.dynamicPackageDependencies : {};
                modelCompilerPackageDependencies = componentFromModel ? componentFromModel.compilerPackageDependencies || {} : {};
                modelTesterPackageDependencies = componentFromModel ? componentFromModel.testerPackageDependencies || {} : {};
                compilerPackageDependencies = _extends({}, modelCompilerPackageDependencies, compilerDynamicPackageDependencies);
                testerPackageDependencies = _extends({}, modelTesterPackageDependencies, testerDynamicPackageDependencies);
                _context15.t0 = Component;
                _context15.t1 = id.name;
                _context15.t2 = id.scope;
                _context15.t3 = id.version;
                _context15.t4 = bitJson.lang;
                _context15.t5 = bitJson.bindingPrefix || (_constants || _load_constants()).DEFAULT_BINDINGS_PREFIX;
                _context15.t6 = compiler;
                _context15.t7 = tester;
                _context15.t8 = componentBitJsonFileExist ? componentBitJson : undefined;
                _context15.t9 = componentMap.mainFile;
                _context15.next = 64;
                return getLoadedFiles();

              case 64:
                _context15.t10 = _context15.sent;
                _context15.t11 = componentMap;
                _context15.t12 = dists;
                _context15.t13 = packageDependencies;
                _context15.t14 = devPackageDependencies;
                _context15.t15 = peerPackageDependencies;
                _context15.t16 = compilerPackageDependencies;
                _context15.t17 = testerPackageDependencies;
                _context15.t18 = deprecated;
                _context15.t19 = componentMap.origin;
                _context15.t20 = componentMap.detachedCompiler;
                _context15.t21 = componentMap.detachedTester;
                _context15.t22 = {
                  name: _context15.t1,
                  scope: _context15.t2,
                  version: _context15.t3,
                  lang: _context15.t4,
                  bindingPrefix: _context15.t5,
                  compiler: _context15.t6,
                  tester: _context15.t7,
                  bitJson: _context15.t8,
                  mainFile: _context15.t9,
                  files: _context15.t10,
                  loadedFromFileSystem: true,
                  componentMap: _context15.t11,
                  dists: _context15.t12,
                  packageDependencies: _context15.t13,
                  devPackageDependencies: _context15.t14,
                  peerPackageDependencies: _context15.t15,
                  compilerPackageDependencies: _context15.t16,
                  testerPackageDependencies: _context15.t17,
                  deprecated: _context15.t18,
                  origin: _context15.t19,
                  detachedCompiler: _context15.t20,
                  detachedTester: _context15.t21
                };
                return _context15.abrupt('return', new _context15.t0(_context15.t22));

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

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

      return loadFromFileSystem;
    }()
  }]);

  return Component;
}();

exports.default = Component;


function _calculateDetachByOrigin(detachVal, origin) {
  // If it was set to true it's the strongest
  if (detachVal) {
    return detachVal;
  }
  // Authored components are by default attached
  if (origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED) {
    return false;
  }
  // Not authored components are by default detached
  return true;
}