"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 link_bins_1 = require("@pnpm/link-bins");
const logger_1 = require("@pnpm/logger");
const modules_yaml_1 = require("@pnpm/modules-yaml");
const utils_1 = require("@pnpm/utils");
const loadJsonFile = require("load-json-file");
const normalize = require("normalize-path");
const pLimit = require("p-limit");
const path = require("path");
const pathAbsolute = require("path-absolute");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const R = require("ramda");
const symlinkDir = require("symlink-dir");
const getSpecFromPackageJson_1 = require("../getSpecFromPackageJson");
const readShrinkwrapFiles_1 = require("../readShrinkwrapFiles");
const extendInstallOptions_1 = require("./extendInstallOptions");
const install_1 = require("./install");
const linkLogger = logger_1.default('link');
const installLimit = pLimit(4);
function link(linkFromPkgs, destModules, 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 extendInstallOptions_1.default(maybeOpts);
        if (!maybeOpts || !maybeOpts.skipInstall) {
            yield Promise.all(linkFromPkgs.map((prefix) => installLimit(() => install_1.install(Object.assign({}, opts, { bin: path.join(prefix, 'node_modules', '.bin'), global: false, prefix })))));
        }
        const shrFiles = yield readShrinkwrapFiles_1.default({
            force: opts.force,
            prefix: opts.prefix,
            registry: opts.registry,
            shrinkwrap: opts.shrinkwrap,
        });
        const oldShrinkwrap = R.clone(shrFiles.currentShrinkwrap);
        const pkg = (yield utils_1.safeReadPackage(path.join(opts.prefix, 'package.json'))) || undefined;
        const linkedPkgs = [];
        for (const linkFrom of linkFromPkgs) {
            const linkedPkg = yield loadJsonFile(path.join(linkFrom, 'package.json'));
            const packagePath = normalize(path.relative(opts.prefix, linkFrom));
            const addLinkOpts = {
                linkedPkgName: linkedPkg.name,
                packagePath,
                pkg,
            };
            addLinkToShrinkwrap(shrFiles.currentShrinkwrap, addLinkOpts);
            addLinkToShrinkwrap(shrFiles.wantedShrinkwrap, addLinkOpts);
            linkedPkgs.push({ path: linkFrom, pkg: linkedPkg });
        }
        const updatedCurrentShrinkwrap = pnpm_shrinkwrap_1.prune(shrFiles.currentShrinkwrap);
        const updatedWantedShrinkwrap = pnpm_shrinkwrap_1.prune(shrFiles.wantedShrinkwrap);
        const modulesInfo = yield modules_yaml_1.read(destModules);
        yield utils_1.removeOrphanPackages({
            bin: opts.bin,
            hoistedAliases: modulesInfo && modulesInfo.hoistedAliases || {},
            newShrinkwrap: updatedCurrentShrinkwrap,
            oldShrinkwrap,
            prefix: opts.prefix,
            shamefullyFlatten: opts.shamefullyFlatten,
            storeController: opts.storeController,
        });
        // Linking should happen after removing orphans
        // Otherwise would've been removed
        for (const linkedPkg of linkedPkgs) {
            yield linkToModules(linkedPkg.pkg.name, linkedPkg.path, destModules);
        }
        const linkToBin = maybeOpts && maybeOpts.linkToBin || path.join(destModules, '.bin');
        yield link_bins_1.linkBinsOfPackages(linkedPkgs.map((p) => ({ manifest: p.pkg, location: p.path })), linkToBin);
        if (opts.shrinkwrap) {
            yield pnpm_shrinkwrap_1.write(opts.prefix, updatedWantedShrinkwrap, updatedCurrentShrinkwrap);
        }
        else {
            yield pnpm_shrinkwrap_1.writeCurrentOnly(opts.prefix, updatedCurrentShrinkwrap);
        }
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
    });
}
exports.default = link;
function addLinkToShrinkwrap(shr, opts) {
    const id = `link:${opts.packagePath}`;
    let addedTo;
    for (const depType of utils_1.dependenciesTypes) {
        if (opts.pkg && opts.pkg[depType]) {
            addedTo = depType;
            shr[depType] = shr[depType] || {};
            shr[depType][opts.linkedPkgName] = id;
        }
        else if (shr[depType]) {
            delete shr[depType][opts.linkedPkgName];
        }
    }
    if (!addedTo) {
        shr.dependencies = shr.dependencies || {};
        shr.dependencies[opts.linkedPkgName] = id;
    }
    // package.json might not be available when linking to global
    if (!opts.pkg)
        return;
    const availableSpec = getSpecFromPackageJson_1.default(opts.pkg, opts.linkedPkgName);
    if (availableSpec) {
        shr.specifiers[opts.linkedPkgName] = availableSpec;
    }
    else {
        delete shr.specifiers[opts.linkedPkgName];
    }
}
function linkToModules(pkgName, linkFrom, modules) {
    return __awaiter(this, void 0, void 0, function* () {
        const dest = path.join(modules, pkgName);
        linkLogger.info(`${dest} -> ${linkFrom}`);
        yield symlinkDir(linkFrom, dest);
    });
}
function linkFromGlobal(pkgNames, linkTo, 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 extendInstallOptions_1.default(maybeOpts);
        const globalPkgPath = pathAbsolute(maybeOpts.globalPrefix);
        const linkFromPkgs = pkgNames.map((pkgName) => path.join(globalPkgPath, 'node_modules', pkgName));
        yield link(linkFromPkgs, path.join(linkTo, 'node_modules'), opts);
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
    });
}
exports.linkFromGlobal = linkFromGlobal;
function linkToGlobal(linkFrom, 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 extendInstallOptions_1.default(maybeOpts);
        const globalPkgPath = pathAbsolute(maybeOpts.globalPrefix);
        yield link([linkFrom], path.join(globalPkgPath, 'node_modules'), Object.assign({}, opts, { linkToBin: maybeOpts.globalBin, prefix: maybeOpts.globalPrefix }));
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
    });
}
exports.linkToGlobal = linkToGlobal;
//# sourceMappingURL=link.js.map