UNPKG

@regele/devtools

Version:

A collection of developer utilities for code processing and text analysis

1,505 lines (1,256 loc) โ€ข 44.6 kB
# @regele/devtools <div align="center"> [![DevTools Version](https://img.shields.io/badge/%40regele-devtools%20v0.9.6-blue?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@regele/devtools) [![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/regele/devtools/blob/main/LICENSE) [![TypeScript](https://img.shields.io/badge/TypeScript-4.9+-blue.svg?style=flat-square&logo=typescript)](https://www.typescriptlang.org/) [![Node.js](https://img.shields.io/badge/Node.js-14.x+-green.svg?style=flat-square&logo=node.js)](https://nodejs.org/) <h3>A powerful suite of developer utilities for code processing, analysis, and text manipulation</h3> </div> <p align="center"> <b>๐Ÿงน Clean</b> โ€ข <b>๐Ÿ’… Beautify</b> โ€ข <b>๐Ÿ“Š Analyze</b> โ€ข <b>โฑ๏ธ Time</b> โ€ข <b>๐Ÿ” Detect</b> </p> --- ## โœจ Features <div class="feature-grid"> <div class="feature-card"> <h3>๐Ÿงน Comment Remover</h3> <p>Intelligently strip comments from 30+ file types while preserving code structure and functionality</p> <ul> <li>Handles single-line, multi-line, and JSX comments</li> <li>Preserves strings and regular expressions</li> <li>Configurable options for selective removal</li> </ul> </div> <div class="feature-card"> <h3>๐Ÿ’… Code Beautifier</h3> <p>Format and beautify code with customizable options for consistent style</p> <ul> <li>Integrates with Prettier for professional formatting</li> <li>Supports all major languages and file types</li> <li>Customizable indentation, quotes, and line width</li> </ul> </div> <div class="feature-card"> <h3>๐Ÿ“Š Word Counter</h3> <p>Comprehensive text analysis with detailed statistics and metrics</p> <ul> <li>Character, word, sentence, and paragraph counts</li> <li>Reading time and typing time estimates</li> <li>Word frequency analysis and readability scoring</li> </ul> </div> <div class="feature-card"> <h3>โฑ๏ธ Handwriting Timer</h3> <p>Track writing sessions with sophisticated time estimation algorithms</p> <ul> <li>Adaptive writing speed calculation</li> <li>Text complexity and skill factor adjustments</li> <li>Session history with detailed snapshots</li> </ul> </div> <div class="feature-card"> <h3>๐Ÿ” Code Analyzer</h3> <p>Detect bugs, security issues, and performance bottlenecks in your code</p> <ul> <li>Multiple severity levels and issue categories</li> <li>Detailed reports with line numbers and suggestions</li> <li>HTML and JSON report generation</li> </ul> </div> <div class="feature-card"> <h3>๐Ÿ–ฅ๏ธ Unified CLI</h3> <p>Powerful command-line interface with consistent options across all tools</p> <ul> <li>Process multiple files with glob patterns</li> <li>Configurable through command line or config files</li> <li>Beautiful terminal output with progress indicators</li> </ul> </div> </div> ### ๐ŸŒˆ 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 <div class="installation-grid"> <div class="installation-card"> <h3>๐Ÿ“š As a Library</h3> ```bash npm install @regele/devtools # or yarn add @regele/devtools # or pnpm add @regele/devtools ``` </div> <div class="installation-card"> <h3>๐Ÿ–ฅ๏ธ For CLI Usage</h3> ```bash npm install -g @regele/devtools # or yarn global add @regele/devtools # or pnpm add -g @regele/devtools ``` </div> </div> <details> <summary><b>๐Ÿ“‹ Requirements</b></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) </details> ## ๐Ÿš€ Quick Start ### ๐Ÿงน Comment Remover <div class="code-example"> <div class="code-header"> <span class="code-title">Basic Usage</span> </div> ```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); ``` <div class="code-output"> <span class="output-title">Output:</span> ```javascript function hello() { console.log('Hello world'); } ``` </div> </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Advanced Configuration</span> </div> ```typescript // 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); ``` </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Processing Multiple Files</span> </div> ```typescript // 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`); ``` </div> ### ๐Ÿ’… Code Beautifier <div class="code-example"> <div class="code-header"> <span class="code-title">Basic Usage</span> </div> ```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) const formattedCode = await beautifier.format(jsCode, FileType.JavaScript); console.log(formattedCode); ``` <div class="code-output"> <span class="output-title">Output:</span> ```javascript function hello() { console.log('Hello world'); } ``` </div> </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Customizing Formatting Options</span> </div> ```typescript // 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 }); ``` </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Integration with Prettier</span> </div> ```typescript 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); ``` <div class="code-output"> <span class="output-title">Output:</span> ```typescript interface User { name: string; age: number; } ``` </div> </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Processing Multiple Files</span> </div> ```typescript // 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`); ``` </div> ### ๐Ÿ“Š Word Counter & โฑ๏ธ Handwriting Timer <div class="code-example"> <div class="code-header"> <span class="code-title">Basic Text Analysis</span> </div> ```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 at once const stats = wordCounter.getStats(); console.log(stats); ``` <div class="code-output"> <span class="output-title">Output:</span> ```javascript { characters: 104, charactersNoSpaces: 85, words: 20, sentences: 3, paragraphs: 2, readingTime: "1 min", handwritingTime: "~3 mins", keyboardTime: "~2 mins" } ``` </div> </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Individual Statistics & Analysis</span> </div> ```typescript // 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 ``` </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Handwriting Timer</span> </div> ```typescript // 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); ``` <div class="code-output"> <span class="output-title">Output:</span> ```javascript { wordsPerMinute: 15, charactersPerMinute: 85, totalWords: 8, totalCharacters: 45, elapsedTimeMs: 32000 } ``` </div> </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Timer Controls & Session History</span> </div> ```typescript // 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); ``` <div class="code-output"> <span class="output-title">Session History Output:</span> ```javascript [ { 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 } ] } ] ``` </div> </div> <div class="code-example"> <div class="code-header"> <span class="code-title">Analyzing Multiple Files</span> </div> ```typescript // 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}`); } } ``` </div> ## ๐Ÿ–ฅ๏ธ CLI Usage <div class="cli-section"> <div class="cli-header"> <h3>๐Ÿ”ง Project Integration</h3> </div> Add these scripts to your `package.json` for easy access to all tools: ```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}" } ``` Then run with npm: ```bash 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 ``` </div> <div class="cli-section"> <div class="cli-header"> <h3>๐Ÿงน Comment Removal</h3> </div> <div class="cli-example"> <div class="cli-example-title">Basic Usage</div> ```bash # Remove comments from files devtools-clean "src/**/*.js" --write ``` <div class="cli-example-title">Selective Comment Removal</div> ```bash # 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 ``` <div class="cli-example-title">Multiple File Types</div> ```bash # 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 ``` </div> </div> <div class="cli-section"> <div class="cli-header"> <h3>๐Ÿ’… Code Beautification</h3> </div> <div class="cli-example"> <div class="cli-example-title">Basic Usage</div> ```bash # Beautify files devtools-beautify "src/**/*.js" --write ``` <div class="cli-example-title">Using Configuration</div> ```bash # Use a custom Prettier config devtools-beautify "src/**/*.js" --config .prettierrc --write # Silent mode (no output) devtools-beautify "src/**/*.js" --silent --write ``` <div class="cli-example-title">Multiple File Types</div> ```bash # 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 ``` </div> </div> <div class="cli-section"> <div class="cli-header"> <h3>๐Ÿ“Š Text Analysis</h3> </div> <div class="cli-example"> <div class="cli-example-title">Basic Usage</div> ```bash # Analyze text files devtools-analyze "src/**/*.{md,txt}" ``` <div class="cli-example-title">Report Generation</div> ```bash # Generate a detailed JSON report devtools-analyze "src/**/*.{md,txt}" --output report.json # Show only summary information devtools-analyze "src/**/*.md" --summary ``` <div class="cli-example-title">Analysis Includes</div> - 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 </div> </div> <div class="cli-section"> <div class="cli-header"> <h3>๐Ÿ” Code Analysis</h3> </div> <div class="cli-example"> <div class="cli-example-title">Basic Usage</div> ```bash # Analyze code for issues devtools-analyze-code "src/**/*.js" ``` <div class="cli-example-title">Filtering Results</div> ```bash # 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 ``` <div class="cli-example-title">Report Generation</div> ```bash # Generate HTML report devtools-analyze-code "src/**/*.js" --output report.html # Generate JSON report devtools-analyze-code "src/**/*.js" --output report.json --format json ``` <div class="cli-example-title">Analysis Categories</div> - **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 </div> </div> <div class="cli-section"> <div class="cli-header"> <h3>๐ŸŒ Unified CLI Interface</h3> </div> <div class="cli-example"> <div class="cli-example-title">Help & Version</div> ```bash # Show help and version devtools --help devtools --version ``` <div class="cli-example-title">Command Execution</div> ```bash # Run commands through the unified interface devtools beautify "src/**/*.js" devtools clean "src/**/*.js" devtools analyze "src/**/*.md" devtools analyze-code "src/**/*.js" ``` <div class="cli-example-title">Global Options</div> ```bash # 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" ``` </div> </div> ## ๐Ÿ”ง Supported File Types <div class="file-types-container"> <div class="file-type-card"> <h3>๐ŸŒ JavaScript & TypeScript</h3> <div class="file-extensions"> <span>.js</span> <span>.jsx</span> <span>.ts</span> <span>.tsx</span> <span>.mjs</span> <span>.cjs</span> <span>.json</span> <span>.vue</span> <span>.svelte</span> <span>.astro</span> </div> </div> <div class="file-type-card"> <h3>๐Ÿ–ฅ๏ธ HTML & XML</h3> <div class="file-extensions"> <span>.html</span> <span>.htm</span> <span>.xml</span> <span>.svg</span> <span>.xhtml</span> <span>.jsp</span> <span>.asp</span> <span>.ejs</span> <span>.hbs</span> <span>.pug</span> </div> </div> <div class="file-type-card"> <h3>๐ŸŽจ CSS & Styling</h3> <div class="file-extensions"> <span>.css</span> <span>.scss</span> <span>.sass</span> <span>.less</span> <span>.styl</span> <span>.stylus</span> <span>.pcss</span> <span>.postcss</span> </div> </div> <div class="file-type-card"> <h3>โš™๏ธ C-style Languages</h3> <div class="file-extensions"> <span>.c</span> <span>.h</span> <span>.cpp</span> <span>.hpp</span> <span>.cc</span> <span>.cs</span> <span>.java</span> <span>.go</span> <span>.swift</span> <span>.kt</span> </div> </div> <div class="file-type-card"> <h3>๐Ÿ˜ PHP</h3> <div class="file-extensions"> <span>.php</span> <span>.php5</span> <span>.phtml</span> <span>.inc</span> </div> </div> <div class="file-type-card"> <h3>๐Ÿ Python & Ruby</h3> <div class="file-extensions"> <span>.py</span> <span>.pyw</span> <span>.rb</span> <span>.pl</span> <span>.pm</span> <span>.r</span> <span>.jl</span> </div> </div> <div class="file-type-card"> <h3>๐Ÿš Shell Scripts</h3> <div class="file-extensions"> <span>.sh</span> <span>.bash</span> <span>.zsh</span> <span>.fish</span> <span>.bat</span> <span>.cmd</span> <span>.ps1</span> </div> </div> <div class="file-type-card"> <h3>๐Ÿ—ƒ๏ธ SQL & Databases</h3> <div class="file-extensions"> <span>.sql</span> <span>.mysql</span> <span>.pgsql</span> <span>.sqlite</span> <span>.plsql</span> </div> </div> </div> <div class="file-type-note"> <p><strong>Note:</strong> All tools support the same file types, with appropriate processing applied based on the language and file structure.</p> </div> ## โš™๏ธ Configuration Options <div class="config-section"> <div class="config-card"> <div class="config-header"> <h3>๐Ÿงน Comment Remover Options</h3> </div> <div class="config-content"> <p>Configure how comments are removed from your code:</p> ```typescript // 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); ``` <div class="config-table"> <table> <thead> <tr> <th>Option</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>singleLine</code></td> <td>boolean</td> <td>true</td> <td>Remove single-line comments like <code>// comment</code></td> </tr> <tr> <td><code>multiLine</code></td> <td>boolean</td> <td>true</td> <td>Remove multi-line comments like <code>/* comment */</code></td> </tr> <tr> <td><code>jsxComments</code></td> <td>boolean</td> <td>true</td> <td>Remove JSX comments like <code>{/* comment */}</code></td> </tr> <tr> <td><code>emptyLines</code></td> <td>boolean</td> <td>true</td> <td>Remove empty lines that result from comment removal</td> </tr> </tbody> </table> </div> </div> </div> <div class="config-card"> <div class="config-header"> <h3>๐Ÿ’… Beautifier Options</h3> </div> <div class="config-content"> <p>Configure how your code is formatted:</p> ```typescript // 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); ``` <div class="config-table"> <table> <thead> <tr> <th>Option</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>semi</code></td> <td>boolean</td> <td>true</td> <td>Add semicolons at the end of statements</td> </tr> <tr> <td><code>singleQuote</code></td> <td>boolean</td> <td>true</td> <td>Use single quotes instead of double quotes</td> </tr> <tr> <td><code>tabWidth</code></td> <td>number</td> <td>2</td> <td>Number of spaces per indentation level</td> </tr> <tr> <td><code>useTabs</code></td> <td>boolean</td> <td>false</td> <td>Use tabs for indentation instead of spaces</td> </tr> <tr> <td><code>printWidth</code></td> <td>number</td> <td>80</td> <td>Maximum line length before wrapping</td> </tr> <tr> <td><code>trailingComma</code></td> <td>string</td> <td>'es5'</td> <td>Print trailing commas wherever possible when multi-line</td> </tr> <tr> <td><code>bracketSpacing</code></td> <td>boolean</td> <td>true</td> <td>Print spaces between brackets in object literals</td> </tr> <tr> <td><code>arrowParens</code></td> <td>string</td> <td>'always'</td> <td>Include parentheses around a sole arrow function parameter</td> </tr> </tbody> </table> </div> </div> </div> <div class="config-card"> <div class="config-header"> <h3>๐Ÿ“Š Word Counter Options</h3> </div> <div class="config-content"> <p>Configure text analysis and timing calculations:</p> ```typescript // 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`) } ); ``` <div class="config-table"> <table> <thead> <tr> <th>Parameter</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>text</code></td> <td>string</td> <td>''</td> <td>Initial text to analyze</td> </tr> <tr> <td><code>wordsPerMinute</code></td> <td>number</td> <td>200</td> <td>Reading speed in words per minute</td> </tr> <tr> <td><code>handwritingWpm</code></td> <td>number</td> <td>25</td> <td>Handwriting speed in words per minute</td> </tr> <tr> <td><code>keyboardWpm</code></td> <td>number</td> <td>60</td> <td>Keyboard typing speed in words per minute</td> </tr> <tr> <td><code>timerOptions</code></td> <td>object</td> <td>{}</td> <td>Options for the handwriting timer</td> </tr> </tbody> </table> </div> </div> </div> </div> ## ๐Ÿ“‹ CLI Options <div class="cli-options-container"> <div class="cli-option-card"> <div class="cli-option-header"> <h3>๐Ÿงน devtools-clean</h3> <span class="cli-badge">Comment Removal</span> </div> ```bash 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 ``` <div class="cli-option-examples"> <div class="cli-example-title">Examples:</div> ```bash # 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 ``` </div> </div> <div class="cli-option-card"> <div class="cli-option-header"> <h3>๐Ÿ’… devtools-beautify</h3> <span class="cli-badge">Code Formatting</span> </div> ```bash 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 ``` <div class="cli-option-examples"> <div class="cli-example-title">Examples:</div> ```bash # 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 ``` </div> </div> <div class="cli-option-card"> <div class="cli-option-header"> <h3>๐Ÿ“Š devtools-analyze</h3> <span class="cli-badge">Text Analysis</span> </div> ```bash 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 ``` <div class="cli-option-features"> <div class="cli-features-title">Analysis includes:</div> <ul> <li><strong>Character count</strong> (with and without spaces)</li> <li><strong>Word, sentence, and paragraph counts</strong></li> <li><strong>Reading time</strong> estimates (based on 200 words per minute)</li> <li><strong>Handwriting time</strong> estimates (based on 25 words per minute)</li> <li><strong>Keyboard typing time</strong> estimates (based on 60 words per minute)</li> <li><strong>Readability score</strong> (Flesch Reading Ease)</li> <li><strong>Word frequency</strong> analysis</li> </ul> </div> <div class="cli-option-examples"> <div class="cli-example-title">Examples:</div> ```bash # Basic usage devtools-analyze "src/**/*.md" # Generate JSON report devtools-analyze "src/**/*.md" --output report.json # Show only summary devtools-analyze "src/**/*.md" --summary ``` </div> </div> <div class="cli-option-card"> <div class="cli-option-header"> <h3>๐Ÿ” devtools-analyze-code</h3> <span class="cli-badge">Code Analysis</span> </div> ```bash 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 ``` <div class="cli-option-features"> <div class="cli-features-title">Analysis categories:</div> <ul> <li><strong>Performance</strong>: Nested loops, unbatched DOM updates, unthrottled event listeners</li> <li><strong>Security</strong>: Unsanitized user input, unsafe eval usage, dangerous innerHTML</li> <li><strong>Maintainability</strong>: Complex functions, deep nesting, duplicated code, missing JSDoc</li> <li><strong>Bugs</strong>: Off-by-one errors, unhandled promises, null dereferences, inconsistent returns</li> <li><strong>Style</strong>: Naming conventions, indentation, semicolon usage, function style</li> </ul> </div> <div class="cli-option-examples"> <div class="cli-example-title">Examples:</div> ```bash # 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 ``` </div> </div> </div> ## ๐Ÿ“š API Reference <div class="api-container"> <div class="api-class-card"> <div class="api-class-header"> <h3>๐Ÿงน CommentRemover</h3> <span class="api-badge">Core</span> </div> <div class="api-class-description"> Removes comments from code while preserving structure and functionality. </div> <div class="api-methods"> <div class="api-method"> <code>constructor(options?: Partial&lt;CommentRemovalOptions&gt;)</code> <p>Creates a new CommentRemover instance with optional configuration.</p> </div> <div class="api-method"> <code>removeComments(code: string, fileType?: FileType | string): string</code> <p>Removes comments from the provided code string based on the file type.</p> </div> <div class="api-method"> <code>updateOptions(options: Partial&lt;CommentRemovalOptions&gt;): void</code> <p>Updates the comment removal options for this instance.</p> </div> <div class="api-method"> <code>getOptions(): CommentRemovalOptions</code> <p>Returns the current comment removal options.</p> </div> <div class="api-method"> <code>cleanFiles(patterns: string | string[], options?: FileOptions): Promise&lt;FileResult[]&gt;</code> <p>Processes multiple files matching the glob patterns and removes comments.</p> </div> </div> </div> <div class="api-class-card"> <div class="api-class-header"> <h3>๐Ÿ’… Beautifier</h3> <span class="api-badge">Core</span> </div> <div class="api-class-description"> Formats and beautifies code with customizable options. </div> <div class="api-methods"> <div class="api-method"> <code>constructor(options?: Partial&lt;FormattingOptions&gt;, prettier?: any)</code> <p>Creates a new Beautifier instance with optional formatting options and Prettier instance.</p> </div> <div class="api-method"> <code>format(code: string, fileType?: FileType | string): Promise&lt;string&gt;</code> <p>Formats the provided code string based on the file type.</p> </div> <div class="api-method"> <code>updateOptions(options: Partial&lt;FormattingOptions&gt;): void</code> <p>Updates the formatting options for this instance.</p> </div> <div class="api-method"> <code>getOptions(): FormattingOptions</code> <p>Returns the current formatting options.</p> </div> <div class="api-method"> <code>setPrettier(prettier: any): void</code> <p>Sets a custom Prettier instance for enhanced formatting capabilities.</p> </div> <div class="api-method"> <code>formatFiles(patterns: string | string[], options?: object): Promise&lt;Result[]&gt;</code> <p>Processes multiple files matching the glob patterns and formats them.</p> </div> </div> </div> ### ๐Ÿ“Š 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 ```typescript 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 <div class="license-container"> <div class="license-card"> <div class="license-header"> <h3>MIT License</h3> <span class="license-badge">Open Source</span> </div> <div class="license-content"> <p>This project is licensed under the MIT License - see the LICENSE file for details.</p> <p>Copyright ยฉ 2025 Regele</p> <p>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:</p> <p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p> </div> </div> </div> --- <div class="footer"> <div align="center"> <p class="footer-text">Made with โค๏ธ by <a href="https://github.com/k6w">drwn</a></p> <div class="footer-links"> <a href="https://www.npmjs.com/package/@regele/devtools">NPM</a> โ€ข </div> <p class="version-text">Current Version: v0.9.6</p> </div> </div>