"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 });
const path = require("path");
const getContext_1 = require("./getContext");
const getSaveType_1 = require("../getSaveType");
const removeDeps_1 = require("../removeDeps");
const extendOptions_1 = require("./extendOptions");
const lock_1 = require("./lock");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const logger_1 = require("@pnpm/logger");
const modulesController_1 = require("../fs/modulesController");
const removeOrphanPkgs_1 = require("./removeOrphanPkgs");
const safeIsInnerLink_1 = require("../safeIsInnerLink");
const removeTopDependency_1 = require("../removeTopDependency");
const shrinkwrapsEqual_1 = require("./shrinkwrapsEqual");
function uninstall(pkgsToUninstall, maybeOpts) {
    return __awaiter(this, void 0, void 0, function* () {
        const reporter = maybeOpts && maybeOpts.reporter;
        if (reporter) {
            logger_1.streamParser.on('data', reporter);
        }
        const opts = yield extendOptions_1.default(maybeOpts);
        if (opts.lock) {
            yield lock_1.default(opts.prefix, _uninstall, { stale: opts.lockStaleDuration, locks: opts.locks });
        }
        else {
            yield _uninstall();
        }
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
        function _uninstall() {
            return __awaiter(this, void 0, void 0, function* () {
                const ctx = yield getContext_1.default(opts);
                if (!ctx.pkg) {
                    throw new Error('No package.json found - cannot uninstall');
                }
                if (opts.lock === false) {
                    return run();
                }
                return lock_1.default(ctx.storePath, run, { stale: opts.lockStaleDuration, locks: opts.locks });
                function run() {
                    return uninstallInContext(pkgsToUninstall, ctx, opts);
                }
            });
        }
    });
}
exports.default = uninstall;
function uninstallInContext(pkgsToUninstall, ctx, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const makePartialCurrentShrinkwrap = !shrinkwrapsEqual_1.default(ctx.currentShrinkwrap, ctx.wantedShrinkwrap);
        const pkgJsonPath = path.join(ctx.root, 'package.json');
        const saveType = getSaveType_1.default(opts);
        const pkg = yield removeDeps_1.default(pkgJsonPath, pkgsToUninstall, saveType);
        const newShr = pnpm_shrinkwrap_1.prune(ctx.wantedShrinkwrap, pkg);
        const removedPkgIds = yield removeOrphanPkgs_1.default({
            oldShrinkwrap: ctx.currentShrinkwrap,
            newShrinkwrap: newShr,
            prefix: ctx.root,
            store: ctx.storePath,
            storeIndex: ctx.storeIndex,
            bin: opts.bin,
        });
        const currentShrinkwrap = makePartialCurrentShrinkwrap
            ? pnpm_shrinkwrap_1.prune(ctx.currentShrinkwrap, pkg)
            : newShr;
        yield pnpm_shrinkwrap_1.write(ctx.root, newShr, currentShrinkwrap);
        yield modulesController_1.save(path.join(ctx.root, 'node_modules'), {
            packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`,
            store: ctx.storePath,
            skipped: Array.from(ctx.skipped).filter(pkgId => removedPkgIds.indexOf(pkgId) === -1),
            layoutVersion: modulesController_1.LAYOUT_VERSION,
            independentLeaves: opts.independentLeaves,
        });
        yield removeOuterLinks(pkgsToUninstall, path.join(ctx.root, 'node_modules'), {
            storePath: ctx.storePath,
            bin: opts.bin,
        });
        logger_1.default('summary').info();
    });
}
exports.uninstallInContext = uninstallInContext;
function removeOuterLinks(pkgsToUninstall, modules, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        // These packages are not in package.json, they were just linked in not installed
        for (const pkgToUninstall of pkgsToUninstall) {
            if ((yield safeIsInnerLink_1.default(modules, pkgToUninstall, opts)) !== true) {
                yield removeTopDependency_1.default({
                    name: pkgToUninstall,
                    dev: false,
                    optional: false,
                }, {
                    modules,
                    bin: opts.bin,
                });
            }
        }
    });
}
//# sourceMappingURL=uninstall.js.map