# @regele/devtools

<div align="center">

![DevTools Logo](https://img.shields.io/badge/%40regele-devtools%20v0.9.0-blue?style=for-the-badge&logo=npm)

[![npm version](https://img.shields.io/npm/v/@regele/devtools.svg?style=flat-square)](https://www.npmjs.com/package/@regele/devtools)
[![npm downloads](https://img.shields.io/npm/dm/@regele/devtools.svg?style=flat-square)](https://www.npmjs.com/package/@regele/devtools)
[![License](https://img.shields.io/npm/l/@regele/devtools.svg?style=flat-square)](https://github.com/yourusername/devtools/blob/main/LICENSE)

**A powerful collection of developer utilities for code processing and text analysis**

</div>

---

## ✨ Features

- 🧹 **Comment Remover**: Remove comments from 30+ file types while preserving code structure
- 💅 **Code Beautifier**: Format and beautify code with customizable options
- 📊 **Word Counter**: Analyze text for word count, character count, reading time, and more
- ⏱️ **Handwriting Timer**: Track writing sessions with detailed statistics and time estimates
- 🔍 **Code Analyzer**: Detect bugs, security issues, and performance bottlenecks in your code
- 🖥️ **CLI Tools**: Unified command-line interface with consistent options and commands
- 🚀 **Performance**: Optimized for speed and efficiency, even with large codebases
- 🌈 **Multi-language Support**: Works with JavaScript, TypeScript, HTML, CSS, Python, Ruby, and many more

## 📦 Installation

### For use as a library:

```bash
npm install @regele/devtools
```

### For CLI usage (global installation):

```bash
npm install -g @regele/devtools
```

## 🚀 Quick Start

### Comment Remover

```typescript
import { CommentRemover, FileType } from '@regele/devtools';

// Create a new comment remover with default options
const commentRemover = new CommentRemover();

// Remove comments from JavaScript code
const jsCode = `
// This is a comment
function hello() {
  /* This is a
     multiline comment */
  console.log('Hello world'); // End of line comment
}
`;

const cleanCode = commentRemover.removeComments(jsCode, FileType.JavaScript);
console.log(cleanCode);
// Output:
// function hello() {
//   console.log('Hello world');
// }

// Customize options
commentRemover.updateOptions({
  singleLine: true,
  multiLine: true,
  jsxComments: true,
  emptyLines: false
});

// Get current options
const options = commentRemover.getOptions();
```

### Code Beautifier

```typescript
import { Beautifier, FileType } from '@regele/devtools';

// Create a new beautifier with custom options
const beautifier = new Beautifier({
  semi: true,
  singleQuote: true,
  tabWidth: 2
});

// Format JavaScript code
const jsCode = `function hello(){console.log("Hello world")}`;

// Format code (returns a promise)
beautifier.format(jsCode, FileType.JavaScript)
  .then(formattedCode => {
    console.log(formattedCode);
    // Output:
    // function hello() {
    //   console.log('Hello world');
    // }
  });

// Update formatting options
beautifier.updateOptions({
  semi: false,
  tabWidth: 4
});

// Use with Prettier (if available)
import prettier from 'prettier';
const prettierBeautifier = new Beautifier({}, prettier);
```

### Word Counter & Handwriting Timer

```typescript
import { WordCounter } from '@regele/devtools';

// Create a new word counter with text
const text = "This is a sample text. It has two sentences. And it has multiple paragraphs.\n\nThis is the second paragraph.";
const wordCounter = new WordCounter(text);

// Get all statistics
const stats = wordCounter.getStats();
console.log(stats);
// Output:
// {
//   characters: 104,
//   charactersNoSpaces: 85,
//   words: 20,
//   sentences: 3,
//   paragraphs: 2,
//   readingTime: "1 min",
//   handwritingTime: "~3 mins",
//   keyboardTime: "~2 mins"
// }

// Get individual statistics
console.log(wordCounter.getWordCount()); // 20
console.log(wordCounter.getReadingTime()); // "1 min"
console.log(wordCounter.getHandwritingTime()); // "~3 mins"

// Set new text
wordCounter.setText("New text to analyze");

// Get word frequency
const frequency = wordCounter.getWordFrequency();
console.log(frequency);

// Get most frequent words
const topWords = wordCounter.getMostFrequentWords(5);
console.log(topWords);

// Get readability score
const readability = wordCounter.getReadabilityScore();
console.log(readability); // Higher score means easier to read

// Using the handwriting timer
// Start a writing session
wordCounter.startWritingSession();

// Update text during the session (this also takes a snapshot)
wordCounter.updateText("Writing in progress...");

// After some time, update with more text
wordCounter.updateText("Writing in progress... Adding more content.");

// Get current writing speed
const writingSpeed = wordCounter.getWritingSpeed();
console.log(writingSpeed);
// Output:
// {
//   wordsPerMinute: 15,
//   charactersPerMinute: 85,
//   totalWords: 8,
//   totalCharacters: 45,
//   elapsedTimeMs: 32000
// }

// Pause the timer
wordCounter.pauseWritingSession();

// Resume the timer
wordCounter.startWritingSession();

// Stop and reset the timer
wordCounter.stopWritingSession();

// Get the writing session history
const sessions = wordCounter.getWritingSessionHistory();
console.log(sessions);
```

## 🖥️ CLI Usage

### Add to your project

Add these scripts to your package.json:

```json
"scripts": {
  "format": "devtools-beautify src/**/*.{js,jsx,ts,tsx,json,css,html}",
  "clean": "devtools-clean src/**/*.{js,jsx,ts,tsx,json,css,html}",
  "analyze": "devtools-analyze src/**/*.{js,jsx,ts,tsx,md,txt}",
  "analyze-code": "devtools-analyze-code src/**/*.{js,jsx,ts,tsx}"
}
```

### CLI Commands

#### Comment Removal

```bash
# Remove comments from files
devtools-clean "src/**/*.js" --write

# Remove only single-line comments
devtools-clean "src/**/*.js" --single-line --no-multi-line --write

# Process multiple file types
devtools-clean "src/**/*.{js,ts,jsx,tsx,css,html}" --write
```

#### Code Beautification

```bash
# Beautify files
devtools-beautify "src/**/*.js" --write

# Use a custom Prettier config
devtools-beautify "src/**/*.js" --config .prettierrc --write

# Process multiple file types
devtools-beautify "src/**/*.{js,ts,jsx,tsx,css,html}" --write
```

#### Text Analysis

```bash
# Analyze text files
devtools-analyze "src/**/*.{md,txt}"

# Generate a detailed report
devtools-analyze "src/**/*.{md,txt}" --output report.json

# The analysis includes reading, handwriting, and keyboard typing time estimates
```

#### Code Analysis

```bash
# Analyze code for issues
devtools-analyze-code "src/**/*.js"

# Filter by severity level
devtools-analyze-code "src/**/*.js" --severity warning

# Filter by category
devtools-analyze-code "src/**/*.js" --category security,performance

# Generate HTML report
devtools-analyze-code "src/**/*.js" --output report.html

# Generate JSON report
devtools-analyze-code "src/**/*.js" --output report.json
```

### Unified CLI

You can also use the unified CLI interface:

```bash
# Show help and version
devtools --help
devtools --version

# Run commands
devtools beautify "src/**/*.js"
devtools clean "src/**/*.js"
devtools analyze "src/**/*.md"
devtools analyze-code "src/**/*.js"

# Global options
devtools --verbose analyze-code "src/**/*.js"
devtools --quiet clean "src/**/*.js"
devtools --config .devtoolsrc analyze-code "src/**/*.js"
devtools --dry-run beautify "src/**/*.js"
```

## 🔧 Supported File Types

### Comment Removal

| Language Family | Extensions |
|-----------------|------------|
| JavaScript/TypeScript | .js, .jsx, .ts, .tsx, .json, .mjs, .cjs, .vue, .svelte, .astro |
| HTML/XML | .html, .htm, .xml, .svg, .xhtml, .jsp, .asp, .aspx, .cshtml, .razor, .ejs, .hbs, .handlebars, .pug, .jade |
| CSS | .css, .scss, .sass, .less, .styl, .stylus, .pcss, .postcss |
| C-style | .c, .h, .cpp, .hpp, .cc, .cxx, .c++, .cs, .java, .go, .swift, .kt, .scala |
| PHP | .php, .php5, .phtml, .inc |
| Python/Ruby | .py, .pyw, .rb, .pl, .pm, .r, .jl |
| Shell | .sh, .bash, .zsh, .fish, .ksh, .bat, .cmd, .ps1 |
| SQL | .sql, .mysql, .pgsql, .sqlite, .plsql |

## ⚙️ Configuration Options

### Comment Remover Options

```javascript
const options = {
  singleLine: true,    // Remove single-line comments
  multiLine: true,     // Remove multi-line comments
  jsxComments: true,   // Remove JSX comments
  emptyLines: true     // Remove empty lines after comment removal
};

const commentRemover = new CommentRemover(options);
```

### Beautifier Options

```javascript
const options = {
  semi: true,          // Add semicolons
  singleQuote: true,   // Use single quotes
  tabWidth: 2,         // Tab width
  useTabs: false,      // Use spaces instead of tabs
  printWidth: 80       // Line width
};

const beautifier = new Beautifier(options);
```

## 📋 CLI Options

### devtools-clean

```
Usage: devtools-clean [options] <patterns...>

Remove comments from code files

Arguments:
  patterns              File patterns to clean (e.g., "src/**/*.js")

Options:
  --single-line         Remove single-line comments (default: true)
  --multi-line          Remove multi-line comments (default: true)
  --jsx                 Remove JSX comments (default: true)
  --empty-lines         Remove empty lines (default: true)
  --ignore <pattern>    Files to ignore (comma-separated)
  --write               Write changes to files (default: true)
  --silent              Suppress output (default: false)
  -h, --help            display help for command
```

### devtools-beautify

```
Usage: devtools-beautify [options] <patterns...>

Format and beautify code files

Arguments:
  patterns              File patterns to beautify (e.g., "src/**/*.js")

Options:
  --config <path>       Path to prettier config
  --ignore <pattern>    Files to ignore (comma-separated)
  --write               Write changes to files (default: true)
  --silent              Suppress output (default: false)
  -h, --help            display help for command
```

### devtools-analyze

```
Usage: devtools-analyze [options] <patterns...>

Analyze text content in files

Arguments:
  patterns              File patterns to analyze (e.g., "src/**/*.md")

Options:
  --summary             Show summary only (default: false)
  --ignore <pattern>    Files to ignore (comma-separated)
  --output <path>       Write report to file
  -h, --help            display help for command
```

The analysis includes:
- Character count (with and without spaces)
- Word, sentence, and paragraph counts
- Reading time estimates (based on 200 words per minute)
- Handwriting time estimates (based on 25 words per minute)
- Keyboard typing time estimates (based on 60 words per minute)
- Readability score (Flesch Reading Ease)
- Most frequent words

### devtools-analyze-code

```
Usage: devtools-analyze-code [options] <patterns...>

Analyze code for potential issues, bugs, and improvements

Arguments:
  patterns                 File patterns to analyze (e.g., "src/**/*.js")

Options:
  --severity <level>       Minimum severity level to report (info, warning, error, critical) (default: "info")
  --category <categories>  Categories to include (comma-separated: performance, security, maintainability, bugs, style)
  --ignore <pattern>       Files to ignore (comma-separated)
  --max-depth <depth>      Maximum depth for recursive analysis
  --root-dir <path>        Root directory for analysis
  --output <path>          Write report to file (json or html)
  --format <format>        Output format (text, json, html) (default: "text")
  --silent                 Suppress output (default: false)
  -h, --help               display help for command
```

The code analysis includes:
- **Performance**: Nested loops, unbatched DOM updates, unthrottled event listeners
- **Security**: Unsanitized user input, unsafe eval usage, dangerous innerHTML
- **Maintainability**: Complex functions, deep nesting, duplicated code, missing JSDoc
- **Bugs**: Off-by-one errors, unhandled promises, null dereferences, inconsistent returns
- **Style**: Naming conventions, indentation, semicolon usage, function style

## 📚 API Reference

### CommentRemover

- `constructor(options?: Partial<CommentRemovalOptions>)`
- `removeComments(code: string, fileType?: FileType | string): string`
- `updateOptions(options: Partial<CommentRemovalOptions>): void`
- `getOptions(): CommentRemovalOptions`

### Beautifier

- `constructor(options?: Partial<FormattingOptions>, prettier?: any)`
- `format(code: string, fileType?: FileType | string): Promise<string>`
- `updateOptions(options: Partial<FormattingOptions>): void`
- `getOptions(): FormattingOptions`
- `setPrettier(prettier: any): void`
- `formatFiles(patterns: string | string[], options?: object): Promise<Result[]>`

### WordCounter

- `constructor(text: string = '', wordsPerMinute: number = 200, handwritingWpm: number = 40, keyboardWpm: number = 60, timerOptions?: HandwritingTimerOptions)`
- `setText(text: string): void`
- `getText(): string`
- `setReadingSpeed(wordsPerMinute: number): void`
- `getReadingSpeed(): number`
- `setHandwritingSpeed(wordsPerMinute: number): void`
- `getHandwritingSpeed(): number`
- `setKeyboardSpeed(wordsPerMinute: number): void`
- `getKeyboardSpeed(): number`
- `getStats(): WordCountStats`
- `getCharacterCount(): number`
- `getCharacterCountNoSpaces(): number`
- `getWordCount(): number`
- `getSentenceCount(): number`
- `getParagraphCount(): number`
- `getReadingTime(): string`
- `getHandwritingTime(): string`
- `getKeyboardTime(): string`
- `getWordFrequency(): Record<string, number>`
- `getMostFrequentWords(limit: number = 10): [string, number][]`
- `getReadabilityScore(): number`
- `startWritingSession(): void`
- `pauseWritingSession(): void`
- `stopWritingSession(): void`
- `resetWritingSession(): void`
- `updateText(text: string): void`
- `getWritingSpeed(): WritingSpeedStats`
- `getWritingSessionHistory(): WritingSession[]`
- `getElapsedTime(): number`
- `getFormattedElapsedTime(): string`
- `isTimerRunning(): boolean`
- `onTimerTick(callback: (elapsedTime: number) => void): void`
- `analyzeFiles(patterns: string | string[], options?: object): Promise<AnalysisResult[]>`

### HandwritingTimer

- `constructor(options?: HandwritingTimerOptions)`
- `start(): void`
- `pause(): void`
- `stop(): void`
- `reset(): void`
- `takeTextSnapshot(text: string): void`
- `calculateWritingSpeed(): WritingSpeedStats`
- `getSessionHistory(): WritingSession[]`
- `getElapsedTime(): number`
- `getFormattedTime(): string`
- `isTimerRunning(): boolean`
- `onTick(callback: (elapsedTime: number) => void): void`

### CodeAnalyzer

- `constructor(options?: CodeAnalysisOptions)`
- `analyzeFile(filePath: string): Promise<CodeAnalysisResult>`
- `analyzeFiles(patterns: string | string[]): Promise<CodeAnalysisResult[]>`

## 📝 License

This project is [MIT](LICENSE) licensed.

---

<div align="center">

Made with ❤️ by [Regele](https://github.com/yourusername)

</div>
