"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const build_modules_1 = __importDefault(require("@pnpm/build-modules"));
const constants_1 = require("@pnpm/constants");
const core_loggers_1 = require("@pnpm/core-loggers");
const error_1 = __importDefault(require("@pnpm/error"));
const filter_lockfile_1 = require("@pnpm/filter-lockfile");
const hoist_1 = __importDefault(require("@pnpm/hoist"));
const lifecycle_1 = require("@pnpm/lifecycle");
const link_bins_1 = __importStar(require("@pnpm/link-bins"));
const lockfile_file_1 = require("@pnpm/lockfile-file");
const lockfile_to_pnp_1 = require("@pnpm/lockfile-to-pnp");
const lockfile_utils_1 = require("@pnpm/lockfile-utils");
const logger_1 = __importStar(require("@pnpm/logger"));
const modules_cleaner_1 = require("@pnpm/modules-cleaner");
const modules_yaml_1 = require("@pnpm/modules-yaml");
const pkgid_to_filename_1 = __importDefault(require("@pnpm/pkgid-to-filename"));
const read_package_json_1 = require("@pnpm/read-package-json");
const read_project_manifest_1 = require("@pnpm/read-project-manifest");
const symlink_dependency_1 = __importStar(require("@pnpm/symlink-dependency"));
const path = require("path");
const dp = require("dependency-path");
const fs = require("mz/fs");
const pLimit = require("p-limit");
const pathAbsolute = require("path-absolute");
const R = require("ramda");
const realpathMissing = require("realpath-missing");
const brokenModulesLogger = logger_1.default('_broken_node_modules');
exports.default = async (opts) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    const reporter = opts.reporter;
    if (reporter && typeof reporter === 'function') {
        logger_1.streamParser.on('data', reporter);
    }
    const lockfileDir = opts.lockfileDir;
    const wantedLockfile = (_a = opts.wantedLockfile) !== null && _a !== void 0 ? _a : await lockfile_file_1.readWantedLockfile(lockfileDir, { ignoreIncompatible: false });
    if (!wantedLockfile) {
        throw new Error(`Headless installation requires a ${constants_1.WANTED_LOCKFILE} file`);
    }
    const relativeModulesDir = (_b = opts.modulesDir) !== null && _b !== void 0 ? _b : 'node_modules';
    const rootModulesDir = await realpathMissing(path.join(lockfileDir, relativeModulesDir));
    const virtualStoreDir = pathAbsolute((_c = opts.virtualStoreDir) !== null && _c !== void 0 ? _c : path.join(relativeModulesDir, '.pnpm'), lockfileDir);
    const currentLockfile = (_d = opts.currentLockfile) !== null && _d !== void 0 ? _d : await lockfile_file_1.readCurrentLockfile(virtualStoreDir, { ignoreIncompatible: false });
    const hoistedModulesDir = path.join(virtualStoreDir, 'node_modules');
    const publicHoistedModulesDir = rootModulesDir;
    for (const { id, manifest, rootDir } of opts.projects) {
        if (!lockfile_utils_1.satisfiesPackageManifest(wantedLockfile, manifest, id)) {
            throw new error_1.default('OUTDATED_LOCKFILE', `Cannot install with "frozen-lockfile" because ${constants_1.WANTED_LOCKFILE} is not up-to-date with ` +
                path.relative(lockfileDir, path.join(rootDir, 'package.json')));
        }
    }
    const scriptsOpts = {
        optional: false,
        rawConfig: opts.rawConfig,
        scriptShell: opts.scriptShell,
        shellEmulator: opts.shellEmulator,
        stdio: (_e = opts.ownLifecycleHooksStdio) !== null && _e !== void 0 ? _e : 'inherit',
        unsafePerm: opts.unsafePerm || false,
    };
    if (!opts.ignoreScripts) {
        await lifecycle_1.runLifecycleHooksConcurrently(['preinstall'], opts.projects, (_f = opts.childConcurrency) !== null && _f !== void 0 ? _f : 5, scriptsOpts);
    }
    const skipped = opts.skipped || new Set();
    if (currentLockfile) {
        await modules_cleaner_1.prune(opts.projects, {
            currentLockfile,
            dryRun: false,
            hoistedDependencies: opts.hoistedDependencies,
            hoistedModulesDir: (_g = (opts.hoistPattern && hoistedModulesDir)) !== null && _g !== void 0 ? _g : undefined,
            include: opts.include,
            lockfileDir,
            pruneStore: opts.pruneStore,
            publicHoistedModulesDir: (_h = (opts.publicHoistPattern && publicHoistedModulesDir)) !== null && _h !== void 0 ? _h : undefined,
            registries: opts.registries,
            skipped,
            storeController: opts.storeController,
            virtualStoreDir,
            wantedLockfile,
        });
    }
    else {
        core_loggers_1.statsLogger.debug({
            prefix: lockfileDir,
            removed: 0,
        });
    }
    core_loggers_1.stageLogger.debug({
        prefix: lockfileDir,
        stage: 'importing_started',
    });
    const filterOpts = {
        include: opts.include,
        registries: opts.registries,
        skipped,
    };
    const filteredLockfile = filter_lockfile_1.filterLockfileByImportersAndEngine(wantedLockfile, opts.projects.map(({ id }) => id), {
        ...filterOpts,
        currentEngine: opts.currentEngine,
        engineStrict: opts.engineStrict,
        failOnMissingDependencies: true,
        includeIncompatiblePackages: opts.force,
        lockfileDir,
    });
    const { directDependenciesByImporterId, graph } = await lockfileToDepGraph(filteredLockfile, opts.force ? null : currentLockfile, {
        ...opts,
        importerIds: opts.projects.map(({ id }) => id),
        lockfileDir,
        skipped,
        virtualStoreDir,
    });
    if (opts.enablePnp) {
        const importerNames = R.fromPairs(opts.projects.map(({ manifest, id }) => { var _a; return [id, (_a = manifest.name) !== null && _a !== void 0 ? _a : id]; }));
        await lockfile_to_pnp_1.writePnpFile(filteredLockfile, {
            importerNames,
            lockfileDir,
            virtualStoreDir,
            registries: opts.registries,
        });
    }
    const depNodes = R.values(graph);
    core_loggers_1.statsLogger.debug({
        added: depNodes.length,
        prefix: lockfileDir,
    });
    await Promise.all(depNodes.map((depNode) => fs.mkdir(depNode.modules, { recursive: true })));
    await Promise.all([
        opts.symlink === false
            ? Promise.resolve()
            : linkAllModules(depNodes, {
                lockfileDir,
                optional: opts.include.optionalDependencies,
            }),
        linkAllPkgs(opts.storeController, depNodes, {
            force: opts.force,
            lockfileDir: opts.lockfileDir,
            targetEngine: opts.sideEffectsCacheRead && constants_1.ENGINE_NAME || undefined,
        }),
    ]);
    core_loggers_1.stageLogger.debug({
        prefix: lockfileDir,
        stage: 'importing_done',
    });
    function warn(message) {
        logger_1.default.info({
            message,
            prefix: lockfileDir,
        });
    }
    let newHoistedDependencies;
    if (opts.hoistPattern != null || opts.publicHoistPattern != null) {
        newHoistedDependencies = await hoist_1.default({
            lockfile: filteredLockfile,
            lockfileDir,
            privateHoistedModulesDir: hoistedModulesDir,
            privateHoistPattern: (_j = opts.hoistPattern) !== null && _j !== void 0 ? _j : [],
            publicHoistedModulesDir,
            publicHoistPattern: (_k = opts.publicHoistPattern) !== null && _k !== void 0 ? _k : [],
            virtualStoreDir,
        });
    }
    else {
        newHoistedDependencies = {};
    }
    await Promise.all(opts.projects.map(async ({ rootDir, id, manifest, modulesDir }) => {
        if (opts.symlink !== false) {
            await linkRootPackages(filteredLockfile, {
                importerId: id,
                importerModulesDir: modulesDir,
                lockfileDir,
                projectDir: rootDir,
                projects: opts.projects,
                registries: opts.registries,
                rootDependencies: directDependenciesByImporterId[id],
            });
        }
        // Even though headless installation will never update the package.json
        // this needs to be logged because otherwise install summary won't be printed
        core_loggers_1.packageManifestLogger.debug({
            prefix: rootDir,
            updated: manifest,
        });
    }));
    if (opts.ignoreScripts) {
        for (const { id, manifest } of opts.projects) {
            if (opts.ignoreScripts && (manifest === null || manifest === void 0 ? void 0 : manifest.scripts) &&
                ((_p = (_o = (_m = (_l = manifest.scripts.preinstall) !== null && _l !== void 0 ? _l : manifest.scripts.prepublish) !== null && _m !== void 0 ? _m : manifest.scripts.install) !== null && _o !== void 0 ? _o : manifest.scripts.postinstall) !== null && _p !== void 0 ? _p : manifest.scripts.prepare)) {
                opts.pendingBuilds.push(id);
            }
        }
        // we can use concat here because we always only append new packages, which are guaranteed to not be there by definition
        opts.pendingBuilds = opts.pendingBuilds
            .concat(depNodes
            .filter(({ requiresBuild }) => requiresBuild)
            .map(({ depPath }) => depPath));
    }
    else {
        const directNodes = new Set();
        for (const { id } of opts.projects) {
            R
                .values(directDependenciesByImporterId[id])
                .filter((loc) => graph[loc])
                .forEach((loc) => {
                directNodes.add(loc);
            });
        }
        const extraBinPaths = [...(_q = opts.extraBinPaths) !== null && _q !== void 0 ? _q : []];
        if (opts.hoistPattern) {
            extraBinPaths.unshift(path.join(virtualStoreDir, 'node_modules/.bin'));
        }
        let extraEnv;
        if (opts.enablePnp) {
            extraEnv = lifecycle_1.makeNodeRequireOption(path.join(opts.lockfileDir, '.pnp.js'));
        }
        await build_modules_1.default(graph, Array.from(directNodes), {
            childConcurrency: opts.childConcurrency,
            extraBinPaths,
            extraEnv,
            lockfileDir,
            optional: opts.include.optionalDependencies,
            rawConfig: opts.rawConfig,
            rootModulesDir: virtualStoreDir,
            scriptShell: opts.scriptShell,
            shellEmulator: opts.shellEmulator,
            sideEffectsCacheWrite: opts.sideEffectsCacheWrite,
            storeController: opts.storeController,
            unsafePerm: opts.unsafePerm,
            userAgent: opts.userAgent,
        });
    }
    await linkAllBins(graph, { optional: opts.include.optionalDependencies, warn });
    await Promise.all(opts.projects.map(async (project) => {
        var _a;
        if (((_a = opts.publicHoistPattern) === null || _a === void 0 ? void 0 : _a.length) && path.relative(opts.lockfileDir, project.rootDir) === '') {
            await linkBinsOfImporter(project);
        }
        else {
            const directPkgDirs = Object.values(directDependenciesByImporterId[project.id]);
            await link_bins_1.linkBinsOfPackages((await Promise.all(directPkgDirs.map(async (dir) => ({
                location: dir,
                manifest: await read_project_manifest_1.safeReadProjectManifestOnly(dir),
            }))))
                .filter(({ manifest }) => manifest != null), project.binsDir, { warn: (message) => logger_1.default.info({ message, prefix: project.rootDir }) });
        }
    }));
    if (currentLockfile && !R.equals(opts.projects.map(({ id }) => id).sort(), Object.keys(filteredLockfile.importers).sort())) {
        Object.assign(filteredLockfile.packages, currentLockfile.packages);
    }
    await lockfile_file_1.writeCurrentLockfile(virtualStoreDir, filteredLockfile);
    await modules_yaml_1.write(rootModulesDir, {
        hoistedDependencies: newHoistedDependencies,
        hoistPattern: opts.hoistPattern,
        included: opts.include,
        layoutVersion: constants_1.LAYOUT_VERSION,
        packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`,
        pendingBuilds: opts.pendingBuilds,
        publicHoistPattern: opts.publicHoistPattern,
        registries: opts.registries,
        skipped: Array.from(skipped),
        storeDir: opts.storeDir,
        virtualStoreDir,
    });
    // waiting till package requests are finished
    await Promise.all(depNodes.map(({ finishing }) => finishing));
    core_loggers_1.summaryLogger.debug({ prefix: lockfileDir });
    await opts.storeController.close();
    if (!opts.ignoreScripts) {
        await lifecycle_1.runLifecycleHooksConcurrently(['install', 'postinstall', 'prepublish', 'prepare'], opts.projects, (_r = opts.childConcurrency) !== null && _r !== void 0 ? _r : 5, scriptsOpts);
    }
    if (reporter && typeof reporter === 'function') {
        logger_1.streamParser.removeListener('data', reporter);
    }
};
function linkBinsOfImporter({ modulesDir, binsDir, rootDir }) {
    const warn = (message) => logger_1.default.info({ message, prefix: rootDir });
    return link_bins_1.default(modulesDir, binsDir, {
        allowExoticManifests: true,
        warn,
    });
}
function linkRootPackages(lockfile, opts) {
    const importerManifestsByImporterId = {};
    for (const { id, manifest } of opts.projects) {
        importerManifestsByImporterId[id] = manifest;
    }
    const projectSnapshot = lockfile.importers[opts.importerId];
    const allDeps = {
        ...projectSnapshot.devDependencies,
        ...projectSnapshot.dependencies,
        ...projectSnapshot.optionalDependencies,
    };
    return Promise.all(Object.keys(allDeps)
        .map(async (alias) => {
        var _a, _b, _c, _d, _e, _f, _g;
        if (allDeps[alias].startsWith('link:')) {
            const isDev = Boolean((_a = projectSnapshot.devDependencies) === null || _a === void 0 ? void 0 : _a[alias]);
            const isOptional = Boolean((_b = projectSnapshot.optionalDependencies) === null || _b === void 0 ? void 0 : _b[alias]);
            const packageDir = path.join(opts.projectDir, allDeps[alias].substr(5));
            const linkedPackage = await (async () => {
                const importerId = lockfile_file_1.getLockfileImporterId(opts.lockfileDir, packageDir);
                if (importerManifestsByImporterId[importerId]) {
                    return importerManifestsByImporterId[importerId];
                }
                // TODO: cover this case with a test
                return await read_project_manifest_1.readProjectManifestOnly(packageDir);
            })();
            await symlink_dependency_1.symlinkDirectRootDependency(packageDir, opts.importerModulesDir, alias, {
                fromDependenciesField: isDev && 'devDependencies' ||
                    isOptional && 'optionalDependencies' ||
                    'dependencies',
                linkedPackage,
                prefix: opts.projectDir,
            });
            return;
        }
        const dir = opts.rootDependencies[alias];
        // Skipping linked packages
        if (!dir) {
            return;
        }
        if ((await symlink_dependency_1.default(dir, opts.importerModulesDir, alias)).reused) {
            return;
        }
        const isDev = Boolean((_c = projectSnapshot.devDependencies) === null || _c === void 0 ? void 0 : _c[alias]);
        const isOptional = Boolean((_d = projectSnapshot.optionalDependencies) === null || _d === void 0 ? void 0 : _d[alias]);
        const depPath = dp.refToRelative(allDeps[alias], alias);
        if (depPath === null)
            return;
        const pkgSnapshot = (_e = lockfile.packages) === null || _e === void 0 ? void 0 : _e[depPath];
        if (!pkgSnapshot)
            return; // this won't ever happen. Just making typescript happy
        const pkgId = (_g = (_f = pkgSnapshot.id) !== null && _f !== void 0 ? _f : dp.refToAbsolute(allDeps[alias], alias, opts.registries)) !== null && _g !== void 0 ? _g : undefined;
        const pkgInfo = lockfile_utils_1.nameVerFromPkgSnapshot(depPath, pkgSnapshot);
        core_loggers_1.rootLogger.debug({
            added: {
                dependencyType: isDev && 'dev' || isOptional && 'optional' || 'prod',
                id: pkgId,
                // latest: opts.outdatedPkgs[pkg.id],
                name: alias,
                realName: pkgInfo.name,
                version: pkgInfo.version,
            },
            prefix: opts.projectDir,
        });
    }));
}
async function lockfileToDepGraph(lockfile, currentLockfile, opts) {
    var _a;
    const currentPackages = (_a = currentLockfile === null || currentLockfile === void 0 ? void 0 : currentLockfile.packages) !== null && _a !== void 0 ? _a : {};
    const graph = {};
    const directDependenciesByImporterId = {};
    if (lockfile.packages) {
        const pkgSnapshotByLocation = {};
        await Promise.all(Object.keys(lockfile.packages).map(async (depPath) => {
            if (opts.skipped.has(depPath))
                return;
            const pkgSnapshot = lockfile.packages[depPath];
            // TODO: optimize. This info can be already returned by pkgSnapshotToResolution()
            const pkgName = lockfile_utils_1.nameVerFromPkgSnapshot(depPath, pkgSnapshot).name;
            const modules = path.join(opts.virtualStoreDir, pkgid_to_filename_1.default(depPath, opts.lockfileDir), 'node_modules');
            const packageId = lockfile_utils_1.packageIdFromSnapshot(depPath, pkgSnapshot, opts.registries);
            const dir = path.join(modules, pkgName);
            if (currentPackages[depPath] && R.equals(currentPackages[depPath].dependencies, lockfile.packages[depPath].dependencies) &&
                R.equals(currentPackages[depPath].optionalDependencies, lockfile.packages[depPath].optionalDependencies)) {
                if (await fs.exists(dir)) {
                    return;
                }
                brokenModulesLogger.debug({
                    missing: dir,
                });
            }
            const resolution = lockfile_utils_1.pkgSnapshotToResolution(depPath, pkgSnapshot, opts.registries);
            core_loggers_1.progressLogger.debug({
                packageId,
                requester: opts.lockfileDir,
                status: 'resolved',
            });
            let fetchResponse = opts.storeController.fetchPackage({
                force: false,
                lockfileDir: opts.lockfileDir,
                pkgId: packageId,
                resolution,
            });
            if (fetchResponse instanceof Promise)
                fetchResponse = await fetchResponse;
            fetchResponse.files() // eslint-disable-line
                .then(({ fromStore }) => {
                core_loggers_1.progressLogger.debug({
                    packageId,
                    requester: opts.lockfileDir,
                    status: fromStore
                        ? 'found_in_store' : 'fetched',
                });
            })
                .catch(() => {
                // ignore
            });
            graph[dir] = {
                children: {},
                depPath,
                dir,
                fetchingFiles: fetchResponse.files,
                filesIndexFile: fetchResponse.filesIndexFile,
                finishing: fetchResponse.finishing,
                hasBin: pkgSnapshot.hasBin === true,
                hasBundledDependencies: !!pkgSnapshot.bundledDependencies,
                modules,
                name: pkgName,
                optional: !!pkgSnapshot.optional,
                optionalDependencies: new Set(R.keys(pkgSnapshot.optionalDependencies)),
                prepare: pkgSnapshot.prepare === true,
                requiresBuild: pkgSnapshot.requiresBuild === true,
            };
            pkgSnapshotByLocation[dir] = pkgSnapshot;
        }));
        const ctx = {
            force: opts.force,
            graph,
            lockfileDir: opts.lockfileDir,
            pkgSnapshotsByDepPaths: lockfile.packages,
            registries: opts.registries,
            sideEffectsCacheRead: opts.sideEffectsCacheRead,
            skipped: opts.skipped,
            storeController: opts.storeController,
            storeDir: opts.storeDir,
            virtualStoreDir: opts.virtualStoreDir,
        };
        for (const dir of R.keys(graph)) {
            const pkgSnapshot = pkgSnapshotByLocation[dir];
            const allDeps = {
                ...pkgSnapshot.dependencies,
                ...(opts.include.optionalDependencies ? pkgSnapshot.optionalDependencies : {}),
            };
            const peerDeps = pkgSnapshot.peerDependencies ? new Set(Object.keys(pkgSnapshot.peerDependencies)) : null;
            graph[dir].children = await getChildrenPaths(ctx, allDeps, peerDeps, '.');
        }
        for (const importerId of opts.importerIds) {
            const projectSnapshot = lockfile.importers[importerId];
            const rootDeps = {
                ...(opts.include.devDependencies ? projectSnapshot.devDependencies : {}),
                ...(opts.include.dependencies ? projectSnapshot.dependencies : {}),
                ...(opts.include.optionalDependencies ? projectSnapshot.optionalDependencies : {}),
            };
            directDependenciesByImporterId[importerId] = await getChildrenPaths(ctx, rootDeps, null, importerId);
        }
    }
    return { graph, directDependenciesByImporterId };
}
async function getChildrenPaths(ctx, allDeps, peerDeps, importerId) {
    const children = {};
    for (const alias of Object.keys(allDeps)) {
        const childDepPath = dp.refToAbsolute(allDeps[alias], alias, ctx.registries);
        if (childDepPath === null) {
            children[alias] = path.resolve(ctx.lockfileDir, importerId, allDeps[alias].substr(5));
            continue;
        }
        const childRelDepPath = dp.refToRelative(allDeps[alias], alias);
        const childPkgSnapshot = ctx.pkgSnapshotsByDepPaths[childRelDepPath];
        if (ctx.graph[childRelDepPath]) {
            children[alias] = ctx.graph[childRelDepPath].dir;
        }
        else if (childPkgSnapshot) {
            const pkgName = lockfile_utils_1.nameVerFromPkgSnapshot(childRelDepPath, childPkgSnapshot).name;
            children[alias] = path.join(ctx.virtualStoreDir, pkgid_to_filename_1.default(childRelDepPath, ctx.lockfileDir), 'node_modules', pkgName);
        }
        else if (allDeps[alias].indexOf('file:') === 0) {
            children[alias] = path.resolve(ctx.lockfileDir, allDeps[alias].substr(5));
        }
        else if (!ctx.skipped.has(childRelDepPath) && (!peerDeps || !peerDeps.has(alias))) {
            throw new Error(`${childRelDepPath} not found in ${constants_1.WANTED_LOCKFILE}`);
        }
    }
    return children;
}
const limitLinking = pLimit(16);
function linkAllPkgs(storeController, depNodes, opts) {
    return Promise.all(depNodes.map(async (depNode) => {
        const filesResponse = await depNode.fetchingFiles();
        const { importMethod, isBuilt } = await storeController.importPackage(depNode.dir, {
            filesResponse,
            force: opts.force,
            targetEngine: opts.targetEngine,
        });
        if (importMethod) {
            core_loggers_1.progressLogger.debug({
                method: importMethod,
                requester: opts.lockfileDir,
                status: 'imported',
                to: depNode.dir,
            });
        }
        depNode.isBuilt = isBuilt;
    }));
}
function linkAllBins(depGraph, opts) {
    return Promise.all(R.values(depGraph)
        .map((depNode) => limitLinking(async () => {
        const childrenToLink = opts.optional
            ? depNode.children
            : Object.keys(depNode.children)
                .reduce((nonOptionalChildren, childAlias) => {
                if (!depNode.optionalDependencies.has(childAlias)) {
                    nonOptionalChildren[childAlias] = depNode.children[childAlias];
                }
                return nonOptionalChildren;
            }, {});
        const binPath = path.join(depNode.dir, 'node_modules/.bin');
        const pkgSnapshots = R.props(R.values(childrenToLink), depGraph);
        if (pkgSnapshots.includes(undefined)) { // eslint-disable-line
            await link_bins_1.default(depNode.modules, binPath, { warn: opts.warn });
        }
        else {
            const pkgs = await Promise.all(pkgSnapshots
                .filter(({ hasBin }) => hasBin)
                .map(async ({ dir }) => ({
                location: dir,
                manifest: await read_package_json_1.fromDir(dir),
            })));
            await link_bins_1.linkBinsOfPackages(pkgs, binPath, { warn: opts.warn });
        }
        // link also the bundled dependencies` bins
        if (depNode.hasBundledDependencies) {
            const bundledModules = path.join(depNode.dir, 'node_modules');
            await link_bins_1.default(bundledModules, binPath, { warn: opts.warn });
        }
    })));
}
async function linkAllModules(depNodes, opts) {
    await Promise.all(depNodes
        .map(async (depNode) => {
        const childrenToLink = opts.optional
            ? depNode.children
            : Object.keys(depNode.children)
                .reduce((nonOptionalChildren, childAlias) => {
                if (!depNode.optionalDependencies.has(childAlias)) {
                    nonOptionalChildren[childAlias] = depNode.children[childAlias];
                }
                return nonOptionalChildren;
            }, {});
        await Promise.all(Object.keys(childrenToLink)
            .map(async (alias) => {
            // if (!pkg.installable && pkg.optional) return
            if (alias === depNode.name) {
                logger_1.default.warn({
                    message: `Cannot link dependency with name ${alias} to ${depNode.modules}. Dependency's name should differ from the parent's name.`,
                    prefix: opts.lockfileDir,
                });
                return;
            }
            await limitLinking(() => symlink_dependency_1.default(childrenToLink[alias], depNode.modules, alias));
        }));
    }));
}
//# sourceMappingURL=index.js.map