"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());
    });
};
const path = require('path');
const mkdirp_1 = require('../fs/mkdirp');
const symlinkToModules_1 = require('./symlinkToModules');
function createFlatTree(store, root, currentDepth, pkgs) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!pkgs.length)
            return;
        const modules = path.join(root, 'node_modules');
        yield mkdirp_1.default(modules);
        const flatDeps = flattenPkgs(pkgs);
        yield Promise.all(Object.keys(flatDeps)
            .filter(id => flatDeps[id].keypath.length > currentDepth)
            .map(function (id) {
            return __awaiter(this, void 0, void 0, function* () {
                const target = path.join(store, id, '_');
                yield symlinkToModules_1.default(target, modules);
                return createFlatTree(store, target, currentDepth + 1, flatDeps[id].dependencies);
            });
        }));
        return;
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = createFlatTree;
function flattenPkgs(pkgs = []) {
    if (!pkgs.length)
        return {};
    return pkgs.reduce((prev, pkg) => {
        if (prev[pkg.id])
            return prev;
        prev[pkg.id] = pkg;
        return Object.assign(prev, flattenPkgs(pkg.dependencies));
    }, {});
}
//# sourceMappingURL=createFlatTree.js.map