UNPKG

counterfact

Version:

a library for building a fake REST API for testing

51 lines (50 loc) 1.52 kB
import { dirname, resolve } from "node:path"; import precinct from "precinct"; export class ModuleDependencyGraph { dependents = new Map(); loadDependencies(path) { try { return precinct.paperwork(path); } catch { return []; } } clearDependents(path) { this.dependents.forEach((group) => { group.delete(path); }); } load(path) { this.clearDependents(path); for (const dependency of this.loadDependencies(path)) { if (!dependency.startsWith(".")) { return; } const key = resolve(dirname(path), dependency); if (!this.dependents.has(key)) { this.dependents.set(key, new Set()); } this.dependents.get(key)?.add(path); } } dependentsOf(path) { const marked = new Set(); const dependents = new Set(); const queue = [path]; while (queue.length > 0) { const file = queue.shift(); if (file !== undefined && !marked.has(file)) { marked.add(file); const fileDependents = this.dependents.get(file); if (fileDependents) { for (const dependent of fileDependents) { dependents.add(dependent); queue.push(dependent); } } } } return dependents; } }