Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@regele/devtools

regele404MIT0.9.6TypeScript support: included

A collection of developer utilities for code processing and text analysis

developer, tools, utilities, code, comment-remover, beautifier, word-counter, code-analyzer, handwriting-timer, text-analysis

readme

@regele/devtools

DevTools Version

npm version npm downloads License TypeScript Node.js

A powerful suite of developer utilities for code processing, analysis, and text manipulation

🧹 Clean💅 Beautify📊 Analyze⏱️ Time🔍 Detect


✨ Features

🧹 Comment Remover

Intelligently strip comments from 30+ file types while preserving code structure and functionality

  • Handles single-line, multi-line, and JSX comments
  • Preserves strings and regular expressions
  • Configurable options for selective removal

💅 Code Beautifier

Format and beautify code with customizable options for consistent style

  • Integrates with Prettier for professional formatting
  • Supports all major languages and file types
  • Customizable indentation, quotes, and line width

📊 Word Counter

Comprehensive text analysis with detailed statistics and metrics

  • Character, word, sentence, and paragraph counts
  • Reading time and typing time estimates
  • Word frequency analysis and readability scoring

⏱️ Handwriting Timer

Track writing sessions with sophisticated time estimation algorithms

  • Adaptive writing speed calculation
  • Text complexity and skill factor adjustments
  • Session history with detailed snapshots

🔍 Code Analyzer

Detect bugs, security issues, and performance bottlenecks in your code

  • Multiple severity levels and issue categories
  • Detailed reports with line numbers and suggestions
  • HTML and JSON report generation

🖥️ Unified CLI

Powerful command-line interface with consistent options across all tools

  • Process multiple files with glob patterns
  • Configurable through command line or config files
  • Beautiful terminal output with progress indicators

🌈 Multi-language Support

Works with 30+ languages and file types including:

  • JavaScript/TypeScript: .js, .jsx, .ts, .tsx, .mjs, .cjs, .vue, .svelte, .astro
  • HTML/XML: .html, .htm, .xml, .svg, .jsp, .asp, .ejs, .hbs
  • CSS: .css, .scss, .sass, .less, .stylus, .postcss
  • C-style: .c, .h, .cpp, .hpp, .java, .cs, .go, .swift
  • Others: .php, .py, .rb, .sql, .md, .txt, .json, .yaml

📦 Installation

📚 As a Library

npm install @regele/devtools
# or
yarn add @regele/devtools
# or
pnpm add @regele/devtools

🖥️ For CLI Usage

npm install -g @regele/devtools
# or
yarn global add @regele/devtools
# or
pnpm add -g @regele/devtools
<summary>📋 Requirements</summary>
  • Node.js: v14.x or higher
  • NPM: v6.x or higher
  • Operating Systems: Windows, macOS, Linux
  • Optional Dependencies:
    • Prettier (for enhanced code formatting)
    • ESLint (for enhanced code analysis)

🚀 Quick Start

🧹 Comment Remover

Basic Usage
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');
}
Advanced Configuration
// Customize removal options
const customRemover = new CommentRemover({
  singleLine: true,     // Remove single-line comments (// in JS)
  multiLine: true,      // Remove multi-line comments (/* */ in JS)
  jsxComments: true,    // Remove JSX comments ({/* */} in JSX/TSX)
  emptyLines: false     // Preserve empty lines after comment removal
});

// Or update options on an existing instance
commentRemover.updateOptions({
  singleLine: true,
  multiLine: false,     // Keep multi-line comments
  emptyLines: true
});

// Get current configuration
const options = commentRemover.getOptions();
console.log(options);
Processing Multiple Files
// Process multiple files with glob patterns
const results = await commentRemover.cleanFiles('src/**/*.{js,ts}', {
  write: true,          // Write changes back to files
  ignore: ['node_modules/**', 'dist/**'],  // Ignore patterns
  silent: false         // Show processing output
});

console.log(`Processed ${results.length} files`);

💅 Code Beautifier

Basic Usage
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)
const formattedCode = await beautifier.format(jsCode, FileType.JavaScript);
console.log(formattedCode);
Output:
function hello() {
  console.log('Hello world');
}
Customizing Formatting Options
// Create with specific options
const beautifier = new Beautifier({
  semi: false,          // No semicolons
  singleQuote: true,    // Use single quotes
  tabWidth: 4,          // 4-space indentation
  useTabs: false,       // Use spaces instead of tabs
  printWidth: 100,      // Line width limit
  trailingComma: 'es5', // Trailing commas where valid in ES5
  bracketSpacing: true, // Spaces in object literals
  arrowParens: 'always' // Parentheses around arrow function parameters
});

// Update options on an existing instance
beautifier.updateOptions({
  semi: true,
  printWidth: 80
});
Integration with Prettier
import prettier from 'prettier';

// Use with Prettier for enhanced formatting capabilities
const prettierBeautifier = new Beautifier({
  // Prettier options
  semi: true,
  singleQuote: true
}, prettier);

// Format files with specific parser
const tsCode = `interface User{name:string;age:number}`;
const formattedTS = await prettierBeautifier.format(tsCode, FileType.TypeScript);
console.log(formattedTS);
Output:
interface User {
  name: string;
  age: number;
}
Processing Multiple Files
// Format multiple files with glob patterns
const results = await beautifier.formatFiles('src/**/*.{js,ts,jsx,tsx}', {
  write: true,          // Write changes back to files
  ignore: ['node_modules/**', 'dist/**'],  // Ignore patterns
  silent: false         // Show processing output
});

console.log(`Beautified ${results.length} files`);

📊 Word Counter & ⏱️ Handwriting Timer

Basic Text Analysis
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 at once
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"
}
Individual Statistics & Analysis
// Get individual statistics
console.log(wordCounter.getWordCount());        // 20
console.log(wordCounter.getSentenceCount());    // 3
console.log(wordCounter.getReadingTime());      // "1 min"
console.log(wordCounter.getHandwritingTime());  // "~3 mins"

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

// Customize reading/writing speeds (words per minute)
wordCounter.setReadingSpeed(250);      // Fast reader
wordCounter.setHandwritingSpeed(20);   // Slow writer
wordCounter.setKeyboardSpeed(80);      // Fast typist

// Advanced analysis
const frequency = wordCounter.getWordFrequency();
console.log(frequency);  // { "new": 1, "text": 1, "to": 1, "analyze": 1 }

// Get most frequent words
const topWords = wordCounter.getMostFrequentWords(5);
console.log(topWords);   // [["new", 1], ["text", 1], ["to", 1], ["analyze", 1]]

// Get readability score (Flesch Reading Ease)
const readability = wordCounter.getReadabilityScore();
console.log(readability); // Higher score means easier to read
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
}
Timer Controls & Session History
// Timer control methods
wordCounter.pauseWritingSession();   // Pause the timer
wordCounter.startWritingSession();   // Resume the timer
wordCounter.stopWritingSession();    // Stop the current session
wordCounter.resetWritingSession();   // Reset the timer and session

// Get elapsed time
const elapsedTime = wordCounter.getElapsedTime();
const formattedTime = wordCounter.getFormattedElapsedTime(); // "00:05:32"

// Check timer status
const isRunning = wordCounter.isTimerRunning();

// Register tick callback (called every 100ms by default)
wordCounter.onTimerTick((elapsedTime) => {
  console.log(`Timer running: ${elapsedTime}ms`);
});

// Get the complete writing session history
const sessions = wordCounter.getWritingSessionHistory();
console.log(sessions);
Session History Output:
[
  {
    id: 1628506892451,
    startTime: "2023-08-09T12:34:52.451Z",
    duration: 65000,
    textSnapshots: [
      {
        timestamp: "2023-08-09T12:35:12.451Z",
        text: "Writing in progress...",
        elapsedTime: 20000
      },
      {
        timestamp: "2023-08-09T12:35:42.451Z",
        text: "Writing in progress... Adding more content.",
        elapsedTime: 50000
      }
    ]
  }
]
Analyzing Multiple Files
// Analyze multiple text files
const results = await wordCounter.analyzeFiles('content/**/*.{md,txt}', {
  ignore: ['node_modules/**', 'dist/**']
});

// Process results
for (const result of results) {
  if (result.success) {
    console.log(`File: ${result.path}`);
    console.log(`Words: ${result.stats?.words}`);
    console.log(`Reading time: ${result.stats?.readingTime}`);
    console.log(`Most frequent words:`, result.frequentWords);
    console.log(`Readability score: ${result.readabilityScore}`);
  }
}

🖥️ CLI Usage

🔧 Project Integration

Add these scripts to your package.json for easy access to all tools:

"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}"
}

Then run with npm:

npm run format    # Format all project files
npm run clean     # Remove comments from all project files
npm run analyze   # Analyze text content in project
npm run analyze-code  # Analyze code for issues

🧹 Comment Removal

Basic Usage
# Remove comments from files
devtools-clean "src/**/*.js" --write
Selective Comment Removal
# Remove only single-line comments
devtools-clean "src/**/*.js" --single-line --no-multi-line --write

# Keep JSX comments but remove others
devtools-clean "src/**/*.jsx" --no-jsx --write

# Remove comments but keep empty lines
devtools-clean "src/**/*.ts" --no-empty-lines --write
Multiple File Types
# Process multiple file types at once
devtools-clean "src/**/*.{js,ts,jsx,tsx,css,html}" --write

# Ignore specific files or directories
devtools-clean "src/**/*.js" --ignore "src/vendor/**,**/*.min.js" --write

💅 Code Beautification

Basic Usage
# Beautify files
devtools-beautify "src/**/*.js" --write
Using Configuration
# Use a custom Prettier config
devtools-beautify "src/**/*.js" --config .prettierrc --write

# Silent mode (no output)
devtools-beautify "src/**/*.js" --silent --write
Multiple File Types
# Process multiple file types at once
devtools-beautify "src/**/*.{js,ts,jsx,tsx,css,html}" --write

# Ignore specific files or directories
devtools-beautify "src/**/*.js" --ignore "src/vendor/**,**/*.min.js" --write

📊 Text Analysis

Basic Usage
# Analyze text files
devtools-analyze "src/**/*.{md,txt}"
Report Generation
# Generate a detailed JSON report
devtools-analyze "src/**/*.{md,txt}" --output report.json

# Show only summary information
devtools-analyze "src/**/*.md" --summary
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

🔍 Code Analysis

Basic Usage
# Analyze code for issues
devtools-analyze-code "src/**/*.js"
Filtering Results
# Filter by severity level
devtools-analyze-code "src/**/*.js" --severity warning

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

# Limit analysis depth
devtools-analyze-code "src/**/*.js" --max-depth 3
Report Generation
# Generate HTML report
devtools-analyze-code "src/**/*.js" --output report.html

# Generate JSON report
devtools-analyze-code "src/**/*.js" --output report.json --format json
Analysis Categories
  • 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

🌐 Unified CLI Interface

Help & Version
# Show help and version
devtools --help
devtools --version
Command Execution
# Run commands through the unified interface
devtools beautify "src/**/*.js"
devtools clean "src/**/*.js"
devtools analyze "src/**/*.md"
devtools analyze-code "src/**/*.js"
Global Options
# Verbose output with detailed information
devtools --verbose analyze-code "src/**/*.js"

# Quiet mode (minimal output)
devtools --quiet clean "src/**/*.js"

# Use configuration file
devtools --config .devtoolsrc analyze-code "src/**/*.js"

# Dry run (no changes to files)
devtools --dry-run beautify "src/**/*.js"

🔧 Supported File Types

🌐 JavaScript & TypeScript

.js .jsx .ts .tsx .mjs .cjs .json .vue .svelte .astro

🖥️ HTML & XML

.html .htm .xml .svg .xhtml .jsp .asp .ejs .hbs .pug

🎨 CSS & Styling

.css .scss .sass .less .styl .stylus .pcss .postcss

⚙️ C-style Languages

.c .h .cpp .hpp .cc .cs .java .go .swift .kt

🐘 PHP

.php .php5 .phtml .inc

🐍 Python & Ruby

.py .pyw .rb .pl .pm .r .jl

🐚 Shell Scripts

.sh .bash .zsh .fish .bat .cmd .ps1

🗃️ SQL & Databases

.sql .mysql .pgsql .sqlite .plsql

Note: All tools support the same file types, with appropriate processing applied based on the language and file structure.

⚙️ Configuration Options

🧹 Comment Remover Options

Configure how comments are removed from your code:

// Default options shown
const options = {
  singleLine: true,    // Remove single-line comments (// in JS)
  multiLine: true,     // Remove multi-line comments (/* */ in JS)
  jsxComments: true,   // Remove JSX comments ({/* */} in JSX/TSX)
  emptyLines: true     // Remove empty lines after comment removal
};

const commentRemover = new CommentRemover(options);
Option Type Default Description
singleLine boolean true Remove single-line comments like // comment
multiLine boolean true Remove multi-line comments like /* comment */
jsxComments boolean true Remove JSX comments like {/* comment */}
emptyLines boolean true Remove empty lines that result from comment removal

💅 Beautifier Options

Configure how your code is formatted:

// Default options shown
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
  trailingComma: 'es5',// Trailing commas where valid in ES5
  bracketSpacing: true,// Spaces in object literals
  arrowParens: 'always'// Parentheses around arrow function parameters
};

const beautifier = new Beautifier(options);
Option Type Default Description
semi boolean true Add semicolons at the end of statements
singleQuote boolean true Use single quotes instead of double quotes
tabWidth number 2 Number of spaces per indentation level
useTabs boolean false Use tabs for indentation instead of spaces
printWidth number 80 Maximum line length before wrapping
trailingComma string 'es5' Print trailing commas wherever possible when multi-line
bracketSpacing boolean true Print spaces between brackets in object literals
arrowParens string 'always' Include parentheses around a sole arrow function parameter

📊 Word Counter Options

Configure text analysis and timing calculations:

// Default options shown
const wordCounter = new WordCounter(
  "Text to analyze",   // Initial text
  200,                 // Reading speed (words per minute)
  25,                  // Handwriting speed (words per minute)
  60,                  // Keyboard typing speed (words per minute)
  {                    // Timer options
    tickInterval: 100, // Timer tick interval in ms
    onTick: (elapsed) => console.log(`Time: ${elapsed}ms`)
  }
);
Parameter Type Default Description
text string '' Initial text to analyze
wordsPerMinute number 200 Reading speed in words per minute
handwritingWpm number 25 Handwriting speed in words per minute
keyboardWpm number 60 Keyboard typing speed in words per minute
timerOptions object {} Options for the handwriting timer

📋 CLI Options

🧹 devtools-clean

Comment Removal
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
Examples:
# Basic usage
devtools-clean "src/**/*.js"

# Keep multi-line comments
devtools-clean "src/**/*.js" --no-multi-line

# Preserve empty lines
devtools-clean "src/**/*.js" --no-empty-lines

💅 devtools-beautify

Code Formatting
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
Examples:
# Basic usage
devtools-beautify "src/**/*.js"

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

# Preview changes without writing
devtools-beautify "src/**/*.js" --no-write

📊 devtools-analyze

Text Analysis
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
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)
  • Word frequency analysis
Examples:
# Basic usage
devtools-analyze "src/**/*.md"

# Generate JSON report
devtools-analyze "src/**/*.md" --output report.json

# Show only summary
devtools-analyze "src/**/*.md" --summary

🔍 devtools-analyze-code

Code Analysis
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
Analysis categories:
  • 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
Examples:
# Basic usage
devtools-analyze-code "src/**/*.js"

# Filter by severity
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

📚 API Reference

🧹 CommentRemover

Core
Removes comments from code while preserving structure and functionality.
constructor(options?: Partial<CommentRemovalOptions>)

Creates a new CommentRemover instance with optional configuration.

removeComments(code: string, fileType?: FileType | string): string

Removes comments from the provided code string based on the file type.

updateOptions(options: Partial<CommentRemovalOptions>): void

Updates the comment removal options for this instance.

getOptions(): CommentRemovalOptions

Returns the current comment removal options.

cleanFiles(patterns: string | string[], options?: FileOptions): Promise<FileResult[]>

Processes multiple files matching the glob patterns and removes comments.

💅 Beautifier

Core
Formats and beautifies code with customizable options.
constructor(options?: Partial<FormattingOptions>, prettier?: any)

Creates a new Beautifier instance with optional formatting options and Prettier instance.

format(code: string, fileType?: FileType | string): Promise<string>

Formats the provided code string based on the file type.

updateOptions(options: Partial<FormattingOptions>): void

Updates the formatting options for this instance.

getOptions(): FormattingOptions

Returns the current formatting options.

setPrettier(prettier: any): void

Sets a custom Prettier instance for enhanced formatting capabilities.

formatFiles(patterns: string | string[], options?: object): Promise<Result[]>

Processes multiple files matching the glob patterns and formats them.

📊 WordCounter

Analyzes text for statistics and provides timing estimates.

Constructor & Basic Methods

  • constructor(text: string = '', wordsPerMinute: number = 200, handwritingWpm: number = 25, keyboardWpm: number = 60, timerOptions?: HandwritingTimerOptions): Creates a new WordCounter instance with optional text and timing parameters.
  • setText(text: string): void: Sets the text to analyze.
  • getText(): string: Gets the current text being analyzed.

Speed Settings

  • setReadingSpeed(wordsPerMinute: number): void: Sets the reading speed in words per minute.
  • getReadingSpeed(): number: Gets the current reading speed.
  • setHandwritingSpeed(wordsPerMinute: number): void: Sets the handwriting speed in words per minute.
  • getHandwritingSpeed(): number: Gets the current handwriting speed.
  • setKeyboardSpeed(wordsPerMinute: number): void: Sets the keyboard typing speed in words per minute.
  • getKeyboardSpeed(): number: Gets the current keyboard typing speed.

Text Statistics

  • getStats(): WordCountStats: Gets all text statistics in a single object.
  • getCharacterCount(): number: Gets the total character count.
  • getCharacterCountNoSpaces(): number: Gets the character count excluding spaces.
  • getWordCount(): number: Gets the word count.
  • getSentenceCount(): number: Gets the sentence count.
  • getParagraphCount(): number: Gets the paragraph count.

Time Estimates

  • getReadingTime(): string: Gets the estimated reading time as a formatted string.
  • getHandwritingTime(): string: Gets the estimated handwriting time as a formatted string.
  • getKeyboardTime(): string: Gets the estimated keyboard typing time as a formatted string.

Advanced Analysis

  • getWordFrequency(): Record<string, number>: Gets the frequency of each word in the text.
  • getMostFrequentWords(limit: number = 10): [string, number][]: Gets the most frequently used words in the text.
  • getReadabilityScore(): number: Gets the readability score (Flesch Reading Ease).
  • analyzeFiles(patterns: string | string[], options?: object): Promise<AnalysisResult[]>: Analyzes multiple files matching the glob patterns.

Writing Session

  • startWritingSession(): void: Starts or resumes a writing session timer.
  • pauseWritingSession(): void: Pauses the current writing session timer.
  • stopWritingSession(): void: Stops the current writing session timer.
  • resetWritingSession(): void: Resets the writing session timer and history.
  • updateText(text: string): void: Updates the text and takes a snapshot for the timer.
  • getWritingSpeed(): WritingSpeedStats: Gets the current writing speed statistics.
  • getWritingSessionHistory(): WritingSession[]: Gets the complete writing session history.
  • getElapsedTime(): number: Gets the elapsed time in milliseconds.
  • getFormattedElapsedTime(): string: Gets the elapsed time as a formatted string (HH:MM:SS).
  • isTimerRunning(): boolean: Checks if the writing timer is currently running.
  • onTimerTick(callback: (elapsedTime: number) => void): void: Sets a callback function for timer tick events.

⏱️ HandwritingTimer

Tracks writing sessions with detailed statistics and snapshots.

  • constructor(options?: HandwritingTimerOptions): Creates a new HandwritingTimer instance with optional configuration.
  • start(): void: Starts or resumes the timer.
  • pause(): void: Pauses the timer.
  • stop(): void: Stops the timer and finalizes the current session.
  • reset(): void: Resets the timer and clears the current session.
  • takeTextSnapshot(text: string): void: Takes a snapshot of the current text for writing speed calculation.
  • calculateWritingSpeed(): WritingSpeedStats: Calculates the writing speed based on text snapshots.
  • getSessionHistory(): WritingSession[]: Gets the complete session history.
  • getElapsedTime(): number: Gets the elapsed time in milliseconds.
  • getFormattedTime(): string: Gets the elapsed time as a formatted string (HH:MM:SS).
  • isTimerRunning(): boolean: Checks if the timer is currently running.
  • onTick(callback: (elapsedTime: number) => void): void: Sets a callback function for timer tick events.

🔍 CodeAnalyzer

Analyzes code for potential issues, bugs, and improvements.

Methods

  • constructor(options?: CodeAnalysisOptions): Creates a new CodeAnalyzer instance with optional configuration.
  • analyzeFile(filePath: string): Promise<CodeAnalysisResult>: Analyzes a single file for issues and returns detailed results.
  • analyzeFiles(patterns: string | string[]): Promise<CodeAnalysisResult[]>: Analyzes multiple files matching the glob patterns.

Examples

import { CodeAnalyzer, SeverityLevel, CategoryType } from '@regele/devtools';

// Create analyzer with custom options
const analyzer = new CodeAnalyzer({
  minSeverity: SeverityLevel.Warning,  // Only report warnings and above
  categories: [                         // Only include these categories
    CategoryType.Security,
    CategoryType.Performance
  ],
  maxDepth: 3,                         // Maximum recursion depth
  ignore: ['node_modules/**', 'dist/**'] // Patterns to ignore
});

// Analyze a single file
const result = await analyzer.analyzeFile('src/app.js');
console.log(`Found ${result.findings.length} issues in ${result.filePath}`);

// Process findings
result.findings.forEach(finding => {
  console.log(`[${finding.severity}] ${finding.message} at line ${finding.line}`);
  console.log(`Category: ${finding.category}`);
  console.log(`Suggestion: ${finding.suggestion}`);
});

// Analyze multiple files
const results = await analyzer.analyzeFiles('src/**/*.js');
const totalIssues = results.reduce((sum, r) => sum + r.findings.length, 0);
console.log(`Found ${totalIssues} issues across ${results.length} files`);

// Calculate quality score
const qualityScore = results.reduce((score, result) => {
  // Higher score means better quality
  const fileScore = 100 - (result.findings.length * 5);
  return score + Math.max(0, fileScore);
}, 0) / results.length;

console.log(`Overall code quality score: ${qualityScore.toFixed(2)}/100`);

Analysis Categories

The CodeAnalyzer detects issues in the following categories:

  • 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

📝 License

MIT License

Open Source

This project is licensed under the MIT License - see the LICENSE file for details.

Copyright © 2025 Regele

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


Made with ❤️ by drwn

NPM

Current Version: v0.9.6