"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.isScopedPackagePath = exports.doResolvePath = exports.doResolve = void 0;var _resolve = _interopRequireDefault(require("resolve"));
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);enumerableOnly && (symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;})), keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = null != arguments[i] ? arguments[i] : {};i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {_defineProperty(target, key, source[key]);}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}return target;}function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return obj;}function _slicedToArray(arr, i) {return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();}function _nonIterableRest() {throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _iterableToArrayLimit(arr, i) {var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];if (_i == null) return;var _arr = [];var _n = true;var _d = false;var _s, _e;try {for (_i = _i.call(arr); !(_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"] != null) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}function _arrayWithHoles(arr) {if (Array.isArray(arr)) return arr;}function _toConsumableArray(arr) {return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();}function _nonIterableSpread() {throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _iterableToArray(iter) {if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);}function _arrayWithoutHoles(arr) {if (Array.isArray(arr)) return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
/**
 * An attempt at drying out filesystem references to [external packages](https://tinyurl.com/mao2dy6).
 *
 * We access external packages for a number of reasons:
 *  - to simply resolve a non-scoped package's (absolute) path on disk. e.g. '/var/project/node_modules/react-native'
 *  - to resolve a scoped package's (absolute) path on disk. e.g. '/var/project/node_modules/@aScope/react-native'
 *  - to resolve an individual file/dir's (absolute) path on disk. e.g. '/var/project/node_modules/react-native/blur/android' (note this is a normally illegal package reference)
 *  - to resolve an individual file (absolute) path on disk by FS relative reference. e.g. '/var/project/node_modules/react-native/relPath'
 *
 * ** Please note that we do not support [subpackage paths](https://tinyurl.com/vub6c7t). All suffixed paths (e.g. 'react-native/SUFFIX_PATH', '@aScope/react-native/SUFFIX_PATH')
 * will be treated as a filepath from root of resolved package (i.e. will ignore subdirectory package.json)
 *
 * @param {*} aPath - package name. e.g. 'file:../rel/path', 'react-native', 'react-native/android', '@react-native-community/masked-view/android'
 * @param {*} mandatory - whether it throws
 * @param {*} options - docs - https://tinyurl.com/r9sfpf7 && {keepSuffix: boolean}
 */
var doResolve = function doResolve(aPath) {var _options$basedir;var mandatory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  options.basedir = (_options$basedir = options.basedir) !== null && _options$basedir !== void 0 ? _options$basedir : process.cwd();
  try {
    if (aPath.startsWith('file:')) {
      return _withPathFix(_doResolveFSPath(aPath, options), options === null || options === void 0 ? void 0 : options.forceForwardPaths);
    }
    return _withPathFix(_doResolveExternalPackage(aPath, options), options === null || options === void 0 ? void 0 : options.forceForwardPaths);
  } catch (err) {
    // perhaps do some warning logging here..
    if (mandatory) throw err;
  }
};exports.doResolve = doResolve;

var _withPathFix = function _withPathFix(p, forceForwardPaths) {
  if (p && forceForwardPaths) {
    return p.replace(/\\/g, '/');
  }
  return p;
};

var doResolvePath = function doResolvePath(aPath) {var _options$basedir2;var mandatory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};var fallbackBase = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
  options.basedir = (_options$basedir2 = options.basedir) !== null && _options$basedir2 !== void 0 ? _options$basedir2 : process.cwd();

  try {
    var pathArr = aPath.split('/');
    // Take care of scenario when someone wrote: "/node_modules/.." instead of "node_modules/..."
    if (pathArr[0] === '') {
      pathArr.shift();
    }
    if (pathArr[0] === 'node_modules') {
      pathArr.shift();
    }
    if (pathArr[0] === 'packages') {
      pathArr.shift();
    }
    var cleanPath = pathArr.join('/');
    if (pathArr[0].startsWith('@')) {
      pathArr.shift();
    }
    pathArr.shift();
    var realPath = doResolve(cleanPath, mandatory, options);
    if (realPath) {
      return _withPathFix(_path["default"].join.apply(_path["default"], [realPath].concat(_toConsumableArray(pathArr))), options === null || options === void 0 ? void 0 : options.forceForwardPaths);
    }
    return _withPathFix(_path["default"].join(fallbackBase, aPath), options === null || options === void 0 ? void 0 : options.forceForwardPaths);
  } catch (err) {
    if (mandatory) throw err;
  }
};exports.doResolvePath = doResolvePath;

var isScopedPackagePath = function isScopedPackagePath(aPath) {
  if (aPath.startsWith('@')) {
    if (!aPath.includes('/')) {
      throw new Error("Scoped packages must include subpackage portion e.g. '@aScope/subpackage'. Supplied path: ".concat(
      aPath));

    }
    return true;
  }
};exports.isScopedPackagePath = isScopedPackagePath;

var _getPackagePathParts = function _getPackagePathParts(aPath) {
  var parts = [];
  if (isScopedPackagePath(aPath)) {
    parts = aPath.match(/^([^/]+\/[^/]+)(?:\/?(.*))/);
  } else {
    parts = aPath.match(/^([^/]+)\/?(.*)/);
  }
  if (!Array.isArray(parts)) {
    throw new Error("Unsuitable path for resolving: ".concat(aPath));
  }
  return parts.slice(1);
};

/**
 * We support path linking using 'file:' protocol (not part of official node resolution alg.)
 */
var _doResolveFSPath = function _doResolveFSPath(aPath, options) {
  var fileRelPath = "".concat(
  options.basedir ? "".concat(options.basedir, "/").replace(/.*\/+$/, '/') : '').concat(
  aPath.replace('file:', ''));
  if (!_fs["default"].existsSync(fileRelPath)) {
    throw new Error("Explicit filepath ".concat(
    aPath, " does not resolve to dir or file"));

  }
  return fileRelPath;
};

/**
 * @see 'LOAD_NODE_MODULES' of node resolution alg. - https://tinyurl.com/pgz6f33
 */
var _doResolveExternalPackage = function _doResolveExternalPackage(aPath, options) {
  var _getPackagePathParts2 = _getPackagePathParts(aPath),_getPackagePathParts3 = _slicedToArray(_getPackagePathParts2, 2),packageBase = _getPackagePathParts3[0],packageSuffix = _getPackagePathParts3[1];

  try {var _options$extensions, _options$keepSuffix;
    var resolvedPath = _resolve["default"].
    sync(packageBase, _objectSpread(_objectSpread({
      packageFilter: function packageFilter(pkg) {
        pkg.main = 'package.json';
        return pkg;
      } },
    options), {}, {
      extensions: ['.js', '.json'].concat((_options$extensions = options.extensions) !== null && _options$extensions !== void 0 ? _options$extensions : []) })).

    replace(/(\\|\/)package.json$/, '');
    return ((_options$keepSuffix = options.keepSuffix) !== null && _options$keepSuffix !== void 0 ? _options$keepSuffix : false) ? "".concat(
    resolvedPath, "/").concat(packageSuffix) :
    resolvedPath;
  } catch (e) {
    return null;
  }
};
//# sourceMappingURL=resolve.js.map