"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 logger_1 = require("@pnpm/logger");
const package_bins_1 = require("@pnpm/package-bins");
const cmdShim = require("@zkochan/cmd-shim");
const isWindows = require("is-windows");
const mkdirp = require("mkdirp-promise");
const Module = require("module");
const fs = require("mz/fs");
const normalizePath = require("normalize-path");
const path = require("path");
const R = require("ramda");
const readPackageJson = require("read-package-json");
const getPkgDirs_1 = require("./getPkgDirs");
const IS_WINDOWS = isWindows();
exports.default = (modules, binPath, exceptPkgName) => __awaiter(this, void 0, void 0, function* () {
    const pkgDirs = yield getPkgDirs_1.default(modules);
    const allCmds = R.unnest((yield Promise.all(pkgDirs
        .map(normalizePath)
        .filter((pkgDir) => !exceptPkgName || !pkgDir.endsWith(`/${exceptPkgName}`))
        .map(getPackageBins)))
        .filter((cmds) => cmds.length));
    return linkBins(allCmds, binPath);
});
function linkBinsOfPackages(pkgs, binsTarget) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!pkgs.length)
            return;
        const allCmds = R.unnest((yield Promise.all(pkgs
            .map((pkg) => getPackageBinsFromPackageJson(pkg.manifest, pkg.location))))
            .filter((cmds) => cmds.length));
        return linkBins(allCmds, binsTarget);
    });
}
exports.linkBinsOfPackages = linkBinsOfPackages;
function linkBins(allCmds, binPath) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!allCmds.length)
            return;
        yield mkdirp(binPath);
        const [cmdsWithOwnName, cmdsWithOtherNames] = R.partition((cmd) => cmd.ownName, allCmds);
        yield Promise.all(cmdsWithOwnName.map((cmd) => linkBin(cmd, binPath)));
        const usedNames = R.fromPairs(cmdsWithOwnName.map((cmd) => [cmd.name, cmd.name]));
        yield Promise.all(cmdsWithOtherNames.map((cmd) => {
            if (usedNames[cmd.name]) {
                logger_1.default.warn(`Cannot link bin "${cmd.name}" of "${cmd.pkgName}" to "${binPath}". A package called "${usedNames[cmd.name]}" already has its bin linked.`);
                return;
            }
            usedNames[cmd.name] = cmd.pkgName;
            return linkBin(cmd, binPath);
        }));
    });
}
function getPackageBins(target) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield safeReadPkg(path.join(target, 'package.json'));
        if (!pkg) {
            logger_1.default.warn(`There's a directory in node_modules without package.json: ${target}`);
            return [];
        }
        return getPackageBinsFromPackageJson(pkg, target);
    });
}
function getPackageBinsFromPackageJson(pkgJson, pkgPath) {
    return __awaiter(this, void 0, void 0, function* () {
        const cmds = yield package_bins_1.default(pkgJson, pkgPath);
        return cmds.map((cmd) => (Object.assign({}, cmd, { ownName: cmd.name === pkgJson.name, pkgName: pkgJson.name })));
    });
}
function linkBin(cmd, binPath) {
    return __awaiter(this, void 0, void 0, function* () {
        const externalBinPath = path.join(binPath, cmd.name);
        const nodePath = (yield getBinNodePaths(cmd.path)).join(path.delimiter);
        return cmdShim(cmd.path, externalBinPath, { nodePath });
    });
}
function getBinNodePaths(target) {
    return __awaiter(this, void 0, void 0, function* () {
        const targetRealPath = yield fs.realpath(target);
        return R.union(Module['_nodeModulePaths'](targetRealPath), // tslint:disable-line:no-string-literal
        Module['_nodeModulePaths'](target));
    });
}
function safeReadPkg(pkgPath) {
    return new Promise((resolve, reject) => {
        readPackageJson(pkgPath, (err, pkg) => {
            if (!err) {
                resolve(pkg);
            }
            else if (err.code !== 'ENOENT') {
                reject(err);
            }
            else {
                resolve(null);
            }
        });
    });
}
//# sourceMappingURL=index.js.map