code-explainer
v2.1.2
Published
AI-Powered React Code Analyzer - Multi-level CLI tool for React components with security, quality, and maintainability insights
Maintainers
Readme
code-explainer
AI-Powered React Code Analyzer - Multi-level CLI tool for analyzing React components with security, quality, and maintainability insights.
Installation | Quick Start | Features | CLI Options | Configuration | API
Overview
code-explainer is a CLI tool that performs deep static analysis on React/TypeScript components. It combines AST-based code analysis with AI-powered explanations (via NVIDIA endpoints) to deliver actionable insights across three levels of depth.
What It Analyzes
| Category | Checks Performed |
|:---------|:-----------------|
| Security | Hardcoded secrets, unsafe API usage (eval, Function), XSS vulnerabilities, missing input validation, authentication gaps |
| Code Quality | Unused imports, dead code, large functions, duplicate logic, formatting consistency |
| Maintainability | Cyclomatic complexity, nesting depth, function length, state/effect counts, modularity |
| Architecture | React patterns (Context, Refs, Suspense), hook usage, API call patterns, memoization adoption |
Installation
# Global install (recommended)
npm install -g code-explainer
# Or use npx directly
npx code-explainer <file.tsx>
# As a project dependency
npm install code-explainerRequirements: Node.js >= 18.0.0
Quick Start
# Analyze a single component (default: senior level, terminal output)
code-explainer src/App.tsx
# Get architect-level audit
code-explainer src/App.tsx -e architect
# Save JSON report
code-explainer src/App.tsx -o json -s report.json
# Analyze all components in a directory
code-explainer src/components/
# Watch for changes
code-explainer src/ --watchSample Terminal Output
┌─────────────────────────────────────────────┐
│ Security ████████░░ 8/10 ✅ Good
│ Code Quality ██████░░░░ 6/10 ⚠️ Needs Attention
│ Maintainability ███████░░░ 7/10 ✅ Good
│ Risk Exposure ██░░░░░░░░ 2/10 ✅ Good
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│ SECURITY RISK ANALYSIS
│ 🔒 Secret scanning: ✅ Clean (0 issues)
│ 🛡️ XSS risk: ✅ Safe (0 instances)
│ 🌐 Unsafe API usage: ✅ None (0 calls)
│ ✅ Validation coverage: ✅ Complete (0 gaps)
│ 🔑 Auth review: ✅ Covered (0 checks)
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│ FINAL VERDICT
│ Overall Health: 🟡 Good with minor issues
│ Risk Category: Low-Medium
│ Immediate Actions: Review recommendations below
└─────────────────────────────────────────────┘Features
AI-Powered Explanations
Three explanation levels powered by NVIDIA AI (Llama 3.1 70B):
| Level | Target Audience | Output Style |
|:------|:---------------|:-------------|
| junior | Beginners learning React | Tutorial format with analogies, step-by-step fixes, score |
| senior | Experienced developers | Code health dashboard with metrics, severity counts |
| architect | Tech leads / architects | System architecture audit with strategic recommendations |
code-explainer src/App.tsx -e junior # Learning mode
code-explainer src/App.tsx -e senior # Professional analysis (default)
code-explainer src/App.tsx -e architect # Strategic auditMultiple Output Formats
| Format | Flag | Description |
|:-------|:-----|:------------|
| Terminal | -o terminal | Rich dashboard with KPI cards and panels (default) |
| JSON | -o json | Structured data for programmatic consumption |
| Markdown | -o markdown | Formatted report with tables and badges |
| HTML | -o html | Self-contained interactive dashboard |
Watch Mode
Automatically re-analyze files when they change:
code-explainer src/ --watchCaching
AI responses are cached locally to reduce API costs:
code-explainer src/App.tsx # Uses cache (default)
code-explainer src/App.tsx --no-cache # Skip cache
code-explainer --clear-cache # Clear all cached responsesGlob Pattern Support
code-explainer "src/**/*.tsx" # All TSX files
code-explainer "src/**/*.{ts,tsx}" # All TS and TSX files
code-explainer src/components/ # All files in directoryCLI Options
| Flag | Short | Description | Default |
|:-----|:------|:------------|:--------|
| --explain <level> | -e | Explanation depth: junior, senior, architect | senior |
| --output <format> | -o | Output format: terminal, json, markdown, html | terminal |
| --save <filename> | -s | Save output to a file | (stdout) |
| --watch | -w | Watch for file changes and re-analyze | false |
| --no-cache | | Bypass AI response cache | false |
| --clear-cache | | Clear the entire AI response cache | false |
| --config <path> | -c | Path to config file | auto-discovered |
| --no-color | | Disable colored terminal output | false |
| --verbose | -v | Show detailed processing logs | false |
Shorthand Levels
| Short | Full |
|:------|:-----|
| j | junior |
| s | senior |
| ar | architect |
Configuration
Config File Discovery
The tool searches for configuration in this order:
--config <path>(explicit).code-explainerrc.json(CWD).code-explainerrc(CWD)code-explainer.config.json(CWD)- Built-in defaults
Config Schema
{
"defaultLevel": "senior",
"defaultOutput": "terminal",
"apiKey": "nvapi-your-api-key-here",
"baseUrl": "https://integrate.api.nvidia.com/v1",
"model": "meta/llama-3.1-70b-instruct",
"cacheEnabled": true,
"cacheTTL": 24,
"supportedExtensions": [".tsx", ".ts", ".jsx", ".js"],
"ignorePatterns": ["node_modules", "dist", "build", ".next", ".git"]
}Field Reference
| Field | Type | Default | Description |
|:------|:-----|:--------|:------------|
| defaultLevel | string | "senior" | Default explanation depth |
| defaultOutput | string | "terminal" | Default output format |
| apiKey | string? | (env) | NVIDIA API key for AI features |
| baseUrl | string | https://integrate.api.nvidia.com/v1 | NVIDIA API endpoint |
| model | string | meta/llama-3.1-70b-instruct | AI model identifier |
| cacheEnabled | boolean | true | Enable/disable caching |
| cacheTTL | number | 24 | Cache TTL in hours |
| supportedExtensions | string[] | [".tsx", ".ts", ".jsx", ".js"] | File extensions to analyze |
| ignorePatterns | string[] | ["node_modules", "dist", ...] | Directories to ignore |
NVIDIA API Key Setup
Option 1: Environment Variable (Recommended)
export NVIDIA_API_KEY="nvapi-your-api-key-here"Option 2: Config File
{
"apiKey": "nvapi-your-api-key-here"
}Get your API key from NVIDIA AI Foundation Endpoints.
API Reference
Programmatic Usage
import { analyzeFile, formatTerminal, formatJSON, formatMarkdown, formatHTML } from "code-explainer";
import { loadConfig } from "code-explainer";
const config = loadConfig();
const summary = await analyzeFile("src/App.tsx", "senior", config);
console.log(formatTerminal(summary, "senior"));
console.log(formatJSON(summary));Functions
analyzeFile(filePath, level, config, verbose?)
Analyzes a React component file and returns a detailed ComponentSummary.
async function analyzeFile(
filePath: string,
level: ExplanationLevel,
config: CodeExplainerConfig,
verbose?: boolean
): Promise<ComponentSummary>formatTerminal(summary, level)
Formats analysis results for terminal dashboard display.
function formatTerminal(summary: ComponentSummary, level: ExplanationLevel): stringformatJSON(summary)
Generates structured JSON output.
function formatJSON(summary: ComponentSummary): stringformatMarkdown(summary)
Creates a markdown-formatted report.
function formatMarkdown(summary: ComponentSummary): stringformatHTML(summary)
Generates a self-contained interactive HTML dashboard.
function formatHTML(summary: ComponentSummary): stringloadConfig(configPath?)
Loads configuration with auto-discovery and defaults merging.
function loadConfig(configPath?: string): CodeExplainerConfigCache Functions
function getCached(code: string, level: string, ttlHours?: number): string | null
function setCache(code: string, level: string, result: string): void
function clearCache(): voidTypeScript Types
All types are fully exported:
import type {
ExplanationLevel, // "junior" | "senior" | "architect"
OutputFormat, // "terminal" | "json" | "markdown" | "html"
CLIOptions, // CLI flag options interface
ComponentSummary, // Main analysis result type
SecurityFinding, // Security issue with severity, location, recommendation
CodeQualityIssue, // Code quality issue
MaintainabilityIssue, // Maintainability issue
ComplexityMetrics, // Cyclomatic complexity, nesting depth, counts
ComponentMetadata, // Props, interfaces, imports
EffectSummary, // Hook effect details
OptimizationSummary, // Hook optimization details
PropInfo, // Property name and type
InterfaceInfo, // Interface name and members
CodeExplainerConfig, // Full configuration schema
} from "code-explainer";Project Structure
code-explainer/
├── src/
│ ├── analyzer.ts # AST analysis engine (ts-morph)
│ ├── cache.ts # SHA-256-based response caching
│ ├── cli.ts # CLI entry point (commander)
│ ├── config.ts # Config file discovery & loading
│ ├── explainer.ts # NVIDIA AI integration (openai SDK)
│ ├── formatters.ts # Terminal, JSON, Markdown, HTML formatters
│ ├── types.ts # Full TypeScript type definitions
│ └── __tests__/
│ ├── analyzer.test.ts # Analyzer unit tests
│ └── cache.test.ts # Cache unit tests
├── bin/
│ ├── ce # CLI alias
│ └── code-explainer # Main CLI entry
├── dist/ # Built output (CJS, ESM, DTS)
├── package.json
├── tsconfig.json
├── README.md
└── CHANGELOG.mdTesting
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Type-check without emitting
npm run lintBuilding
# Build for production
npm run build
# Output:
# dist/cli.js (CommonJS)
# dist/cli.mjs (ES Module)
# dist/cli.d.ts (TypeScript declarations)Contributing
Contributions are welcome! Here's how to get started:
- Fork the repository
- Clone your fork:
git clone https://github.com/<your-username>/Code-Analyzer-Tool.git - Install dependencies:
npm install - Create a feature branch:
git checkout -b feature/my-feature - Make your changes and add tests
- Run tests:
npm test - Commit and push:
git commit -m "feat: add my feature" git push origin feature/my-feature - Open a Pull Request
Development Commands
| Command | Description |
|:--------|:------------|
| npm run dev | Run CLI in development mode |
| npm run build | Build for production |
| npm test | Run tests |
| npm run test:watch | Run tests in watch mode |
| npm run lint | Type-check the codebase |
Changelog
See CHANGELOG.md for a detailed history of all changes.
License
Built with ❤️ for the React community
