"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
// Map SIGINT & SIGTERM to process exit
// so that lockfiles are removed automatically
process
    .once('SIGINT', () => process.exit(1))
    .once('SIGTERM', () => process.exit(1));
// Patch the global fs module here at the app level
const fs = require("fs");
const gfs = require("graceful-fs");
gfs.gracefulify(fs);
const loudRejection = require("loud-rejection");
loudRejection();
const config_1 = require("@pnpm/config");
const logger_1 = require("@pnpm/logger");
const isCI = require("is-ci");
const nopt = require("nopt");
const checkForUpdates_1 = require("./checkForUpdates");
const pnpmCmds = require("./cmd");
const runNpm_1 = require("./cmd/runNpm");
const getCommandFullName_1 = require("./getCommandFullName");
require("./logging/fileLogger");
const pnpmPkgJson_1 = require("./pnpmPkgJson");
const reporter_1 = require("./reporter");
pnpmCmds['install-test'] = pnpmCmds.installTest;
const supportedCmds = new Set([
    'add',
    'install',
    'uninstall',
    'update',
    'link',
    'prune',
    'install-test',
    'run',
    'server',
    'store',
    'list',
    'unlink',
    'help',
    'root',
    'outdated',
    'rebuild',
    'recursive',
]);
const passedThroughCmds = new Set([
    'access',
    'adduser',
    'bin',
    'bugs',
    'c',
    'config',
    'deprecate',
    'dist-tag',
    'docs',
    'edit',
    'get',
    'info',
    'init',
    'login',
    'logout',
    'owner',
    'pack',
    'ping',
    'prefix',
    'profile',
    'publish',
    'repo',
    'restart',
    's',
    'se',
    'search',
    'set',
    'star',
    'stars',
    'start',
    'stop',
    'team',
    't',
    'tst',
    'test',
    'token',
    'unpublish',
    'unstar',
    'v',
    'version',
    'view',
    'whoami',
    'xmas',
]);
function run(argv) {
    return __awaiter(this, void 0, void 0, function* () {
        // tslint:disable
        const shortHands = {
            's': ['--loglevel', 'silent'],
            'd': ['--loglevel', 'info'],
            'dd': ['--loglevel', 'verbose'],
            'ddd': ['--loglevel', 'silly'],
            'noreg': ['--no-registry'],
            'N': ['--no-registry'],
            'reg': ['--registry'],
            'no-reg': ['--no-registry'],
            'silent': ['--loglevel', 'silent'],
            'verbose': ['--loglevel', 'verbose'],
            'quiet': ['--loglevel', 'warn'],
            'q': ['--loglevel', 'warn'],
            'h': ['--usage'],
            'H': ['--usage'],
            '?': ['--usage'],
            'help': ['--usage'],
            'v': ['--version'],
            'f': ['--force'],
            'desc': ['--description'],
            'no-desc': ['--no-description'],
            'local': ['--no-global'],
            'l': ['--long'],
            'm': ['--message'],
            'p': ['--parseable'],
            'porcelain': ['--parseable'],
            'prod': ['--production'],
            'g': ['--global'],
            'S': ['--save'],
            'D': ['--save-dev'],
            'P': ['--save-prod'],
            'E': ['--save-exact'],
            'O': ['--save-optional'],
            'y': ['--yes'],
            'n': ['--no-yes'],
            'B': ['--save-bundle'],
            'C': ['--prefix'],
        };
        // tslint:enable
        const cliConf = nopt(config_1.types, shortHands, argv, 0);
        let cmd = getCommandFullName_1.default(cliConf.argv.remain[0]) || 'help';
        if (!supportedCmds.has(cmd)) {
            if (passedThroughCmds.has(cmd)) {
                runNpm_1.default(argv);
                return Promise.resolve();
            }
            cmd = 'help';
        }
        if (cliConf['dry-run']) {
            console.error(`Error: 'dry-run' is not supported yet, sorry!`);
            process.exit(1);
        }
        cliConf.save = cliConf.save || !cliConf['save-dev'] && !cliConf['save-optional'];
        const opts = yield config_1.default({
            cliArgs: cliConf,
            packageManager: pnpmPkgJson_1.default,
        });
        const selfUpdate = opts.global && (cmd === 'install' || cmd === 'update') && cliConf.argv.remain.indexOf(pnpmPkgJson_1.default.name) !== -1;
        // Don't check for updates
        //   1. on CI environments
        //   2. when in the middle of an actual update
        if (!isCI && !selfUpdate) {
            checkForUpdates_1.default();
        }
        const reporterType = (() => {
            if (opts.loglevel === 'silent')
                return 'silent';
            if (opts.reporter)
                return opts.reporter;
            if (isCI || !process.stdout.isTTY)
                return 'append-only';
            return 'default';
        })();
        reporter_1.default(reporterType, {
            cmd,
            prefix: opts.prefix,
            subCmd: cliConf.argv.remain[1] && getCommandFullName_1.default(cliConf.argv.remain[1]),
        });
        delete opts.reporter; // This is a silly workaround because supi expects a function as opts.reporter
        if (selfUpdate) {
            yield pnpmCmds.server(['stop'], opts);
        }
        // NOTE: we defer the next stage, otherwise reporter might not catch all the logs
        yield new Promise((resolve, reject) => {
            setTimeout(() => {
                // `pnpm install ""` is going to be just `pnpm install`
                const cliArgs = cliConf.argv.remain.slice(1).filter(Boolean);
                try {
                    const result = pnpmCmds[cmd](cliArgs, opts, cliConf.argv.remain[0]);
                    if (result instanceof Promise) {
                        result
                            .then(resolve)
                            .catch(reject);
                    }
                    else {
                        resolve();
                    }
                }
                catch (err) {
                    reject(err);
                }
            }, 0);
        });
        logger_1.default('cli').debug('command_done');
    });
}
exports.default = run;
//# sourceMappingURL=main.js.map