aqua/api/api-npm/imports.js

46 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2023-12-06 10:50:48 +00:00
// @ts-check
import Arborist from "@npmcli/arborist";
import { breadth } from "treeverse";
export async function gatherImportsFromNpm(path) {
const arb = new Arborist({ path });
return await gatherImportsFromArborist(arb);
}
export async function gatherImportsFromArborist(arborist) {
const tree = await arborist.loadActual();
2023-12-06 10:56:59 +00:00
/**
* Traverse dependency tree to construct map
* (real path of a package) -> (real paths of its immediate dependencies)
*/
2023-12-06 10:50:48 +00:00
let result = new Map();
breadth({
tree,
getChildren(node, _) {
let deps = [];
for (let edge of node.edgesOut.values()) {
2023-12-06 10:56:59 +00:00
// Skip dependencies that are not installed.
2023-12-06 10:50:48 +00:00
if (edge.to === null) continue;
2023-12-06 10:56:59 +00:00
// NOTE: Any errors in edge are ignored.
2023-12-06 10:50:48 +00:00
const dep = edge.to;
2023-12-06 10:56:59 +00:00
// Gather dependencies to traverse them.
2023-12-06 10:50:48 +00:00
deps.push(dep);
2023-12-06 10:56:59 +00:00
// Gather dependencies real paths.
2023-12-06 10:50:48 +00:00
result.set(node.realpath, [
...(result.get(node.realpath) || []),
dep.realpath,
]);
}
2023-12-06 10:56:59 +00:00
2023-12-06 10:50:48 +00:00
return deps;
},
});
2023-12-06 10:56:59 +00:00
// Convert map to object.
2023-12-06 10:50:48 +00:00
return Object.fromEntries(result);
}