"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_loggers_1 = require("@pnpm/core-loggers");
const logger_1 = require("@pnpm/logger");
const modules_cleaner_1 = require("@pnpm/modules-cleaner");
const modules_yaml_1 = require("@pnpm/modules-yaml");
const prune_shrinkwrap_1 = require("@pnpm/prune-shrinkwrap");
const shamefully_flatten_1 = require("@pnpm/shamefully-flatten");
const shrinkwrap_file_1 = require("@pnpm/shrinkwrap-file");
const utils_1 = require("@pnpm/utils");
const dp = require("dependency-path");
const path = require("path");
const constants_1 = require("../constants");
const getContext_1 = require("../getContext");
const lock_1 = require("../lock");
const shrinkwrapsEqual_1 = require("../shrinkwrapsEqual");
const extendUninstallOptions_1 = require("./extendUninstallOptions");
const removeDeps_1 = require("./removeDeps");
async function uninstall(pkgsToUninstall, maybeOpts) {
    const reporter = maybeOpts && maybeOpts.reporter;
    if (reporter) {
        logger_1.streamParser.on('data', reporter);
    }
    const opts = await extendUninstallOptions_1.default(maybeOpts);
    if (opts.lock) {
        await lock_1.default(opts.prefix, _uninstall, {
            locks: opts.locks,
            prefix: opts.prefix,
            stale: opts.lockStaleDuration,
            storeController: opts.storeController,
        });
    }
    else {
        await _uninstall();
    }
    if (reporter) {
        logger_1.streamParser.removeListener('data', reporter);
    }
    async function _uninstall() {
        const ctx = await getContext_1.getContextForSingleImporter(opts);
        if (!ctx.pkg) {
            throw new Error('No package.json found - cannot uninstall');
        }
        return uninstallInContext(pkgsToUninstall, ctx, opts);
    }
}
exports.default = uninstall;
async function uninstallInContext(pkgsToUninstall, ctx, opts) {
    const makePartialCurrentShrinkwrap = !shrinkwrapsEqual_1.default(ctx.currentShrinkwrap, ctx.wantedShrinkwrap);
    const pkgJsonPath = path.join(ctx.prefix, 'package.json');
    const saveType = utils_1.getSaveType(opts);
    const pkg = await removeDeps_1.default(pkgJsonPath, pkgsToUninstall, { prefix: opts.prefix, saveType });
    const newShr = prune_shrinkwrap_1.prune(ctx.wantedShrinkwrap, pkg, ctx.importerId, {
        defaultRegistry: ctx.registries.default,
        warn: (message) => logger_1.default.warn({ message, prefix: ctx.prefix }),
    });
    const removedPkgIds = await modules_cleaner_1.prune({
        importers: [
            {
                bin: opts.bin,
                hoistedAliases: ctx.hoistedAliases,
                id: ctx.importerId,
                modulesDir: ctx.modulesDir,
                prefix: ctx.prefix,
                removePackages: pkgsToUninstall,
                shamefullyFlatten: opts.shamefullyFlatten,
            },
        ],
        newShrinkwrap: newShr,
        oldShrinkwrap: ctx.currentShrinkwrap,
        registries: ctx.registries,
        shrinkwrapDirectory: opts.shrinkwrapDirectory,
        storeController: opts.storeController,
        virtualStoreDir: ctx.virtualStoreDir,
    });
    ctx.pendingBuilds = ctx.pendingBuilds.filter((pkgId) => !removedPkgIds.has(dp.resolve(ctx.registries, pkgId)));
    await opts.storeController.close();
    const currentShrinkwrap = makePartialCurrentShrinkwrap
        ? prune_shrinkwrap_1.prune(ctx.currentShrinkwrap, pkg, ctx.importerId, { defaultRegistry: ctx.registries.default })
        : newShr;
    const shrinkwrapOpts = { forceSharedFormat: opts.forceSharedShrinkwrap };
    if (opts.shrinkwrap) {
        await shrinkwrap_file_1.write(ctx.shrinkwrapDirectory, newShr, currentShrinkwrap, shrinkwrapOpts);
    }
    else {
        await shrinkwrap_file_1.writeCurrentOnly(ctx.shrinkwrapDirectory, currentShrinkwrap, shrinkwrapOpts);
    }
    if (opts.shamefullyFlatten) {
        ctx.hoistedAliases = await shamefully_flatten_1.shamefullyFlattenByShrinkwrap(currentShrinkwrap, ctx.importerId, {
            getIndependentPackageLocation: opts.independentLeaves
                ? async (packageId, packageName) => {
                    const { directory } = await opts.storeController.getPackageLocation(packageId, packageName, {
                        importerPrefix: ctx.shrinkwrapDirectory,
                        targetEngine: opts.sideEffectsCacheRead && constants_1.ENGINE_NAME || undefined,
                    });
                    return directory;
                }
                : undefined,
            modulesDir: ctx.modulesDir,
            prefix: opts.shrinkwrapDirectory,
            registries: ctx.registries,
            virtualStoreDir: ctx.virtualStoreDir,
        }) || {};
    }
    await modules_yaml_1.write(ctx.virtualStoreDir, Object.assign({}, ctx.modulesFile, { importers: Object.assign({}, ctx.modulesFile && ctx.modulesFile.importers, { [ctx.importerId]: {
                hoistedAliases: ctx.hoistedAliases,
                shamefullyFlatten: opts.shamefullyFlatten,
            } }), included: ctx.include, independentLeaves: opts.independentLeaves, layoutVersion: constants_1.LAYOUT_VERSION, packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, pendingBuilds: ctx.pendingBuilds, registries: ctx.registries, skipped: Array.from(ctx.skipped).filter((pkgId) => !removedPkgIds.has(pkgId)), store: ctx.storePath }));
    core_loggers_1.summaryLogger.debug({ prefix: opts.prefix });
}
exports.uninstallInContext = uninstallInContext;
//# sourceMappingURL=index.js.map