Skip to content

getComponents

Treats the graph as undirected and extracts its connected components. BFS groups nodes that are reachable from one another, returning “clusters” of documents.

Even in a large repository, documents often split into several independent clusters in practice. getComponents lets you see which document groups form a coherent context together and whether any isolated clusters exist.

It is also useful for finding orphan documents — components of size 1, where no document references them and they reference nothing (the GRP-003 rule detects this automatically).

function getComponents(graph: ContextGraph): string[][];
ParameterTypeRequiredDescription
graphContextGraphThe graph built by buildContextGraph.

Returns string[][]. Each component is an array of file paths sorted alphabetically. The components themselves are also sorted deterministically by their first file path.

import { buildContextGraph, getComponents, loadDocuments } from "@contextlint/core";
const documents = loadDocuments(["docs/**/*.md"]);
const graph = buildContextGraph(documents);
const components = getComponents(graph);
console.log(`Detected ${components.length} clusters`);
for (const [index, component] of components.entries()) {
console.log(`\nCluster ${index + 1}: ${component.length} files`);
for (const file of component) {
console.log(` - ${file}`);
}
}
// Extract orphan documents
const orphans = components.filter((c) => c.length === 1).flat();
console.log(`Orphan documents: ${orphans.length}`);