"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@pnpm/utils");
const supi_1 = require("supi");
const createStoreController_1 = require("../createStoreController");
const findWorkspacePackages_1 = require("../findWorkspacePackages");
const getPinnedVersion_1 = require("../getPinnedVersion");
const requireHooks_1 = require("../requireHooks");
const recursive_1 = require("./recursive");
const OVERWRITE_UPDATE_OPTIONS = {
    allowNew: true,
    update: false,
};
/**
 * Perform installation.
 * @example
 *     installCmd([ 'lodash', 'foo' ], { silent: true })
 */
async function installCmd(input, opts) {
    // `pnpm install ""` is going to be just `pnpm install`
    input = input.filter(Boolean);
    const prefix = opts.prefix || process.cwd();
    const localPackages = opts.linkWorkspacePackages && opts.workspacePrefix
        ? findWorkspacePackages_1.arrayOfLocalPackagesToMap(await findWorkspacePackages_1.default(opts.workspacePrefix))
        : undefined;
    if (!opts.ignorePnpmfile) {
        opts.hooks = requireHooks_1.default(prefix, opts);
    }
    const store = await createStoreController_1.default(opts);
    const installOpts = Object.assign({}, opts, { 
        // In case installation is done in a multi-package repository
        // The dependencies should be built first,
        // so ignoring scripts for now
        ignoreScripts: !!localPackages || opts.ignoreScripts, localPackages, store: store.path, storeController: store.ctrl });
    if (!input || !input.length) {
        await supi_1.install(installOpts);
    }
    else {
        await supi_1.mutateModules([
            {
                bin: installOpts.bin,
                dependencySelectors: input,
                mutation: 'installSome',
                pinnedVersion: getPinnedVersion_1.default(opts),
                prefix: installOpts.prefix,
                targetDependenciesField: utils_1.getSaveType(installOpts),
            },
        ], installOpts);
    }
    if (opts.linkWorkspacePackages && opts.workspacePrefix) {
        // TODO: reuse somehow the previous read of packages
        // this is not optimal
        const allWorkspacePkgs = await findWorkspacePackages_1.default(opts.workspacePrefix);
        await recursive_1.recursive(allWorkspacePkgs, [], Object.assign({}, opts, OVERWRITE_UPDATE_OPTIONS, { ignoredPackages: new Set([prefix]), packageSelectors: [
                {
                    matcher: prefix,
                    scope: 'dependencies',
                    selectBy: 'location',
                },
            ] }), 'install', 'install');
        if (opts.ignoreScripts)
            return;
        await supi_1.rebuild([{ buildIndex: 0, prefix: opts.prefix }], Object.assign({}, opts, { pending: true })); // tslint:disable-line:no-any
    }
}
exports.default = installCmd;
//# sourceMappingURL=install.js.map