"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.getNpmDefinitions = exports.getGlobalNpm = exports.getNpm = void 0;
const node_child_process_1 = require("node:child_process");
const promises_1 = require("node:fs/promises");
const node_os_1 = require("node:os");
const node_util_1 = require("node:util");
const system_settings_1 = require("@ewizardjs/system-settings");
const upath_1 = require("@ewizardjs/upath");
const child_process_promise_1 = require("child-process-promise");
const execAsync = (0, node_util_1.promisify)(node_child_process_1.exec);
const LEGACY_PACKAGE_SPEC = 'npm-legacy@npm:npm@^6.14.18';
const LEGACY_MODULE_NAME = 'npm-legacy';
const legacyDir = (0, upath_1.join)((0, node_os_1.tmpdir)(), 'ewizard-cli', 'npm-legacy');
const legacyModulePaths = [(0, upath_1.join)(legacyDir, 'node_modules'), (0, upath_1.join)(legacyDir, 'lib', 'node_modules')];
function getNpm(options) {
    return __awaiter(this, void 0, void 0, function* () {
        const { npmVersion = system_settings_1.NpmVersion.Latest, root = false } = options !== null && options !== void 0 ? options : {};
        if (npmVersion === system_settings_1.NpmVersion.Legacy) {
            const modulePaths = legacyModulePaths;
            const legacyNpm = yield ensureLegacyNpm(modulePaths);
            return root ? resolveModuleRoot(LEGACY_MODULE_NAME, modulePaths) : legacyNpm;
        }
        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 getNpmDefinitions() {
    return __awaiter(this, void 0, void 0, function* () {
        const npmPath = yield getNpm({ npmVersion: system_settings_1.NpmVersion.Latest, root: true });
        return npmPath ? resolveModule('@npmcli/config/lib/definitions', [npmPath]) : null;
    });
}
exports.getNpmDefinitions = getNpmDefinitions;
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, '');
    });
}
function ensureLegacyNpm(modulePaths) {
    return __awaiter(this, void 0, void 0, function* () {
        let legacyNpm = resolveModule(LEGACY_MODULE_NAME, modulePaths);
        if (legacyNpm) {
            return legacyNpm;
        }
        yield (0, promises_1.mkdir)(legacyDir, { recursive: true });
        yield (0, child_process_promise_1.spawn)('npm', [
            'install',
            '--no-save',
            '--quiet',
            '--registry=https://registry.npmjs.org',
            '--prefix',
            legacyDir,
            LEGACY_PACKAGE_SPEC,
        ]);
        legacyNpm = resolveModule(LEGACY_MODULE_NAME, modulePaths);
        if (!legacyNpm) {
            throw new Error('Failed to resolve legacy npm installation');
        }
        return legacyNpm;
    });
}
//# sourceMappingURL=getNpm.js.map