graph-store.js 4.79 KB
const { toPosix } = require("./path-utils");

function normalizeEvidence(evidence = {}) {
	return {
		path: toPosix(evidence.path || "unknown"),
		line: Number.isInteger(evidence.line) ? evidence.line : 1,
		column: Number.isInteger(evidence.column) ? evidence.column : 0,
	};
}

function compareSerialized(left, right) {
	return JSON.stringify(left).localeCompare(JSON.stringify(right), "en");
}

class GraphStore {
	constructor(domainCatalog) {
		this.nodes = new Map();
		this.edges = new Map();
		this.unresolved = new Map();
		this.domainCatalog = domainCatalog;
	}

	domainsForPath(filePath) {
		const normalized = toPosix(filePath);
		return this.domainCatalog.domains
			.filter(domain => [
				domain.routeModule,
				...(domain.roots || []),
				...(domain.entrypoints || []),
				...(domain.documents || []),
			].filter(Boolean).some((root) => {
				const normalizedRoot = toPosix(root).replace(/\/$/, "");
				return normalized === normalizedRoot || normalized.startsWith(`${normalizedRoot}/`);
			}))
			.map(domain => String(domain.id))
			.sort();
	}

	addNode(node) {
		if (!node || !node.id || !node.type) {
			throw new Error("Invalid graph node");
		}
		const normalized = {
			id: node.id,
			type: node.type,
			name: node.name || node.id,
		};
		if (node.path) {
			normalized.path = toPosix(node.path);
		}
		const domainIds = node.domainIds || (node.path ? this.domainsForPath(node.path) : []);
		if (domainIds.length) {
			normalized.domainIds = [...new Set(domainIds.map(String))].sort();
		}
		if (node.meta && Object.keys(node.meta).length) {
			normalized.meta = node.meta;
		}
		const previous = this.nodes.get(normalized.id);
		this.nodes.set(normalized.id, previous
			? {
					...previous,
					...normalized,
					domainIds: [...new Set([...(previous.domainIds || []), ...(normalized.domainIds || [])])].sort(),
				}
			: normalized);
		return normalized.id;
	}

	addEdge(edge) {
		if (!edge || !edge.from || !edge.to || !edge.type) {
			throw new Error("Invalid graph edge");
		}
		const normalized = {
			from: edge.from,
			to: edge.to,
			type: edge.type,
			confidence: typeof edge.confidence === "number" ? edge.confidence : 1,
			evidence: normalizeEvidence(edge.evidence),
		};
		const key = `${normalized.type}|${normalized.from}|${normalized.to}|${JSON.stringify(normalized.evidence)}`;
		this.edges.set(key, normalized);
	}

	addUnresolved(item) {
		const normalized = {
			kind: item.kind,
			path: toPosix(item.path),
			line: Number.isInteger(item.line) ? item.line : 1,
			column: Number.isInteger(item.column) ? item.column : 0,
			reason: item.reason,
			expressionKind: item.expressionKind || "Unknown",
		};
		const key = `${normalized.kind}|${normalized.path}|${normalized.line}|${normalized.column}|${normalized.reason}`;
		this.unresolved.set(key, normalized);
	}

	propagateDomains() {
		const propagatingEdges = new Set([
			"contains",
			"renders",
			"declares",
			"calls",
			"usesComponent",
			"definesApi",
			"callsApi",
			"callsEndpoint",
			"readsState",
			"readsGetter",
			"dispatchesAction",
			"commitsMutation",
		]);
		let changed = true;
		while (changed) {
			changed = false;
			for (const edge of this.edges.values()) {
				if (!propagatingEdges.has(edge.type)) {
					continue;
				}
				const source = this.nodes.get(edge.from);
				const target = this.nodes.get(edge.to);
				if (edge.type === "calls" && (!source?.path || source.path !== target?.path)) {
					continue;
				}
				if (!source?.domainIds?.length || !target) {
					continue;
				}
				const merged = [...new Set([...(target.domainIds || []), ...source.domainIds])].sort();
				if (merged.length !== (target.domainIds || []).length) {
					target.domainIds = merged;
					changed = true;
				}
			}
		}
		for (const edge of this.edges.values()) {
			if (edge.type !== "coveredBy") {
				continue;
			}
			const source = this.nodes.get(edge.from);
			const target = this.nodes.get(edge.to);
			if (source?.domainIds?.length === 1 && target) {
				target.domainIds = [...new Set([...(target.domainIds || []), source.domainIds[0]])].sort();
			}
		}
	}

	toGraph() {
		this.propagateDomains();
		const nodes = [...this.nodes.values()].sort((left, right) => left.id.localeCompare(right.id, "en"));
		const edges = [...this.edges.values()].sort(compareSerialized);
		const unresolved = [...this.unresolved.values()].sort(compareSerialized);
		const nodeTypes = {};
		const edgeTypes = {};
		nodes.forEach((node) => {
			nodeTypes[node.type] = (nodeTypes[node.type] || 0) + 1;
		});
		edges.forEach((edge) => {
			edgeTypes[edge.type] = (edgeTypes[edge.type] || 0) + 1;
		});
		return {
			schemaVersion: "1.0.0",
			nodes,
			edges,
			unresolved,
			stats: {
				nodeCount: nodes.length,
				edgeCount: edges.length,
				unresolvedCount: unresolved.length,
				nodeTypes,
				edgeTypes,
			},
		};
	}
}

module.exports = {
	GraphStore,
	normalizeEvidence,
};