npm package: @llms-sdk/decorators
Description: Dynamic code documentation and annotation system for LLMS SDK
Author: Lenny Miller
Latest version: 2.2.0

# @llms-sdk/decorators

Dynamic code documentation and annotation system for LLMS SDK. A modern reimplementation of literate programming concepts with LLM-powered annotations.

## Features

- **Multi-Language Support**: 70+ programming languages supported
- **Dynamic Documentation**: Generate documentation on-demand, no static files required
- **LLM Annotations**: Integrate with LLMS SDK's LLM clients for intelligent code explanations
- **Multiple Output Formats**: HTML, Markdown, and Terminal output
- **Syntax Highlighting**: Beautiful code highlighting with Shiki
- **Literate Programming**: Support for markdown files with embedded code
- **In-Memory Operation**: Fast, no file system overhead
- **Plugin System**: Extensible architecture with lifecycle hooks
- **Enhanced Navigation**: File tree sidebar, fuzzy search, keyboard shortcuts
- **Smart Index Generation**: Auto-categorization, symbol extraction, documentation stats
- **Code Complexity Analysis**: Built-in plugin for code quality metrics

## Installation

```bash
# Install as a dependency
npm install @llms-sdk/decorators

# Or use directly with npx (no installation required)
npx @llms-sdk/decorators generate src/index.ts
```

## Usage

### Basic Documentation Generation

#### CLI Usage

```bash
# Generate documentation for a single file
npx @llms-sdk/decorators generate src/index.ts

# Generate with theme and output directory
npx @llms-sdk/decorators generate src/index.ts --theme dark --output ./docs

# Process entire project with automatic index generation
npx @llms-sdk/decorators generate "src/**/*.ts" "lib/**/*.js" --output ./docs
```

#### Programmatic Usage

```typescript
import { Adorn } from "@llms-sdk/decorators";
import { readFile } from "fs/promises";

const adorn = new Adorn({
	layout: "parallel", // or 'linear', 'terminal'
	highlighter: "shiki",
	theme: "github-dark",
});

const source = "example.ts";
const content = await readFile(source, "utf-8");

const result = await adorn.document(source, content);

// Access different output formats
console.log(result.html); // HTML output
console.log(result.markdown); // Markdown output
console.log(result.terminal); // Terminal-friendly output
```

### LLM-Powered Annotations

#### CLI Usage

```bash
# Generate documentation with AI annotations
npx @llms-sdk/decorators annotate src/complex-algorithm.ts \
  --query "Explain the algorithm and suggest optimizations" \
  --provider anthropic \
  --model claude-3-5-sonnet-latest

# Batch annotation for multiple files
npx @llms-sdk/decorators annotate "src/core/*.ts" \
  --query "Create developer onboarding documentation" \
  --output ./docs/onboarding/
```

#### Programmatic Usage

```typescript
import { Adorn } from "@llms-sdk/decorators";
import { AnthropicClient } from "@llms-sdk/core";

const client = new AnthropicClient({ apiKey: process.env.ANTHROPIC_API_KEY });

const adorn = new Adorn({
	layout: "terminal",
});

// Configure the annotator with an LLM client
const result = await adorn.annotate(source, content, "Explain the error handling");

// Each section now includes AI-generated annotations
result.sections.forEach((section) => {
	if (section.annotation) {
		console.log(`💡 ${section.annotation}`);
	}
});
```

### Direct Annotator Usage

```typescript
import { Annotator } from "@llms-sdk/decorators";
import { OpenAIClient } from "@llms-sdk/core";

const client = new OpenAIClient({ apiKey: process.env.OPENAI_API_KEY });
const annotator = new Annotator({ client });

// Generate function documentation
const docString = await annotator.generateDocString(functionCode, "jsdoc");

// Explain a specific function
const explanation = await annotator.explainFunction(functionCode, "processData");

// Get improvement suggestions
const suggestions = await annotator.suggestImprovements(codeBlock);
```

### Parser Usage

```typescript
import { Parser } from "@llms-sdk/decorators";

const parser = new Parser();
const sections = await parser.parse("example.py", pythonCode);

// Extract documentation for a specific function
const funcDoc = await parser.extractDocumentation("example.py", pythonCode, "calculate_total");
```

## `/annotate` Command Integration

When integrated into an LLMS SDK chat application:

```
/annotate file.ts
/annotate src/utils.ts "How does the caching work?"
/annotate module.py explain the main algorithm
```

## API Reference

### `Adorn`

Main class for documentation generation.

#### Constructor Options

- `layout`: Output layout style ('parallel', 'linear', 'terminal')
- `highlighter`: Syntax highlighter to use ('shiki' or 'highlight.js')
- `theme`: Color theme for syntax highlighting
- `languages`: Custom language definitions
- `llmProvider`: LLM provider for annotations
- `llmModel`: Specific model to use

#### Methods

- `document(source, content)`: Generate documentation without annotations
- `annotate(source, content, query?)`: Generate documentation with AI annotations

### `Parser`

Extracts comments and code sections from source files.

- `parse(source, content)`: Parse entire file into sections
- `parseBlock(source, content, startLine, endLine)`: Parse specific block
- `extractDocumentation(source, content, identifier)`: Extract docs for identifier

### `Formatter`

Handles markdown rendering and syntax highlighting.

- `format(source, sections)`: Format sections with syntax highlighting
- `formatForTerminal(sections)`: Generate terminal-friendly output

### `Generator`

Produces final output in various formats.

- `generate(source, sections)`: Generate output based on configured format
- `generateIndex(files)`: Create an index page for multiple files

### `Annotator`

Provides LLM-powered code annotations.

- `annotate(sections, query?)`: Add annotations to sections
- `explainFunction(code, name)`: Explain a specific function
- `suggestImprovements(code)`: Get improvement suggestions
- `generateDocString(code, style)`: Generate documentation comments
- `batchAnnotate(sections, options)`: Efficiently annotate multiple sections

## Plugin System

Create custom plugins to extend functionality:

```typescript
import { BasePlugin } from "@llms-sdk/decorators";

class MyPlugin extends BasePlugin {
	name = "my-plugin";
	version = "1.0.0";

	// Lifecycle hooks
	async afterParse(sections) {
		// Process sections after parsing
		return sections;
	}

	// UI extensions
	getStyles() {
		return `.my-class { color: blue; }`;
	}
}

// Register plugin
adorn.registerPlugin(new MyPlugin());
```

### Built-in Plugins

#### Complexity Analyzer

Analyzes code complexity and quality:

```typescript
import { ComplexityAnalyzerPlugin } from "@llms-sdk/decorators";

const complexityPlugin = new ComplexityAnalyzerPlugin({
	config: {
		thresholds: {
			cyclomatic: { low: 5, medium: 10, high: 20 },
			functionLength: { warning: 50, error: 100 },
		},
		reportFormat: "inline", // or "summary", "detailed"
	},
});
```

Provides:

- Cyclomatic and cognitive complexity metrics
- Function length analysis
- Nesting depth warnings
- Parameter count checks
- Maintainability index
- Visual complexity indicators

### Dependency Graph Visualizer

```typescript
import { DependencyVisualizerPlugin } from "@llms-sdk/decorators";

const depPlugin = new DependencyVisualizerPlugin({
	config: {
		enabled: true,
		includeExternal: false,
		detectCircular: true,
		showStats: true,
		interactive: true,
		layout: "force", // or "hierarchy", "circular"
	},
});
```

Provides:

- Interactive dependency graph visualization
- Circular dependency detection
- Module relationship analysis
- Hub module identification
- Import/export statistics
- D3.js-powered interactive graphs

### Using Multiple Plugins

```typescript
const adorn = new Adorn({ layout: "parallel" });

// Register both plugins
adorn.registerPlugin(new ComplexityAnalyzerPlugin());
adorn.registerPlugin(new DependencyVisualizerPlugin());

// Generate documentation with both analyses
const results = await adorn.processFiles(["src/**/*.ts"]);
```

## Contributing

See the main LLMS SDK repository for contribution guidelines.

## License

MIT