"use strict";

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

var _child_process = require("child_process");

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

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;
  }

  try {
    const paths = [local && process.cwd(), global && globalNodeModules].filter(Boolean); // x({ paths, globalNodeModules, global, local, opts });

    const moduleResolvePath = require.resolve(moduleName, {
      paths
    });

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

function requireLocal(moduleName) {
  return requireLocalOrGlobal(moduleName, {
    global: false,
    local: true
  });
}

function requireGlobal(moduleName) {
  return requireLocalOrGlobal(moduleName, {
    global: true,
    local: false
  });
}