"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGlobalNpm = exports.getNpm = void 0;
const system_settings_1 = require("@ewizardjs/system-settings");
const upath_1 = require("@ewizardjs/upath");
const child_process_1 = require("child_process");
const util_1 = require("util");
const execAsync = (0, util_1.promisify)(child_process_1.exec);
function getNpm(options) {
    const { npmVersion = system_settings_1.NpmVersion.Latest, root = false } = options !== null && options !== void 0 ? options : {};
    const npm = `npm-${npmVersion}`;
    return root ? resolveModuleRoot(npm) : resolveModule(npm);
}
exports.getNpm = getNpm;
function getGlobalNpm() {
    return __awaiter(this, void 0, void 0, function* () {
        const modulesPath = yield globalModulesPath();
        return resolveModule('npm', [modulesPath]);
    });
}
exports.getGlobalNpm = getGlobalNpm;
function resolveModuleRoot(moduleName, paths) {
    const pathToPackageJson = resolveModule((0, upath_1.join)(moduleName, 'package.json'), paths);
    return pathToPackageJson ? (0, upath_1.dirname)(pathToPackageJson) : null;
}
function resolveModule(moduleName, paths) {
    try {
        return require.resolve(moduleName, { paths });
    }
    catch (_a) {
        return null;
    }
}
function globalModulesPath() {
    return __awaiter(this, void 0, void 0, function* () {
        const { stdout } = yield execAsync('npm root -g');
        return stdout.trim().replace(/\n/g, '');
    });
}
//# sourceMappingURL=getNpm.js.map