UNPKG

2.42 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.DepGraphBuilder = void 0;
4const graphlib = require("../graphlib");
5const dep_graph_1 = require("./dep-graph");
6const validate_graph_1 = require("./validate-graph");
7class DepGraphBuilder {
8 constructor(pkgManager, rootPkg) {
9 this._pkgs = {};
10 this._pkgNodes = {};
11 const graph = new graphlib.Graph({
12 directed: true,
13 multigraph: false,
14 compound: false,
15 });
16 if (!rootPkg) {
17 rootPkg = {
18 name: '_root',
19 version: '0.0.0',
20 };
21 }
22 this._rootNodeId = 'root-node';
23 this._rootPkgId = DepGraphBuilder._getPkgId(rootPkg);
24 this._pkgs[this._rootPkgId] = rootPkg;
25 graph.setNode(this._rootNodeId, { pkgId: this._rootPkgId });
26 this._pkgNodes[this._rootPkgId] = new Set([this._rootNodeId]);
27 this._graph = graph;
28 this._pkgManager = pkgManager;
29 }
30 get rootNodeId() {
31 return this._rootNodeId;
32 }
33 static _getPkgId(pkg) {
34 return `${pkg.name}@${pkg.version || ''}`;
35 }
36 getPkgs() {
37 return Object.values(this._pkgs);
38 }
39 // TODO: this can create disconnected nodes
40 addPkgNode(pkgInfo, nodeId, nodeInfo) {
41 if (nodeId === this._rootNodeId) {
42 throw new Error('DepGraphBuilder.addPkgNode() cant override root node');
43 }
44 (0, validate_graph_1.validatePackageURL)(pkgInfo);
45 const pkgId = DepGraphBuilder._getPkgId(pkgInfo);
46 this._pkgs[pkgId] = pkgInfo;
47 this._pkgNodes[pkgId] = this._pkgNodes[pkgId] || new Set();
48 this._pkgNodes[pkgId].add(nodeId);
49 this._graph.setNode(nodeId, { pkgId, info: nodeInfo });
50 return this;
51 }
52 // TODO: this can create cycles
53 connectDep(parentNodeId, depNodeId) {
54 if (!this._graph.hasNode(parentNodeId)) {
55 throw new Error('parentNodeId does not exist');
56 }
57 if (!this._graph.hasNode(depNodeId)) {
58 throw new Error('depNodeId does not exist');
59 }
60 this._graph.setEdge(parentNodeId, depNodeId);
61 return this;
62 }
63 build() {
64 return new dep_graph_1.DepGraphImpl(this._graph, this._rootNodeId, this._pkgs, this._pkgNodes, this._pkgManager);
65 }
66}
67exports.DepGraphBuilder = DepGraphBuilder;
68//# sourceMappingURL=builder.js.map
\No newline at end of file