"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Npm = void 0;
const semver = __importStar(require("semver"));
const Utilities_1 = require("./Utilities");
async function runNpmCommandAndCaptureOutputAsync(args, workingDirectory, environment) {
    const { stdout, stderr, signal, exitCode } = await Utilities_1.Utilities.executeCommandAndCaptureOutputAsync({
        command: 'npm',
        args,
        workingDirectory,
        environment,
        keepEnvironment: true,
        captureExitCodeAndSignal: true
    });
    if (signal) {
        throw new Error(`The npm command was terminated by signal: ${signal}. Output: ${stdout} ${stderr}`);
    }
    else if (exitCode !== 0) {
        throw new Error(`The npm command failed with exit code: ${exitCode}. Output: ${stdout} ${stderr}`);
    }
    else {
        return stdout;
    }
}
class Npm {
    static async getPublishedVersionsAsync(packageName, workingDirectory, environment, extraArgs = []) {
        const versions = [];
        try {
            const packageTime = await runNpmCommandAndCaptureOutputAsync(['view', packageName, 'time', '--json', ...extraArgs], workingDirectory, environment);
            if (packageTime) {
                Object.keys(JSON.parse(packageTime)).forEach((v) => {
                    if (semver.valid(v)) {
                        versions.push(v);
                    }
                });
            }
            else {
                // eslint-disable-next-line no-console
                console.log(`Package ${packageName} time value does not exist. Fall back to versions.`);
                // time property does not exist. It happens sometimes. Fall back to versions.
                const packageVersions = await runNpmCommandAndCaptureOutputAsync(['view', packageName, 'versions', '--json', ...extraArgs], workingDirectory, environment);
                if (packageVersions && packageVersions.length > 0) {
                    const parsedPackageVersions = JSON.parse(packageVersions);
                    // NPM <= 6 always returns an array, NPM >= 7 returns a string if the package has only one version available
                    (Array.isArray(parsedPackageVersions) ? parsedPackageVersions : [parsedPackageVersions]).forEach((version) => {
                        versions.push(version);
                    });
                }
                else {
                    // eslint-disable-next-line no-console
                    console.log(`No version is found for ${packageName}`);
                }
            }
        }
        catch (e) {
            const error = e;
            if (['E404', 'npm ERR! 404'].some((check) => error.message.includes(check))) {
                // eslint-disable-next-line no-console
                console.log(`Package ${packageName} does not exist in the registry.`);
            }
            else {
                // eslint-disable-next-line no-console
                console.log(`Failed to get NPM information about ${packageName}.`);
                throw error;
            }
        }
        return versions;
    }
}
exports.Npm = Npm;
//# sourceMappingURL=Npm.js.map