"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const semver = require("semver");
const R = require("ramda");
const npa = require("npm-package-arg");
function default_1(pkgs) {
    const pkgMap = createPkgMap(pkgs);
    const unmatched = [];
    const graph = Object.keys(pkgMap)
        .reduce((acc, pkgSpec) => {
        acc[pkgSpec] = {
            manifest: pkgMap[pkgSpec].manifest,
            dependencies: createNode(pkgMap[pkgSpec])
        };
        return acc;
    }, {});
    return { graph, unmatched };
    function createNode(pkg) {
        const dependencies = Object.assign({}, pkg.manifest.devDependencies, pkg.manifest.optionalDependencies, pkg.manifest.dependencies);
        return Object.keys(dependencies)
            .map(depName => {
            const spec = npa.resolve(depName, dependencies[depName], pkg.path);
            if (spec.type === 'directory') {
                const matchedPkg = R.values(pkgMap).find(pkg => pkg.path === spec.fetchSpec);
                if (!matchedPkg) {
                    return '';
                }
                return matchedPkg.path;
            }
            if (spec.type !== 'version' && spec.type !== 'range')
                return '';
            const range = dependencies[depName];
            const pkgs = R.values(pkgMap).filter(pkg => pkg.manifest.name === depName);
            if (!pkgs.length)
                return '';
            const versions = pkgs.map(pkg => pkg.manifest.version);
            if (versions.indexOf(range) !== -1) {
                const matchedPkg = pkgs.find(pkg => pkg.manifest.name === depName && pkg.manifest.version === range);
                return matchedPkg.path;
            }
            const matched = semver.maxSatisfying(versions, range);
            if (!matched) {
                unmatched.push({ pkgName: depName, range });
                return '';
            }
            const matchedPkg = pkgs.find(pkg => pkg.manifest.name === depName && pkg.manifest.version === matched);
            return matchedPkg.path;
        })
            .filter(Boolean);
    }
}
exports.default = default_1;
function createPkgMap(pkgs) {
    const pkgMap = {};
    for (let pkg of pkgs) {
        pkgMap[pkg.path] = pkg;
    }
    return pkgMap;
}
//# sourceMappingURL=index.js.map