'use strict';

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

var _regenerator;

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

var _bluebird;

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

var _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 _ramdaAdjunct;

function _load_ramdaAdjunct() {
  return _ramdaAdjunct = _interopRequireWildcard(require('ramda-adjunct'));
}

var _constants;

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

var _componentMap;

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

var _bitId;

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

var _driver;

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

var _utils;

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

var _logger;

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

var _dependencies;

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

var _generalError;

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

var _;

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

var _envExtension;

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

var _bitMap;

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

var _linkContent;

function _load_linkContent() {
  return _linkContent = require('../../../../links/link-content');
}

var _overridesDependencies;

function _load_overridesDependencies() {
  return _overridesDependencies = _interopRequireDefault(require('./overrides-dependencies'));
}

var _consumerOverrides;

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

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

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

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

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

var DependencyResolver = function () {
  function DependencyResolver(component, consumer, componentId) {
    _classCallCheck(this, DependencyResolver);

    this.component = component;
    this.consumer = consumer;
    this.componentId = componentId;
    this.componentMap = this.component.componentMap;
    this.componentFromModel = this.component.componentFromModel;
    this.consumerPath = this.consumer.getPath();
    this.allDependencies = {
      dependencies: [],
      devDependencies: [],
      compilerDependencies: [],
      testerDependencies: []
    };
    this.allPackagesDependencies = {
      packageDependencies: {},
      devPackageDependencies: {},
      compilerPackageDependencies: {},
      testerPackageDependencies: {},
      peerPackageDependencies: {}
    };
    this.processedFiles = [];
    this.issues = {
      missingPackagesDependenciesOnFs: {},
      missingComponents: {},
      untrackedDependencies: {},
      missingDependenciesOnFs: {},
      missingLinks: {},
      missingCustomModuleResolutionLinks: {},
      relativeComponents: {},
      parseErrors: {},
      resolveErrors: {},
      missingBits: {} // temporarily, will be combined with missingComponents. see combineIssues
    };
    this.overridesDependencies = new (_overridesDependencies || _load_overridesDependencies()).default(component, consumer);
  }

  _createClass(DependencyResolver, [{
    key: 'setTree',
    value: function setTree(tree) {
      this.tree = tree;
      // console.log(JSON.stringify(tree, null, 4)); // uncomment to easily watch the tree received from bit-javascript
    }

    /**
     * Load components and packages dependencies for a component. The process is as follows:
     * 1) Use the language driver to parse the component files and find for each file its dependencies.
     * 2) The results we get from the driver per file tells us what are the files and packages that depend on our file.
     * and also whether there are missing packages and files.
     * 3) Using the information from the driver, we go over each one of the dependencies files and find its counterpart
     * component. The way how we find it, is by using the bit.map file which has a mapping between the component name and
     * the file paths.
     * 4) If we find a component to the file dependency, we add it to component.dependencies. Otherwise, it's added to
     * component.issues.untrackedDependencies
     * 5) Similarly, when we find the packages dependencies, they are added to component.packageDependencies. Otherwise,
     * they're added to component.issues.missingPackagesDependenciesOnFs
     * 6) In case the driver found a file dependency that is not on the file-system, we add that file to
     * component.issues.missingDependenciesOnFs
     */

  }, {
    key: 'loadDependenciesForComponent',
    value: function () {
      var _ref = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(bitDir, cacheResolvedDependencies, cacheProjectAst) {
        var _this = this;

        var driver, _componentMap$getFile, nonTestsFiles, testsFiles, allFiles, getDependenciesTree, dependenciesTree;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                driver = this.consumer.driver;
                _componentMap$getFile = this.componentMap.getFilesGroupedByBeingTests(), nonTestsFiles = _componentMap$getFile.nonTestsFiles, testsFiles = _componentMap$getFile.testsFiles;

                this.setCompilerFiles();
                this.setTesterFiles();
                allFiles = [].concat(_toConsumableArray(nonTestsFiles), _toConsumableArray(testsFiles), _toConsumableArray(this.compilerFiles), _toConsumableArray(this.testerFiles));

                getDependenciesTree = function () {
                  var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee() {
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
                      while (1) {
                        switch (_context.prev = _context.next) {
                          case 0:
                            return _context.abrupt('return', driver.getDependencyTree(bitDir, _this.consumerPath, allFiles, _this.component.bindingPrefix, _this.consumer.config.resolveModules, cacheResolvedDependencies, cacheProjectAst));

                          case 1:
                          case 'end':
                            return _context.stop();
                        }
                      }
                    }, _callee, _this);
                  }));

                  return function getDependenciesTree() {
                    return _ref2.apply(this, arguments);
                  };
                }();
                // find the dependencies (internal files and packages) through automatic dependency resolution


                _context2.next = 8;
                return getDependenciesTree();

              case 8:
                dependenciesTree = _context2.sent;

                // we have the files dependencies, these files should be components that are registered in bit.map. Otherwise,
                // they are referred as "untracked components" and the user should add them later on in order to tag
                this.setTree(dependenciesTree.tree);
                this.populateDependencies(allFiles, testsFiles);
                this.component.setDependencies(this.allDependencies.dependencies);
                this.component.setDevDependencies(this.allDependencies.devDependencies);
                this.component.setCompilerDependencies(this.allDependencies.compilerDependencies);
                this.component.setTesterDependencies(this.allDependencies.testerDependencies);
                this.component.packageDependencies = this.allPackagesDependencies.packageDependencies;
                this.component.devPackageDependencies = this.allPackagesDependencies.devPackageDependencies;
                this.component.compilerPackageDependencies = (_ramda || _load_ramda()).default.merge(this.allPackagesDependencies.compilerPackageDependencies, this.component.compilerPackageDependencies);
                this.component.testerPackageDependencies = (_ramda || _load_ramda()).default.merge(this.allPackagesDependencies.testerPackageDependencies, this.component.testerPackageDependencies);
                this.component.peerPackageDependencies = this.allPackagesDependencies.peerPackageDependencies;
                if (!(_ramda || _load_ramda()).default.isEmpty(this.issues)) this.component.issues = this.issues;
                this.component.manuallyRemovedDependencies = this.overridesDependencies.manuallyRemovedDependencies;
                this.component.manuallyAddedDependencies = this.overridesDependencies.manuallyAddedDependencies;

                return _context2.abrupt('return', this.component);

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

      function loadDependenciesForComponent(_x, _x2, _x3) {
        return _ref.apply(this, arguments);
      }

      return loadDependenciesForComponent;
    }()

    /**
     * Given the tree of file dependencies from the driver, find the components of these files.
     * Each dependency file has a path, use bit.map to search for the component name by that path.
     * If the component is found, add it to "this.allDependencies.dependencies". Otherwise, add it to "this.issues.untrackedDependencies".
     *
     * For the found components, add their sourceRelativePath and destinationRelativePath, they are being used for
     * generating links upon import:
     * sourceRelativePath - location of the link file.
     * destinationRelativePath - destination written inside the link file.
     */

  }, {
    key: 'populateDependencies',
    value: function populateDependencies(files, testsFiles) {
      var _this2 = this;

      files.forEach(function (file) {
        var fileType = {
          isTestFile: (_ramda || _load_ramda()).default.contains(file, testsFiles),
          isCompilerFile: (_ramda || _load_ramda()).default.contains(file, _this2.compilerFiles),
          isTesterFile: (_ramda || _load_ramda()).default.contains(file, _this2.testerFiles)
        };
        _this2.throwForNonExistFile(file);
        if (_this2.overridesDependencies.shouldIgnoreFile(file, fileType)) {
          return;
        }
        _this2.processMissing(file, fileType);
        _this2.processErrors(file);
        _this2.processPackages(file, fileType);
        _this2.processBits(file, fileType);
        _this2.processDepFiles(file, fileType);
        _this2.processUnidentifiedPackages(file, fileType);
      });
      this.removeDevAndEnvDepsIfTheyAlsoRegulars();
      this.copyEnvDependenciesFromModelIfNeeded();
      this.combineIssues();
      this.removeEmptyIssues();
      this.populatePeerPackageDependencies();
      this.manuallyAddDependencies();
    }
  }, {
    key: 'throwForNonExistFile',
    value: function throwForNonExistFile(file) {
      if (!this.tree[file]) {
        throw new Error(`DependencyResolver: a file "${file}" was not returned from the driver, its dependencies are unknown`);
      }
    }
  }, {
    key: 'manuallyAddDependencies',
    value: function manuallyAddDependencies() {
      var _this3 = this;

      var packageJson = this._getPackageJson();
      var dependencies = this.overridesDependencies.getDependenciesToAddManually(packageJson, this.allDependencies);
      if (!dependencies) return;
      var components = dependencies.components,
          packages = dependencies.packages;

      (_consumerOverrides || _load_consumerOverrides()).dependenciesFields.forEach(function (depField) {
        if (components[depField] && components[depField].length) {
          // $FlowFixMe
          components[depField].forEach(function (id) {
            return _this3.allDependencies[depField].push({ id, relativePaths: [] });
          });
        }
        if (packages[depField] && !(_ramda || _load_ramda()).default.isEmpty(packages[depField])) {
          Object.assign(_this3.allPackagesDependencies[_this3._pkgFieldMapping(depField)], packages[depField]);
        }
      });
    }
  }, {
    key: 'traverseTreeForComponentId',
    value: function traverseTreeForComponentId(depFile) {
      if (!this.tree[depFile] || !this.tree[depFile].files && !this.tree[depFile].bits) return;
      if (!this.componentMap.rootDir) {
        throw Error('traverseTreeForComponentId should get called only when rootDir is set');
      }
      var rootDirFullPath = (_path || _load_path()).default.join(this.consumerPath, this.componentMap.rootDir);
      if (this.tree[depFile].files && this.tree[depFile].files.length) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = this.tree[depFile].files[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var file = _step.value;

            var fullDepFile = (_path || _load_path()).default.resolve(rootDirFullPath, file.file);
            var depRelativeToConsumer = (0, (_utils || _load_utils()).pathNormalizeToLinux)((_path || _load_path()).default.relative(this.consumerPath, fullDepFile));
            var componentId = this.consumer.bitMap.getComponentIdByPath(depRelativeToConsumer);
            if (componentId) return componentId; // eslint-disable-line consistent-return
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }
      if (this.tree[depFile].bits && this.tree[depFile].bits.length) {
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = this.tree[depFile].bits[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var bit = _step2.value;

            var _componentId = this.consumer.getComponentIdFromNodeModulesPath(bit, this.component.bindingPrefix);
            if (_componentId) return _componentId; // eslint-disable-line consistent-return
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2.return) {
              _iterator2.return();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }
      }

      if (this.tree[depFile].files && this.tree[depFile].files.length) {
        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = undefined;

        try {
          for (var _iterator3 = this.tree[depFile].files[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
            var _file = _step3.value;

            if (_file.file !== depFile) {
              var _componentId2 = this.traverseTreeForComponentId(_file.file);
              if (_componentId2) return _componentId2; // eslint-disable-line consistent-return
            } else {
              (_logger || _load_logger()).default.warn(`traverseTreeForComponentId found a cyclic dependency. ${_file.file} depends on itself`);
            }
          }
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3.return) {
              _iterator3.return();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }
      }
    }
  }, {
    key: 'getComponentIdByDepFile',
    value: function getComponentIdByDepFile(depFile) {
      var depFileRelative = depFile; // dependency file path relative to consumer root
      var componentId = void 0;
      var destination = void 0;
      var rootDir = this.componentMap.rootDir;
      if (rootDir) {
        // The depFileRelative is relative to rootDir, change it to be relative to current consumer.
        // We can't use path.resolve(rootDir, fileDep) because this might not work when running
        // bit commands not from root, because resolve take by default the process.cwd
        var rootDirFullPath = (_path || _load_path()).default.join(this.consumerPath, rootDir);
        var fullDepFile = (_path || _load_path()).default.resolve(rootDirFullPath, depFile);
        depFileRelative = (0, (_utils || _load_utils()).pathNormalizeToLinux)((_path || _load_path()).default.relative(this.consumerPath, fullDepFile));
      }

      componentId = this.consumer.bitMap.getComponentIdByPath(depFileRelative);
      if (!componentId) componentId = this._getComponentIdFromCustomResolveToPackageWithDist(depFileRelative);
      // if not found here, the file is not a component file. It might be a bit-auto-generated file.
      // find the component file by the auto-generated file.
      // We make sure also that rootDir is there, otherwise, it's an AUTHORED component, which shouldn't have
      // auto-generated files.
      if (!componentId && rootDir) {
        componentId = this.traverseTreeForComponentId(depFile);
        if (componentId) {
          // it is verified now that this depFile is an auto-generated file, therefore the sourceRelativePath and the
          // destinationRelativePath should be a partial-path and not full-relative-to-consumer path.
          // since the dep-file is a generated file, it is safe to assume that the componentFromModel has in its
          // dependencies array this component with the relativePaths array. Find the relativePath of this dep-file
          // to get the correct destinationRelativePath. There is no other way to obtain this info.
          if (!this.componentFromModel) {
            throw new (_generalError || _load_generalError()).default(`Failed to resolve ${componentId.toString()} dependencies because the component is not in the model.
Try to run "bit import ${this.component.id.toString()} --objects" to get the component saved in the model`);
          }

          var _getDependencyPathsFr = this.getDependencyPathsFromModel(componentId, depFile, rootDir);

          componentId = _getDependencyPathsFr.componentId;
          destination = _getDependencyPathsFr.destination;
          depFileRelative = _getDependencyPathsFr.depFileRelative;
        } else if (!(0, (_linkContent || _load_linkContent()).isSupportedExtension)(depFile) && this.componentFromModel) {
          // unsupported files, such as binary files, don't have link files. instead, they have a
          // symlink (or sometimes a copy on Windows) of the dependency inside the component. to
          // check whether a file is a symlink to a dependency we loop through the
          // sourceRelativePaths of the dependency, if there is match, we use the data from the model
          var dependenciesFromModel = this.componentFromModel.getAllDependenciesCloned();
          var sourcePaths = dependenciesFromModel.getSourcesPaths();
          if (sourcePaths.includes(depFile)) {
            var dependencyFromModel = dependenciesFromModel.getBySourcePath(depFile);
            componentId = dependencyFromModel.id;

            var _getDependencyPathsFr2 = this.getDependencyPathsFromModel(componentId, depFile, rootDir);

            componentId = _getDependencyPathsFr2.componentId;
            destination = _getDependencyPathsFr2.destination;
            depFileRelative = _getDependencyPathsFr2.depFileRelative;
          }
        }
      }

      return { componentId, depFileRelative, destination };
    }

    /**
     * this is a workaround for cases where an alias points to a package with dist.
     * normally, aliases are created for local directories.
     * they can be however useful when a source code can't be touched and `require` to one package
     * needs to be replaced with a `require` to a component. in that case, our options are:
     * 1) point the alias to the package name.
     * 2) point the alias to the relative directory of the imported component
     * the ideal solution is #1, however, it requires changes in the Tree structure, which should
     * allow "bits" to have more data, such as importSource.
     * here, we go option #2, the alias is a relative path to the component. however, when there is
     * dist directory, the resolved path contains the "dist", which doesn't exist in the ComponentMap,
     * the solution we take is to identify such cases, strip the dist, then try to find them again.
     */

  }, {
    key: '_getComponentIdFromCustomResolveToPackageWithDist',
    value: function _getComponentIdFromCustomResolveToPackageWithDist(depFile) {
      if (!depFile.includes('dist')) return null;
      var resolveModules = this.consumer.config.resolveModules;
      if (!resolveModules || !resolveModules.aliases) return null;
      var foundAlias = Object.keys(resolveModules.aliases).find(function (alias) {
        return depFile.startsWith(resolveModules.aliases[alias]);
      });
      if (!foundAlias) return null;
      var newDepFile = depFile.replace(`${resolveModules.aliases[foundAlias]}/dist`, resolveModules.aliases[foundAlias]);
      return this.consumer.bitMap.getComponentIdByPath(newDepFile);
    }
  }, {
    key: 'getDependencyPathsFromModel',
    value: function getDependencyPathsFromModel(componentId, depFile, rootDir) {
      var dependency = this.componentFromModel.getAllDependencies().find(function (dep) {
        return dep.id.isEqualWithoutVersion(componentId);
      });
      if (!dependency) {
        throw new (_generalError || _load_generalError()).default( // $FlowFixMe
        `the auto-generated file ${depFile} should be connected to ${componentId}, however, it's not part of the model dependencies of ${this.componentFromModel.id}`);
      }
      var isCompilerDependency = this.componentFromModel.compilerDependencies.getById(componentId);
      var isTesterDependency = this.componentFromModel.testerDependencies.getById(componentId);
      var isEnvDependency = isCompilerDependency || isTesterDependency;
      var isRelativeToConfigDir = Boolean(isEnvDependency && this.componentMap.configDir && this.componentMap.rootDir);
      var originallySource = this.getOriginallySourcePath(isRelativeToConfigDir, rootDir, depFile, isCompilerDependency);
      var relativePath = dependency.relativePaths.find(function (r) {
        return r.sourceRelativePath === originallySource;
      });
      if (!relativePath) {
        throw new (_generalError || _load_generalError()).default(`unable to find ${originallySource} path in the dependencies relativePaths of ${this.componentFromModel.id}`);
      }
      return {
        componentId: dependency.id,
        destination: relativePath.destinationRelativePath,
        // in the case of isRelativeToConfigDir, sourceRelativePath should be relative to configDir
        depFileRelative: isRelativeToConfigDir ? originallySource : depFile
      };
    }
  }, {
    key: 'getOriginallySourcePath',
    value: function getOriginallySourcePath(isRelativeToConfigDir, rootDir, depFile, isCompilerDependency) {
      if (isRelativeToConfigDir) {
        // find the sourceRelativePath relative to the configDir, not to the rootDir of the component
        var resolvedSource = (_path || _load_path()).default.resolve(rootDir, depFile);
        // @todo: use the new ConfigDir class that Gilad added once it is merged.

        var _BitMap$parseConfigDi = (_bitMap || _load_bitMap()).default.parseConfigDir(this.componentMap.configDir, this.componentMap.rootDir),
            compilerConfigDir = _BitMap$parseConfigDi.compiler,
            testerConfigDir = _BitMap$parseConfigDi.tester;

        var configDir = isCompilerDependency ? compilerConfigDir : testerConfigDir;
        var absoluteConfigDir = this.consumer.toAbsolutePath(configDir);
        return (0, (_utils || _load_utils()).pathRelativeLinux)(absoluteConfigDir, resolvedSource);
      }
      return depFile;
    }
  }, {
    key: 'processDepFiles',
    value: function processDepFiles(originFile, fileType) {
      var _this4 = this;

      var allDepsFiles = this.tree[originFile].files;
      if (!allDepsFiles || (_ramda || _load_ramda()).default.isEmpty(allDepsFiles)) return;
      allDepsFiles.forEach(function (depFile) {
        if (_this4.overridesDependencies.shouldIgnoreFile(depFile.file, fileType)) return;
        if (depFile.isLink) _this4.processLinkFile(originFile, depFile, fileType);else {
          _this4.processOneDepFile(originFile, depFile.file, depFile.importSpecifiers, undefined, fileType, depFile);
        }
      });
    }
  }, {
    key: 'processOneDepFile',
    value: function processOneDepFile(originFile, depFile, importSpecifiers, linkFile, fileType, depFileObject) {
      if (this.processedFiles.includes(depFile)) return;
      this.processedFiles.push(depFile);

      // if the dependency of an envFile is already included in the env files of the component, we're good
      if (fileType.isCompilerFile && this.compilerFiles.includes(depFile)) return;
      if (fileType.isTesterFile && this.testerFiles.includes(depFile)) return;

      var _getComponentIdByDepF = this.getComponentIdByDepFile(depFile),
          componentId = _getComponentIdByDepF.componentId,
          depFileRelative = _getComponentIdByDepF.depFileRelative,
          destination = _getComponentIdByDepF.destination;
      // the file dependency doesn't have any counterpart component. Add it to this.issues.untrackedDependencies


      if (!componentId) {
        if (this.issues.untrackedDependencies[originFile]) {
          this.issues.untrackedDependencies[originFile].push(depFileRelative);
        } else {
          this.issues.untrackedDependencies[originFile] = [depFileRelative];
        }
        return;
      }
      if (this.overridesDependencies.shouldIgnoreComponent(componentId, fileType)) {
        // we can't support it because on the imported side, we don't know to convert the relative path
        // to the component name, as it won't have the component installed
        throw new (_generalError || _load_generalError()).default(`unable to ignore "${componentId.toString()}" dependency of "${this.componentId.toString()}" by using ignore components syntax because the component is required with relative path.
either, use the ignore file syntax or change the require statement to have a module path`);
      }
      // happens when in the same component one file requires another one. In this case, there is
      // noting to do regarding the dependencies
      if (componentId.isEqual(this.componentId)) {
        if (depFileObject.isCustomResolveUsed) {
          this.component.customResolvedPaths.push({
            destinationPath: depFileObject.file,
            importSource: depFileObject.importSource
          });
        }
        return;
      }

      var depComponentMap = this.consumer.bitMap.getComponentIfExist(componentId);
      // found a dependency component. Add it to this.allDependencies.dependencies
      var depRootDir = depComponentMap ? depComponentMap.rootDir : undefined;
      var destinationRelativePath = destination || (depRootDir && depFileRelative.startsWith(depRootDir) ? (0, (_utils || _load_utils()).pathRelativeLinux)(depRootDir, depFileRelative) : depFileRelative);

      var sourceRelativePath = void 0;
      if (linkFile) {
        sourceRelativePath = linkFile;
      } else {
        // when there is no rootDir for the current dependency (it happens when it's AUTHORED), keep the original path
        sourceRelativePath = depRootDir ? depFileRelative : depFile;
      }

      var depsPaths = {
        sourceRelativePath,
        destinationRelativePath
      };
      if (importSpecifiers) {
        importSpecifiers.map(function (importSpecifier) {
          if (importSpecifier.linkFile) delete importSpecifier.linkFile.exported;
          if (importSpecifier.mainFile) delete importSpecifier.mainFile.exported;
        });
        depsPaths.importSpecifiers = importSpecifiers;
      }
      if (depFileObject.isCustomResolveUsed) {
        depsPaths.isCustomResolveUsed = depFileObject.isCustomResolveUsed;
        depsPaths.importSource = depFileObject.importSource;
      }
      var currentComponentsDeps = { id: componentId, relativePaths: [depsPaths] };

      if (depComponentMap && !depFileObject.isCustomResolveUsed && ( // for custom resolve, the link is written in node_modules, so it doesn't matter
      depComponentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED && this.componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED || depComponentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED && this.componentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED)) {
        // prevent author using relative paths for IMPORTED component (to avoid long paths)
        // also prevent adding AUTHORED component to an IMPORTED component using relative syntax. The reason is that when
        // this component is imported somewhere else, a link-file between the IMPORTED and the AUTHORED must be written
        // outside the component directory, which might override user files.
        if (this.issues.relativeComponents[originFile]) this.issues.relativeComponents[originFile].push(componentId);else this.issues.relativeComponents[originFile] = [componentId];
        return;
      }

      var allDependencies = [].concat(_toConsumableArray(this.allDependencies.dependencies), _toConsumableArray(this.allDependencies.devDependencies), _toConsumableArray(this.allDependencies.compilerDependencies), _toConsumableArray(this.allDependencies.testerDependencies));
      var existingDependency = this.getExistingDependency(allDependencies, componentId);
      if (existingDependency) {
        // it is another file of an already existing component. Just add the new path
        existingDependency.relativePaths.push(depsPaths);
      } else {
        this.pushToDependenciesArray(currentComponentsDeps, fileType);
      }
    }
  }, {
    key: 'processLinkFile',
    value: function processLinkFile(originFile, linkFile, fileType) {
      var _this5 = this;

      if (!linkFile.linkDependencies || (_ramda || _load_ramda()).default.isEmpty(linkFile.linkDependencies)) return;
      var nonLinkImportSpecifiers = [];
      linkFile.linkDependencies.forEach(function (dependency) {
        var component = _this5.getComponentIdByDepFile(linkFile.file);
        if (component.componentId) {
          // the linkFile is already a component, no need to treat it differently than other depFile
          // aggregate all dependencies using the same linkFile and ultimately run processDepFile
          // with all importSpecifiers of that linkFile.
          // also, delete the linkFile attribute of importSpecifiers so then once the component is
          // imported and the link is generated, it won't be treated as a linkFile.
          dependency.importSpecifiers.map(function (a) {
            return delete a.linkFile;
          });
          nonLinkImportSpecifiers.push(dependency.importSpecifiers);
        } else {
          _this5.processOneDepFile(originFile, dependency.file, dependency.importSpecifiers, linkFile.file, fileType, linkFile);
        }
      });
      if (nonLinkImportSpecifiers.length) {
        this.processOneDepFile(originFile, linkFile.file, (_ramda || _load_ramda()).default.flatten(nonLinkImportSpecifiers), undefined, fileType, linkFile);
      }
    }

    /**
     * process require/import of Bit components where the require statement is not a relative path
     * but a module path, such as `require('@bit/bit.envs/compiler/babel');`
     */

  }, {
    key: 'processBits',
    value: function processBits(originFile, fileType) {
      var _this6 = this;

      var bits = this.tree[originFile].bits;
      if (!bits || (_ramda || _load_ramda()).default.isEmpty(bits)) return;
      bits.forEach(function (bitDep) {
        var componentId = _this6.consumer.getComponentIdFromNodeModulesPath(bitDep, _this6.component.bindingPrefix);
        if (_this6.overridesDependencies.shouldIgnoreComponent(componentId, fileType)) return;
        var getExistingId = function getExistingId() {
          var existingId = _this6.consumer.bitmapIds.searchWithoutVersion(componentId);
          if (existingId) return existingId;

          // maybe the dependencies were imported as npm packages
          if (bitDep.startsWith('node_modules')) {
            // Add the root dir in case it exists (to make sure we search for the dependency package json in the correct place)
            var basePath = _this6.componentMap.rootDir ? (_path || _load_path()).default.join(_this6.consumerPath, _this6.componentMap.rootDir) : _this6.consumerPath;
            var depPath = (_path || _load_path()).default.join(basePath, bitDep);
            var packageJson = _this6.consumer.driver.driver.PackageJson.findPackage(depPath);
            if (packageJson) {
              var depVersion = packageJson.version;
              existingId = componentId.changeVersion(depVersion);
              return existingId;
            }
          }
          if (_this6.componentFromModel) {
            var modelDep = _this6.componentFromModel.getAllDependenciesIds().searchWithoutVersion(componentId);
            if (modelDep) return modelDep;
          }
          return null;
        };
        var existingId = getExistingId();
        if (existingId) {
          if (existingId.isEqual(_this6.componentId)) {
            // happens when one of the component files requires another using module path
            // no need to enter anything to the dependencies
            return;
          }
          var currentComponentsDeps = { id: existingId, relativePaths: [] };
          var existingDependency = _this6.getExistingDependency(_this6.allDependencies.dependencies, existingId);
          if (!existingDependency) {
            _this6.pushToDependenciesArray(currentComponentsDeps, fileType);
          }
        } else {
          _this6.issues.missingBits[originFile] ? _this6.issues.missingBits[originFile].push(componentId) : _this6.issues.missingBits[originFile] = [componentId];
        }
      });
    }
  }, {
    key: 'processPackages',
    value: function processPackages(originFile, fileType) {
      var _this7 = this;

      var getPackages = function getPackages() {
        var packages = _this7.tree[originFile].packages;
        if ((_ramdaAdjunct || _load_ramdaAdjunct()).isNilOrEmpty(packages)) return null;
        var shouldBeIncluded = function shouldBeIncluded(pkgVersion, pkgName) {
          return !_this7.overridesDependencies.shouldIgnorePackage(pkgName, fileType);
        };
        return (_ramda || _load_ramda()).default.pickBy(shouldBeIncluded, packages);
      };
      var packages = getPackages();
      if (packages && !(_ramda || _load_ramda()).default.isEmpty(packages)) {
        if (fileType.isTestFile) {
          Object.assign(this.allPackagesDependencies.devPackageDependencies, packages);
        } else if (fileType.isCompilerFile) {
          Object.assign(this.allPackagesDependencies.compilerPackageDependencies, packages);
        } else if (fileType.isTesterFile) {
          Object.assign(this.allPackagesDependencies.testerPackageDependencies, packages);
        } else {
          Object.assign(this.allPackagesDependencies.packageDependencies, packages);
        }
      }
    }
  }, {
    key: 'processMissing',
    value: function processMissing(originFile, fileType) {
      var _this8 = this;

      var missing = this.tree[originFile].missing;
      if (!missing) return;
      var processMissingFiles = function processMissingFiles() {
        if ((_ramdaAdjunct || _load_ramdaAdjunct()).isNilOrEmpty(missing.files)) return;
        var absOriginFile = _this8.consumer.toAbsolutePath(originFile);
        var missingFiles = missing.files.filter(function (missingFile) {
          // convert from importSource (the string inside the require/import call) to the path relative to consumer
          var resolvedPath = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(absOriginFile), missingFile);
          var relativeToConsumer = _this8.consumer.getPathRelativeToConsumer(resolvedPath);
          return !_this8.overridesDependencies.shouldIgnoreFile(relativeToConsumer, fileType);
        });
        if ((_ramda || _load_ramda()).default.isEmpty(missingFiles)) return;
        if (_this8.issues.missingDependenciesOnFs[originFile]) {
          _this8.issues.missingDependenciesOnFs[originFile].concat(missingFiles);
        } else _this8.issues.missingDependenciesOnFs[originFile] = missingFiles;
      };
      var processMissingPackages = function processMissingPackages() {
        if ((_ramdaAdjunct || _load_ramdaAdjunct()).isNilOrEmpty(missing.packages)) return;
        var missingPackages = missing.packages.filter(function (pkg) {
          return !_this8.overridesDependencies.shouldIgnorePackage(pkg, fileType);
        });
        if ((_ramda || _load_ramda()).default.isEmpty(missingPackages)) return;
        var customResolvedDependencies = _this8.findOriginallyCustomModuleResolvedDependencies(missingPackages);
        if (customResolvedDependencies) {
          Object.keys(customResolvedDependencies).forEach(function (missingPackage) {
            var componentId = customResolvedDependencies[missingPackage].toString();
            if (_this8.issues.missingCustomModuleResolutionLinks[originFile]) {
              _this8.issues.missingCustomModuleResolutionLinks[originFile].push(componentId);
            } else _this8.issues.missingCustomModuleResolutionLinks[originFile] = [componentId];
          });
        }
        var missingPackagesWithoutCustomResolved = customResolvedDependencies ? (_ramda || _load_ramda()).default.difference(missingPackages, Object.keys(customResolvedDependencies)) : missingPackages;

        if (!(_ramda || _load_ramda()).default.isEmpty(missingPackagesWithoutCustomResolved)) {
          if (_this8.issues.missingPackagesDependenciesOnFs[originFile]) {
            _this8.issues.missingPackagesDependenciesOnFs[originFile].concat(missingPackages);
          } else _this8.issues.missingPackagesDependenciesOnFs[originFile] = missingPackages;
        }
      };
      var processMissingComponents = function processMissingComponents() {
        if ((_ramdaAdjunct || _load_ramdaAdjunct()).isNilOrEmpty(missing.bits)) return;
        missing.bits.forEach(function (missingBit) {
          var componentId = _this8.consumer.getComponentIdFromNodeModulesPath(missingBit, _this8.component.bindingPrefix);
          if (_this8.overridesDependencies.shouldIgnoreComponent(componentId, fileType)) return;
          // todo: a component might be on bit.map but not on the FS, yet, it's not about missing links.
          if (_this8.consumer.bitMap.getBitIdIfExist(componentId, { ignoreVersion: true })) {
            if (_this8.issues.missingLinks[originFile]) _this8.issues.missingLinks[originFile].push(componentId);else _this8.issues.missingLinks[originFile] = [componentId];
          } else if (_this8.issues.missingComponents[originFile]) {
            _this8.issues.missingComponents[originFile].push(componentId);
          } else {
            _this8.issues.missingComponents[originFile] = [componentId];
          }
        });
      };
      processMissingFiles();
      processMissingPackages();
      processMissingComponents();
    }
  }, {
    key: 'processErrors',
    value: function processErrors(originFile) {
      var error = this.tree[originFile].error;
      if (!error) return;
      (_logger || _load_logger()).default.errorAndAddBreadCrumb('dependency-resolver.processErrors', 'got an error from the driver while resolving dependencies');
      (_logger || _load_logger()).default.error(error);
      // $FlowFixMe error.code is set when it comes from bit-javascript, otherwise, it's undefined and treated as resolve-error
      if (error.code === 'PARSING_ERROR') this.issues.parseErrors[originFile] = error.message;else this.issues.resolveErrors[originFile] = error.message;
    }

    /**
     * currently the only unidentified packages being process are the ones coming from custom-modules-resolution.
     * assuming the author used custom-resolution, which enable using non-relative import syntax,
     * for example, requiring the file 'src/utils/is-string' from anywhere as require('utils/is-string');
     * now, when the component is imported, the driver recognizes 'utils/is-string' as a package,
     * because it's not relative.
     * the goal here is to use the 'package' the driver found and match it with one of the
     * dependencies from the model. In the example above, we might find in the model, a dependency
     * is-string with importSource of 'utils/is-string'.
     * Once a match is found, copy the relativePaths from the model.
     */

  }, {
    key: 'processUnidentifiedPackages',
    value: function processUnidentifiedPackages(originFile, fileType) {
      var _this9 = this;

      var unidentifiedPackages = this.tree[originFile].unidentifiedPackages;
      if (!unidentifiedPackages) return;
      if (!this.componentFromModel) return; // not relevant, the component is not imported
      var getDependencies = function getDependencies() {
        if (fileType.isTestFile) return _this9.componentFromModel.devDependencies;
        if (fileType.isCompilerFile) return _this9.componentFromModel.compilerDependencies;
        if (fileType.isTesterFile) return _this9.componentFromModel.testerDependencies;
        return _this9.componentFromModel.dependencies;
      };
      var dependencies = getDependencies();
      if (dependencies.isEmpty()) return;
      var importSourceMap = dependencies.getCustomResolvedData();
      if ((_ramda || _load_ramda()).default.isEmpty(importSourceMap)) return;
      var clonedDependencies = new (_dependencies || _load_dependencies()).default(dependencies.getClone());
      unidentifiedPackages.forEach(function (unidentifiedPackage) {
        var packageLinuxFormat = (0, (_utils || _load_utils()).pathNormalizeToLinux)(unidentifiedPackage);
        var packageWithNoNodeModules = packageLinuxFormat.replace('node_modules/', '');
        var foundImportSource = Object.keys(importSourceMap).find(function (importSource) {
          return packageWithNoNodeModules.startsWith(importSource);
        });
        if (foundImportSource) {
          var dependencyId = importSourceMap[foundImportSource];
          var existingDependency = _this9.getExistingDependency(_this9.allDependencies.dependencies, dependencyId);
          var existingDevDependency = _this9.getExistingDependency(_this9.allDependencies.devDependencies, dependencyId);
          var existingCompilerDependency = _this9.getExistingDependency(_this9.allDependencies.compilerDependencies, dependencyId);
          var existingTesterDependency = _this9.getExistingDependency(_this9.allDependencies.testerDependencies, dependencyId);
          var currentComponentDeps = {
            id: dependencyId,
            // $FlowFixMe
            relativePaths: clonedDependencies.getById(dependencyId).relativePaths
          };
          if (fileType.isTestFile && !existingDevDependency) {
            _this9.allDependencies.devDependencies.push(currentComponentDeps);
          } else if (fileType.isCompilerFile && !existingCompilerDependency) {
            _this9.allDependencies.compilerDependencies.push(currentComponentDeps);
          } else if (fileType.isTesterFile && !existingTesterDependency) {
            _this9.allDependencies.testerDependencies.push(currentComponentDeps);
          } else if (!fileType.isTestFile && !fileType.isCompilerFile && !fileType.isTesterFile && !existingDependency) {
            _this9.allDependencies.dependencies.push(currentComponentDeps);
          }
        }
      });
    }
  }, {
    key: 'pushToDependenciesArray',
    value: function pushToDependenciesArray(currentComponentsDeps, fileType) {
      if (fileType.isTestFile) {
        this.allDependencies.devDependencies.push(currentComponentsDeps);
      } else if (fileType.isCompilerFile) {
        this.allDependencies.compilerDependencies.push(currentComponentsDeps);
      } else if (fileType.isTesterFile) {
        this.allDependencies.testerDependencies.push(currentComponentsDeps);
      } else {
        this.allDependencies.dependencies.push(currentComponentsDeps);
      }
    }

    /**
     * Remove the dependencies which appear both in dev and regular deps from the dev
     * Because if a dependency is both dev dependency and regular dependency it should be treated as regular one
     * Apply for both packages and components dependencies
     */

  }, {
    key: 'removeDevAndEnvDepsIfTheyAlsoRegulars',
    value: function removeDevAndEnvDepsIfTheyAlsoRegulars() {
      var _this10 = this;

      // remove dev and env packages that are also regular packages
      var getNotRegularPackages = function getNotRegularPackages(packages) {
        return (_ramda || _load_ramda()).default.difference((_ramda || _load_ramda()).default.keys(packages), (_ramda || _load_ramda()).default.keys(_this10.allPackagesDependencies.packageDependencies));
      };
      this.allPackagesDependencies.devPackageDependencies = (_ramda || _load_ramda()).default.pick(getNotRegularPackages(this.allPackagesDependencies.devPackageDependencies), this.allPackagesDependencies.devPackageDependencies);
      this.allPackagesDependencies.compilerPackageDependencies = (_ramda || _load_ramda()).default.pick(getNotRegularPackages(this.allPackagesDependencies.compilerPackageDependencies), this.allPackagesDependencies.compilerPackageDependencies);
      this.allPackagesDependencies.testerPackageDependencies = (_ramda || _load_ramda()).default.pick(getNotRegularPackages(this.allPackagesDependencies.testerPackageDependencies), this.allPackagesDependencies.testerPackageDependencies);

      // remove dev and env dependencies that are also regular dependencies
      var componentDepsIds = new (Function.prototype.bind.apply((_bitId || _load_bitId()).BitIds, [null].concat(_toConsumableArray(this.allDependencies.dependencies.map(function (c) {
        return c.id;
      })))))();
      this.allDependencies.devDependencies = this.allDependencies.devDependencies.filter(function (d) {
        return !componentDepsIds.has(d.id);
      });
      this.allDependencies.compilerDependencies = this.allDependencies.compilerDependencies.filter(function (d) {
        return !componentDepsIds.has(d.id);
      });
      this.allDependencies.testerDependencies = this.allDependencies.testerDependencies.filter(function (d) {
        return !componentDepsIds.has(d.id);
      });
    }

    /**
     * given missing packages name, find whether they were dependencies with custom-resolve before.
     */

  }, {
    key: 'findOriginallyCustomModuleResolvedDependencies',
    value: function findOriginallyCustomModuleResolvedDependencies(packages) {
      if (!packages) return undefined;
      if (!this.componentFromModel) return undefined; // not relevant, the component is not imported
      var dependencies = new (_dependencies || _load_dependencies()).default(this.componentFromModel.getAllDependencies());
      if (dependencies.isEmpty()) return undefined;
      var importSourceMap = dependencies.getCustomResolvedData();
      if ((_ramda || _load_ramda()).default.isEmpty(importSourceMap)) return undefined;
      var foundPackages = packages.reduce(function (acc, value) {
        var packageLinuxFormat = (0, (_utils || _load_utils()).pathNormalizeToLinux)(value);
        var foundImportSource = Object.keys(importSourceMap).find(function (importSource) {
          return importSource.startsWith(packageLinuxFormat);
        });
        if (foundImportSource) {
          var dependencyId = importSourceMap[foundImportSource];
          acc[value] = dependencyId;
        }
        return acc;
      }, {});

      return (_ramda || _load_ramda()).default.isEmpty(foundPackages) ? undefined : foundPackages;
    }

    // when env dependencies are not sent to the dependency-resolver, they should be copied from the model

  }, {
    key: 'copyEnvDependenciesFromModelIfNeeded',
    value: function copyEnvDependenciesFromModelIfNeeded() {
      if (!this.componentFromModel) return;
      if (!shouldProcessEnvDependencies(this.component.compiler)) {
        this.allDependencies.compilerDependencies = this.componentFromModel.compilerDependencies.get();
        this.allPackagesDependencies.compilerPackageDependencies = this.componentFromModel.compilerPackageDependencies;
      }
      if (!shouldProcessEnvDependencies(this.component.tester)) {
        this.allDependencies.testerDependencies = this.componentFromModel.testerDependencies.get();
        this.allPackagesDependencies.testerPackageDependencies = this.componentFromModel.testerPackageDependencies;
      }
    }
  }, {
    key: 'combineIssues',
    value: function combineIssues() {
      var _this11 = this;

      Object.keys(this.issues.missingBits).forEach(function (missingBit) {
        if (_this11.issues.missingComponents[missingBit]) {
          _this11.issues.missingComponents[missingBit] = _this11.issues.missingComponents[missingBit].concat(_this11.issues.missingBits[missingBit]);
        } else {
          _this11.issues.missingComponents[missingBit] = _this11.issues.missingBits[missingBit];
        }
      });
    }
  }, {
    key: 'removeEmptyIssues',
    value: function removeEmptyIssues() {
      var notEmpty = function notEmpty(item) {
        return !(_ramda || _load_ramda()).default.isEmpty(item);
      };
      this.issues = (_ramda || _load_ramda()).default.filter(notEmpty, this.issues);
    }
  }, {
    key: 'getExistingDependency',
    value: function getExistingDependency(dependencies, id) {
      return dependencies.find(function (d) {
        return d.id.isEqual(id);
      });
    }
  }, {
    key: 'setCompilerFiles',
    value: function setCompilerFiles() {
      var compilerFiles = shouldProcessEnvDependencies(this.component.compiler) ? this.component.compiler.files : [];
      this.compilerFiles = this.getRelativeEnvFiles(compilerFiles);
    }
  }, {
    key: 'setTesterFiles',
    value: function setTesterFiles() {
      var testerFiles = shouldProcessEnvDependencies(this.component.tester) ? this.component.tester.files : [];
      this.testerFiles = this.getRelativeEnvFiles(testerFiles);
    }
  }, {
    key: 'getRelativeEnvFiles',
    value: function getRelativeEnvFiles(files) {
      var _this12 = this;

      var getPathsRelativeToComponentRoot = function getPathsRelativeToComponentRoot() {
        var rootDirAbsolute = _this12.consumer.toAbsolutePath(_this12.componentMap.getRootDir());
        return files.map(function (file) {
          var envAbsolute = file.path;
          return (_path || _load_path()).default.relative(rootDirAbsolute, envAbsolute);
        });
      };
      return getPathsRelativeToComponentRoot().map(function (file) {
        return (0, (_utils || _load_utils()).pathNormalizeToLinux)(file);
      });
    }

    /**
     * For author, the peer-dependencies are set in the root package.json
     * For imported components, we don't want to change the peerDependencies of the author, unless
     * we're certain the user intent to do so. Therefore, we ignore the root package.json and look for
     * the package.json in the component's directory.
     */

  }, {
    key: 'populatePeerPackageDependencies',
    value: function populatePeerPackageDependencies() {
      var _this13 = this;

      var componentMap = this.component.componentMap;
      var getPeerDependencies = function getPeerDependencies() {
        var packageJson = _this13._getPackageJson();
        if (packageJson && packageJson.peerDependencies) return packageJson.peerDependencies;
        if (_this13.component.componentFromModel && componentMap.origin !== (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED) {
          return _this13.component.componentFromModel.peerPackageDependencies;
        }
        return {};
      };
      var projectPeerDependencies = getPeerDependencies();
      var peerPackages = {};
      if ((_ramda || _load_ramda()).default.isEmpty(projectPeerDependencies)) return;

      // check whether the peer-dependencies was actually require in the code. if so, remove it from
      // the packages/dev-packages and add it as a peer-package.
      // if it was not required in the code, don't add it to the peerPackages
      Object.keys(projectPeerDependencies).forEach(function (pkg) {
        if (_this13.overridesDependencies.shouldIgnorePeerPackage(pkg)) return;
        ['packageDependencies', 'devPackageDependencies'].forEach(function (field) {
          if (Object.keys(_this13.allPackagesDependencies[field]).includes(pkg)) {
            delete _this13.allPackagesDependencies[field][pkg];
            peerPackages[pkg] = projectPeerDependencies[pkg];
          }
        });
      });
      this.allPackagesDependencies.peerPackageDependencies = peerPackages;
    }
  }, {
    key: '_getPackageJson',
    value: function _getPackageJson() {
      var componentMap = this.component.componentMap;
      // $FlowFixMe
      var componentRoot = componentMap.getRootDir();
      var packageJsonLocation = (_path || _load_path()).default.join(this.consumer.toAbsolutePath(componentRoot), 'package.json');
      if (!(_fsExtra || _load_fsExtra()).default.existsSync(packageJsonLocation)) return null;
      try {
        var packageJson = (_fsExtra || _load_fsExtra()).default.readJsonSync(packageJsonLocation);
        return packageJson;
      } catch (err) {
        (_logger || _load_logger()).default.errorAndAddBreadCrumb('dependency-resolver._getPackageJson', 'Failed reading the project package.json at {packageJsonLocation}. Error Message: {message}', { packageJsonLocation, message: err.message });
      }
    }
  }, {
    key: '_pkgFieldMapping',
    value: function _pkgFieldMapping(field) {
      switch (field) {
        case 'dependencies':
          return 'packageDependencies';
        case 'devDependencies':
          return 'devPackageDependencies';
        case 'peerDependencies':
          return 'peerPackageDependencies';
        default:
          throw new Error(`${field} is not recognized`);
      }
    }
  }]);

  return DependencyResolver;
}();

/**
 * if the component doesn't have the env files written on the filesystem there is nothing to pass
 * to the dependencyResolver
 */


exports.default = DependencyResolver;
function shouldProcessEnvDependencies(env) {
  return Boolean(env && env.files && env.files.every(function (file) {
    return !file.fromModel;
  }));
}