How to Use CodeGraph as a Library in Node.js Applications
Yes, CodeGraph ships as the npm package @colbymchenry/codegraph and exposes a complete programmatic API through the CodeGraph class in src/index.ts, allowing you to embed repository indexing, semantic graph queries, and AI context generation directly into any Node.js application.
CodeGraph transforms static code analysis into a queryable local database that can be manipulated programmatically. By importing the library into your own projects, you gain access to AST extraction, reference resolution, and graph traversal capabilities without requiring external services or CLI subprocesses.
Installation and Requirements
Install the package from npm to begin integrating CodeGraph into your application.
npm install @colbymchenry/codegraph
CodeGraph requires Node.js version 18 or higher. The library ships with zero runtime dependencies beyond the optional native SQLite driver (better-sqlite3); if the native module is unavailable, it automatically falls back to a WebAssembly implementation. Everything runs locally—no external services or cloud APIs are required.
Core API Lifecycle
The CodeGraph class defined in src/index.ts provides a high-level façade over the entire codebase analysis pipeline. Understanding these lifecycle methods allows you to control when projects are initialized, indexed, queried, and torn down.
Initialize New Projects
Use the static CodeGraph.init method to create a new .codegraph directory, write default configuration, and set up the SQLite database. This method optionally runs an immediate index of the source files to populate the graph.
Implementation reference: src/index.ts, lines 85‑119.
Open Existing Projects
The static CodeGraph.open method loads an existing project, verifies the directory structure, and optionally performs an incremental sync to update the graph with recent file changes.
Implementation reference: src/index.ts, lines 149‑185.
Index and Synchronize
After initialization or opening, the indexAll, sync, and resolveReferences methods run the AST extraction pipeline using tree-sitter, store nodes and edges in SQLite, and resolve cross-file references including imports and framework-specific patterns.
Implementation reference: src/index.ts, lines 71‑131 and 371‑438.
Graph Queries
Once indexed, query the semantic graph using methods like searchNodes, getCallers, getCallGraph, and getImpactRadius to find symbols, traverse relationships, and compute dependency metrics.
Implementation reference: src/index.ts, lines 525‑750.
Context Building
The buildContext and findRelevantContext methods generate AI-friendly context packages containing code snippets and surrounding graph data for specific tasks.
Implementation reference: src/index.ts, lines 822‑904.
File Watching
Enable automatic synchronization with watch, which monitors the file system for changes and triggers incremental updates. Use unwatch to stop monitoring.
Implementation reference: src/index.ts, lines 513‑539.
Resource Cleanup
Call close to release database connections and file locks, or uninitialize to completely remove the .codegraph directory and associated resources.
Implementation reference: src/index.ts, lines 260‑282 and 771‑785.
Implementation Examples
The following examples demonstrate typical usage patterns after installing the package.
Initialize and Index a New Project
Create a CodeGraph project with configuration options and immediate indexing.
import CodeGraph from '@colbymchenry/codegraph';
const projectRoot = '/path/to/your/project';
(async () => {
const cg = await CodeGraph.init(projectRoot, {
config: { languages: ['typescript', 'javascript'] },
index: true,
onProgress: (p) => console.log(`${p.phase}: ${p.current}/${p.total}`),
});
console.log('Initialized CodeGraph with', cg.getStats().nodeCount, 'nodes');
await cg.close();
})();
Implementation reference: CodeGraph.init in src/index.ts, lines 85‑119.
Query Callers and Symbols
Open an existing project and search for specific symbols to analyze dependencies.
import CodeGraph from '@colbymchenry/codegraph';
(async () => {
const cg = await CodeGraph.open('/path/to/your/project', { sync: true });
const results = cg.searchNodes('UserService');
console.log('Found', results.length, 'matches');
if (results.length) {
const callers = cg.getCallers(results[0].node.id);
console.log('Callers:', callers.map(c => c.node.name));
}
await cg.close();
})();
Implementation reference: searchNodes and getCallers in src/index.ts, lines 525‑545.
Generate AI Context
Build task-oriented context for AI assistants with relevant code snippets and graph relationships.
import CodeGraph from '@colbymchenry/codegraph';
(async () => {
const cg = await CodeGraph.open('/path/to/project');
const ctx = await cg.buildContext(
{ title: 'Fix login bug', description: 'Users cannot log in after recent refactor' },
{ maxNodes: 25, includeCode: true, format: 'markdown' }
);
console.log('Generated context:\n', ctx);
await cg.close();
})();
Implementation reference: buildContext in src/index.ts, lines 822‑904.
Enable File Watching
Set up automatic synchronization when files change.
import CodeGraph from '@colbymchenry/codegraph';
(async () => {
const cg = await CodeGraph.open('/path/to/project');
cg.watch({ debounceMs: 2000 });
// Later, to stop watching:
// cg.unwatch();
})();
Implementation reference: watch and unwatch in src/index.ts, lines 513‑539.
Architecture and Key Source Files
The modular architecture allows you to use individual subsystems or the complete CodeGraph façade. Key files include:
src/index.ts– The public API exposing theCodeGraphclass and high-level methods.src/types.ts– Core TypeScript interfaces includingNode,Edge, andSearchResult.src/extraction/– Tree-sitter based AST parsing and node/edge extraction.src/resolution/– Cross-file reference resolution and framework pattern detection.src/graph/– SQLite schema, storage, and graph traversal algorithms.src/context/– Context building for AI tasks using semantic search and graph expansion.src/sync/– Incremental synchronization logic and file-system watching.src/db/– Database connection management with native and WASM backend selection.src/config.ts– Configuration handling for languages and exclusion patterns.
All heavy lifting occurs internally within these modules, exposing only high-level methods to consuming applications.
Summary
- CodeGraph is distributed as the npm package
@colbymchenry/codegraphand can be imported like any standard Node.js library. - The
CodeGraphclass insrc/index.tsprovides static methods for initialization (init) and opening existing projects (open), plus instance methods for querying and context building. - All processing runs locally in SQLite with no external service dependencies, supporting Node.js 18+.
- The API covers the full lifecycle: project setup, AST extraction, graph storage, reference resolution, semantic querying, AI context generation, and file watching.
- Source files are modular, allowing advanced users to import individual subsystems from
src/extraction/,src/resolution/, orsrc/graph/if needed.
Frequently Asked Questions
What versions of Node.js does CodeGraph support?
CodeGraph requires Node.js 18 or higher. The library uses modern Node.js APIs and ships with bundled WASM parsers, ensuring compatibility across supported LTS versions without additional runtime dependencies.
Can I use CodeGraph subsystems independently without the full class?
Yes. While the CodeGraph class in src/index.ts provides a convenient all-in-one façade, the codebase is architected into distinct layers. You can import specific modules from src/extraction/ for AST parsing, src/resolution/ for reference analysis, or src/graph/ for direct database access, though this requires deeper familiarity with the internal APIs.
Does CodeGraph require any external databases or cloud services?
No. CodeGraph is self-contained and stores all graph data in a local SQLite database within the .codegraph directory. It uses better-sqlite3 when available for performance, falling back to a WASM implementation otherwise. No network calls or external APIs are required for operation.
How does the file watcher impact system performance?
The watch method, implemented in src/index.ts lines 513‑539, uses debounced file-system monitoring (configurable via debounceMs, defaulting to 2000ms) to batch rapid changes and avoid excessive re-indexing. It performs incremental syncs rather than full rebuilds, minimizing CPU and I/O overhead during active development.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →