"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterNodesFromGraph = exports.filterPackagesFromGraph = void 0;
const builder_1 = require("./builder");
async function filterPackagesFromGraph(originalDepGraph, packagesToFilterOut) {
    if (!(packagesToFilterOut === null || packagesToFilterOut === void 0 ? void 0 : packagesToFilterOut.length))
        return originalDepGraph;
    const depGraph = originalDepGraph;
    const packages = depGraph
        .getDepPkgs()
        .filter((existingPkg) => packagesToFilterOut.some((pkgToFilter) => isString(pkgToFilter)
        ? existingPkg.name === pkgToFilter
        : existingPkg.name === pkgToFilter.name &&
            existingPkg.version === pkgToFilter.version));
    const nodeIdsToFilterOut = [];
    for (const pkg of packages) {
        const nodeIds = depGraph.getPkgNodeIds(pkg);
        for (const nodeId of nodeIds) {
            nodeIdsToFilterOut.push(nodeId);
        }
    }
    return filterNodesFromGraph(originalDepGraph, nodeIdsToFilterOut);
}
exports.filterPackagesFromGraph = filterPackagesFromGraph;
async function filterNodesFromGraph(originalDepGraph, nodeIdsToFilterOut) {
    if (!(nodeIdsToFilterOut === null || nodeIdsToFilterOut === void 0 ? void 0 : nodeIdsToFilterOut.length))
        return originalDepGraph;
    const depGraph = originalDepGraph;
    const existingNodeIds = new Set(depGraph['_graph'].nodes());
    nodeIdsToFilterOut = nodeIdsToFilterOut.filter((nodeId) => existingNodeIds.has(nodeId));
    if (nodeIdsToFilterOut.length === 0)
        return originalDepGraph;
    const depGraphBuilder = new builder_1.DepGraphBuilder(depGraph.pkgManager, depGraph.rootPkg);
    const nodeIdsToFilterOutSet = new Set(nodeIdsToFilterOut);
    const queue = [[depGraph.rootNodeId, undefined]];
    while (queue.length > 0) {
        const [nodeId, parentNodeId] = queue.pop();
        if (nodeIdsToFilterOutSet.has(nodeId))
            continue;
        if (parentNodeId) {
            const pkgInfo = depGraph.getNodePkg(nodeId);
            let nodeInfo = depGraph.getNode(nodeId);
            if (isEmpty(nodeInfo))
                nodeInfo = undefined;
            depGraphBuilder.addPkgNode(pkgInfo, nodeId, nodeInfo);
            depGraphBuilder.connectDep(parentNodeId, nodeId);
        }
        const dependencies = depGraph.getNodeDepsNodeIds(nodeId).slice().reverse();
        for (const depNodeId of dependencies) {
            queue.push([depNodeId, nodeId]);
        }
    }
    return depGraphBuilder.build();
}
exports.filterNodesFromGraph = filterNodesFromGraph;
function isString(pkgToFilter) {
    return typeof pkgToFilter === 'string';
}
function isEmpty(obj) {
    return !obj || Object.keys(obj).length === 0;
}
//# sourceMappingURL=filter-from-graph.js.map