npm package: @mathonsunday/dead-code-toolkit
Description: Comprehensive dead code detection and cleanup toolkit for TypeScript projects. Detects unused exports, files, dependencies, type errors, and more via Knip, TypeScript, ESLint, and custom analysis.
Author: mathonsunday
Latest version: 0.2.1

# @mathonsunday/dead-code-toolkit

**Comprehensive dead code detection and cleanup toolkit for TypeScript projects**

Detects unused exports, files, dependencies, type errors, and more via Knip, TypeScript, ESLint, and custom analysis. Perfect for keeping TypeScript codebases clean and maintaining high code quality.

## Features

✨ **Multi-layered Detection**
- **Knip**: Unused exports, files, dependencies (symbol-level)
- **TypeScript**: Type errors and unused variables
- **ESLint**: Linting issues and redundant types
- **Union Exhaustiveness**: Validates discriminated unions

🔧 **Automated Setup**
- One-command project setup: `npx @mathonsunday/dead-code-toolkit setup`
- Detects project type and generates optimal configurations
- Optional pre-commit hooks via `--hooks` flag

🚀 **LLM-Friendly**
- Callable as an MCP tool for AI assistance
- Structured JSON output for easy interpretation
- Action items and recommendations
- Perfect for Claude, ChatGPT, and other LLMs


📊 **Reporting**
- Human-readable terminal output
- JSON format for programmatic use
- LLM-friendly summaries
- Detailed suggestions for fixes

## Installation

```bash
npm install --save-dev @mathonsunday/dead-code-toolkit
```

## Quick Start

### CLI Usage

**Analyze your project for dead code:**
```bash
npx dead-code-toolkit analyze
```

**Output as JSON (for LLMs):**
```bash
npx dead-code-toolkit analyze --json
```

**Get brief summary:**
```bash
npx dead-code-toolkit analyze --summary
```

**Specific checks:**
```bash
npx dead-code-toolkit analyze --checks knip,typescript
```

**Run individual checks:**
```bash
npx dead-code-toolkit check:knip
npx dead-code-toolkit check:types
```

### Programmatic Usage

```typescript
import { analyzeDeadCode, createJSONReport } from '@mathonsunday/dead-code-toolkit';

const result = await analyzeDeadCode({
  projectRoot: process.cwd(),
  checks: ['knip', 'typescript'],
  verbose: true,
});

console.log(`Found ${result.summary.totalIssues} issues`);
console.log(`${result.summary.fixableCount} can be auto-fixed`);

// Get JSON report for LLM consumption
const report = createJSONReport(result);
console.log(JSON.stringify(report, null, 2));
```

### Setup in New Project

**Automatic setup:**
```bash
npx @mathonsunday/dead-code-toolkit setup
```

This auto-detects your project type and generates optimal configurations. Use `--hooks` flag to also install pre-commit hooks (optional).

## Configuration

The toolkit auto-detects your project structure and generates appropriate configs. You can override defaults:

**knip.json** - Symbol-level dead code detection
```json
{
  "entry": ["src/main.ts", "api/handler.ts"],
  "project": ["src/**/*.ts", "api/**/*.ts"],
  "ignore": ["dist/**", "node_modules/**"]
}
```

**ESLint rules** - Add to `eslint.config.js`:
```javascript
export default [
  {
    rules: {
      '@typescript-eslint/no-unused-vars': 'warn',
      '@typescript-eslint/no-redundant-type-constituents': 'warn',
      '@typescript-eslint/switch-exhaustiveness-check': 'error',
    },
  },
];
```

**package.json scripts:**
```json
{
  "scripts": {
    "dead-code": "knip",
    "dead-code:fix": "knip --fix",
    "dead-code:analyze": "dead-code-toolkit analyze",
    "verify": "npm run type-check && npm run lint && npm run dead-code"
  }
}
```

## LLM Integration

Use with Claude or other LLMs as an MCP tool:

```typescript
// In your tool registry
const deadCodeTool = {
  name: 'dead_code_analysis',
  description: 'Analyze TypeScript project for dead code',
  execute: async (input) => {
    const result = await analyzeDeadCode({
      projectRoot: input.projectRoot,
      checks: input.checks || ['knip', 'typescript'],
    });
    return createJSONReport(result);
  },
};
```

**LLM Workflow:**
1. User: "Help clean up dead code"
2. LLM: Calls `dead_code_analysis` tool
3. Tool: Returns structured findings
4. LLM: Interprets results and guides user
5. User: Approves fixes
6. LLM: Applies changes

## Architecture

### Checker Layers

| Layer | Detection Method | Scope |
|-------|-----------------|-------|
| **Knip** | Symbol analysis | Exports, files, dependencies |
| **TypeScript** | Type compiler | Type errors, unused variables |
| **ESLint** | Linting rules | Unused variables, redundant types, union exhaustiveness |

### Finding Categories

- `unused-export` - Exported but never used
- `unused-file` - File never imported
- `unused-dependency` - Package in package.json but unused
- `type-error` - TypeScript compilation error
- `unused-var` - Variable declared but never used
- `unused-param` - Function parameter never used
- `redundant-type` - Union with overlapping members
- `union-issue` - Discriminated union not exhaustively handled

## Known Limitations

1. **Semantic dead code** - Cannot detect if code serves no business purpose
2. **Dynamic imports** - May miss `import(`./${variant}`)`
3. **Reflection** - Runtime string-based access not tracked
4. **Cross-project usage** - Only analyzes within single project
5. **Performance** - May be slow on 100k+ LOC projects (optimization in progress)

## Troubleshooting

**"Knip not installed"**
```bash
npm install --save-dev knip
```

**"TypeScript not found"**
```bash
npm install --save-dev typescript
```

**"No issues found but I think there's dead code"**
- Run with `--verbose` flag for detailed output
- Check `knip.json` entry points are correct
- Verify project structure matches config


## License

MIT