"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.globalNodeModules = void 0;
exports.requireAllPossible = requireAllPossible;
exports.requireGlobal = requireGlobal;
exports.requireInFolder = requireInFolder;
exports.requireLocal = requireLocal;
exports.requireLocalOrGlobal = requireLocalOrGlobal;

var _child_process = require("child_process");

var _path = _interopRequireDefault(require("path"));

var _constants = require("../constants");

var _logger = require("../../logger");

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

const globalNodeModules = _path.default.join(`${(0, _child_process.execSync)('npm config get prefix')}`.trim(), 'lib');

exports.globalNodeModules = globalNodeModules;

function requireLocalOrGlobal(moduleName, opts = {}) {
  let {
    global = true
  } = opts;
  const {
    local = true
  } = opts;
  const isRelativePath = moduleName[0] === '.'; // NOTE: if starts with . then it only mean local

  if (isRelativePath) {
    global = false;
  }

  const paths = [local && _constants.appPath, global && globalNodeModules].filter(Boolean); // eslint-disable-next-line no-use-before-define

  return requireInFolder(moduleName, paths);
}

function requireInFolder(moduleName, paths) {
  try {
    const moduleResolvePath = require.resolve(moduleName, {
      paths
    }); // eslint-disable-next-line import/no-dynamic-require, global-require


    return require(moduleResolvePath);
  } catch (error) {
    // NOTE: since we return null we can check out side
    (0, _logger.verboseLogger)('Re validate: ', error);
    return null;
  }
}

function requireLocal(moduleName) {
  return requireInFolder(moduleName, [_constants.appPath]);
}

function requireGlobal(moduleName) {
  const isRelativePath = moduleName[0] === '.'; // NOTE: if starts with . then it only mean local

  if (isRelativePath) {
    return null;
  }

  return requireInFolder(moduleName, [globalNodeModules]);
}

function requireAllPossible(moduleName) {
  const localP = requireLocal(moduleName);
  const globalP = localP ? null : requireGlobal(moduleName);
  return {
    local: localP,
    global: globalP
  };
}