UNPKG

@regele/devtools

Version:

A collection of developer utilities for code processing and text analysis

3 lines (2 loc) 25.4 kB
"use strict";var t,e,s=require("commander"),i=require("fs"),r=require("fast-glob"),n=require("chalk"),a=require("ora"),o=require("path");function l(e,s){var i;if(s){const e=(null===(i=s.split(".").pop())||void 0===i?void 0:i.toLowerCase())||"";if(["js","cjs","mjs"].includes(e))return t.JavaScript;if(["jsx"].includes(e))return t.JSX;if(["ts"].includes(e))return t.TypeScript;if(["tsx"].includes(e))return t.TSX;if(["json"].includes(e))return t.JSON;if(["yaml","yml"].includes(e))return t.YAML;if(["css"].includes(e))return t.CSS;if(["scss","sass"].includes(e))return t.SCSS;if(["less"].includes(e))return t.LESS;if(["html","htm","xhtml","jsp","asp","aspx","cshtml","razor","ejs","hbs","handlebars","pug","jade"].includes(e))return t.HTML;if(["xml","xsd","xsl","xslt"].includes(e))return t.XML;if(["svg"].includes(e))return t.SVG;if(["py","pyw"].includes(e))return t.Python;if(["rb"].includes(e))return t.Ruby;if(["php","php5","phtml","inc"].includes(e))return t.PHP;if(["java"].includes(e))return t.Java;if(["cs"].includes(e))return t.CSharp;if(["c","h"].includes(e))return t.C;if(["cpp","hpp","cc","cxx","c++"].includes(e))return t.CPP;if(["go"].includes(e))return t.Go;if(["swift"].includes(e))return t.Swift;if(["kt"].includes(e))return t.Kotlin;if(["rs"].includes(e))return t.Rust;if(["sh","bash","zsh","fish","ksh"].includes(e))return t.Shell;if(["ps1"].includes(e))return t.PowerShell;if(["bat","cmd"].includes(e))return t.Batch;if(["sql","mysql","pgsql","sqlite","plsql"].includes(e))return t.SQL;if(["md","markdown"].includes(e))return t.Markdown;if(["txt"].includes(e))return t.Text}const r=e.slice(0,1e3).trim();return r.includes("import React")||r.includes('from "react"')||r.includes("from 'react'")||r.match(/<\w+(\s+\w+=".*?")*\s*\/?>/)||r.includes("</")?r.includes(": ")||r.includes("interface ")||r.includes("type ")||r.match(/:\s*[A-Za-z]+[<>]/)||r.includes("as ")?r.includes("JSX")||r.includes("<>")?t.TSX:t.TypeScript:r.includes("JSX")||r.includes("<>")?t.JSX:t.JavaScript:r.startsWith("{")&&r.includes('"')||r.startsWith("[")&&r.includes('"')?t.JSON:r.match(/^[a-zA-Z0-9_-]+:\s*[^\s]/)||r.match(/^\s+- [a-zA-Z0-9_-]+:/)?t.YAML:r.includes("{")&&r.includes("}")&&r.includes(":")&&(r.includes(";")||r.includes("px")||r.includes("em"))?t.CSS:r.match(/<html|<!DOCTYPE|<head|<body|<div/i)?t.HTML:r.match(/<\?xml|<[a-zA-Z0-9_-]+>[\s\S]*?<\/[a-zA-Z0-9_-]+>/)?t.XML:r.includes("<svg")||r.includes("xmlns:svg=")?t.SVG:r.match(/^(import|from|def|class)\s/m)||r.includes('if __name__ == "__main__"')||r.match(/^\s*#.*$/m)?t.Python:r.match(/^(require|class|def|module)\s/m)||r.includes("do |")||r.includes("end")?t.Ruby:r.includes("<?php")||r.match(/^\s*<\?/)?t.PHP:r.match(/public\s+(class|interface|enum)/)||r.match(/import\s+java\./)||r.match(/package\s+[a-z0-9_.]+;/)?t.Java:r.match(/using\s+System;/)||r.match(/namespace\s+[A-Za-z0-9_.]+/)||r.includes("public class ")?t.CSharp:r.match(/#include\s+[<"].*[>"]/)?r.includes("std::")||r.includes("namespace ")?t.CPP:t.C:r.match(/package\s+[a-z0-9_]+/)||r.match(/import\s+\(/)||r.match(/func\s+[A-Za-z0-9_]+\(/)?t.Go:r.match(/import\s+Foundation/)||r.match(/class\s+[A-Za-z0-9_]+\s*:/)||r.match(/func\s+[a-zA-Z0-9_]+\(/)?t.Swift:r.match(/fun\s+[a-zA-Z0-9_]+\(/)||r.match(/val\s+[a-zA-Z0-9_]+:/)||r.match(/var\s+[a-zA-Z0-9_]+:/)?t.Kotlin:r.match(/^#!/)||r.match(/^\s*#.*$/m)||r.match(/echo\s+["']/)||r.match(/export\s+[A-Z_]+=/)?t.Shell:r.includes("function ")&&r.includes("param(")?t.PowerShell:r.match(/^@echo off/i)||r.match(/^REM\s/i)||r.match(/^(set|echo|if|goto)\s/im)?t.Batch:r.match(/SELECT\s+.*\s+FROM/i)||r.match(/CREATE\s+TABLE/i)||r.match(/INSERT\s+INTO/i)||r.match(/UPDATE\s+.*\s+SET/i)?t.SQL:r.match(/^#\s+/)||r.match(/\n#{1,6}\s+/)||r.match(/\[.*\]\(.*\)/)||r.match(/\*\*.*\*\*/)?t.Markdown:r.split("\n").length>1||r.length>0?t.Text:t.Unknown}!function(t){t.JavaScript="javascript",t.TypeScript="typescript",t.JSX="jsx",t.TSX="tsx",t.HTML="html",t.CSS="css",t.SCSS="scss",t.LESS="less",t.JSON="json",t.XML="xml",t.SVG="svg",t.Python="python",t.Ruby="ruby",t.PHP="php",t.Java="java",t.CSharp="csharp",t.CPP="cpp",t.C="c",t.Go="go",t.Swift="swift",t.Kotlin="kotlin",t.Rust="rust",t.Shell="shell",t.PowerShell="powershell",t.Batch="batch",t.SQL="sql",t.Markdown="markdown",t.YAML="yaml",t.Text="text",t.Unknown="unknown"}(t||(t={})),function(t){t.JavaScript="js",t.HTML="html",t.CSS="css",t.JSON="json",t.XML="xml",t.Python="python",t.Ruby="ruby",t.PHP="php",t.CStyle="cstyle",t.Shell="shell",t.SQL="sql",t.Markdown="markdown",t.YAML="yaml",t.Text="text",t.Unknown="unknown"}(e||(e={}));const c=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/package-lock.json","**/yarn.lock","**/*.min.js","**/*.min.css","**/*.bundle.js"];async function u(t,e={}){const s=[...c,...e.ignore||[]],i=(Array.isArray(t)?t:[t]).map((t=>t.replace(/\\/g,"/")));return await r(i,{ignore:s,onlyFiles:!0,absolute:!0,followSymbolicLinks:!1})}function h(t){try{const e=i.readFileSync(t,"utf8");return{content:e,fileType:l(e,t)}}catch(e){throw new Error(`Failed to read file ${t}: ${e.message}`)}}async function m(t,e,s={}){try{const{content:r,fileType:n}=h(t),a=r.length;if(!r.trim())return{path:t,success:!0,fileType:n,originalSize:a,newSize:a,diffSize:0,diffPercentage:0};const o=await e(r,n),l=o.length,c=a-l,u=a>0?c/a*100:0;return s.write&&function(t,e){try{return i.writeFileSync(t,e,"utf8"),!0}catch(e){throw new Error(`Failed to write file ${t}: ${e.message}`)}}(t,o),{path:t,success:!0,fileType:n,originalSize:a,newSize:l,diffSize:c,diffPercentage:u}}catch(e){return{path:t,success:!1,error:e.message}}}async function d(t,e,s={}){const i=await u(t,s),r=[];for(const t of i){const i=await m(t,e,s);r.push(i)}return r}class p{constructor(t,e){this.options={semi:!0,singleQuote:!1,tabWidth:2,useTabs:!1,trailingComma:"es5",bracketSpacing:!0,arrowParens:"always",...t},this.prettier=e}async format(e,s){if(!e.trim())return"";const i="string"==typeof s&&s in t?s:l(e);try{return this.prettier?this.formatWithPrettier(e,i):"undefined"!=typeof window&&window.prettier?this.formatWithBrowserPrettier(e,i):this.formatWithSimpleFormatters(e)}catch(t){return console.warn("Formatting error:",t),e}}formatWithPrettier(t,e){const s=this.getPrettierParser(e);return this.prettier.format(t,{parser:s,...this.options})}formatWithBrowserPrettier(t,e){const s=this.getPrettierParser(e);return window.prettier.format(t,{parser:s,plugins:window.prettierPlugins?Object.values(window.prettierPlugins):void 0,...this.options})}getPrettierParser(e){switch(e){case t.JavaScript:case t.JSX:return"babel";case t.TypeScript:case t.TSX:return"typescript";case t.JSON:return"json";case t.CSS:return"css";case t.HTML:return"html";default:return"babel"}}formatWithSimpleFormatters(t){let e=t;return e=this.indentCode(e),e=this.formatQuotes(e),e=this.formatSemicolons(e),e}indentCode(t){const e=t.split("\n");let s=0;const i=this.options.useTabs?"\t":" ".repeat(this.options.tabWidth);return e.map((t=>{const e=t.trim();if(!e)return"";e.includes("}")&&s>0&&s--;const r=i.repeat(s)+e;return e.includes("{")&&s++,r})).join("\n")}formatQuotes(t){return this.options.singleQuote?t.replace(/"([^"\\]*(?:\\.[^"\\]*)*)"/g,((t,e)=>e.includes("'")?t:`'${e}'`)):t.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g,((t,e)=>e.includes('"')?t:`"${e}"`))}formatSemicolons(t){return this.options.semi?t.replace(/(\w+|\)|\}|\])\s*(\n|$)/g,((t,e,s)=>e.endsWith(";")?t:`${e};${s}`)):t.replace(/;(\s*(\n|$))/g,"$1")}updateOptions(t){this.options={...this.options,...t}}getOptions(){return{...this.options}}setPrettier(t){this.prettier=t}async formatFiles(t,e={}){return d(t,(async(t,e)=>this.format(t,e)),e)}}class g{constructor(t){this.options={singleLine:!0,multiLine:!0,jsxComments:!0,emptyLines:!0,...t}}removeComments(s,i){if(!s.trim())return"";const r=function(s){return[t.JavaScript,t.TypeScript,t.JSX,t.TSX].includes(s)?e.JavaScript:[t.HTML,t.SVG].includes(s)?e.HTML:s===t.XML?e.XML:[t.CSS,t.SCSS,t.LESS].includes(s)?e.CSS:s===t.JSON?e.JSON:s===t.YAML?e.YAML:s===t.Python?e.Python:s===t.Ruby?e.Ruby:s===t.PHP?e.PHP:[t.Java,t.CSharp,t.C,t.CPP,t.Go,t.Swift,t.Kotlin,t.Rust].includes(s)?e.CStyle:[t.Shell,t.PowerShell,t.Batch].includes(s)?e.Shell:s===t.SQL?e.SQL:s===t.Markdown?e.Markdown:s===t.Text?e.Text:e.Unknown}("string"==typeof i&&i in t?i:l(s));try{switch(r){case e.JavaScript:return this.removeJavaScriptComments(s);case e.HTML:return this.removeHTMLComments(s);case e.CSS:return this.removeCSSComments(s);case e.JSON:return this.removeJavaScriptComments(s);case e.Text:return s;default:return this.removeJavaScriptComments(s)}}catch(t){throw new Error(`Failed during comment removal: ${t.message}`)}}removeJavaScriptComments(t){let e=t;try{const t=[];let s=0;e=e.replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1|\/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+\/(?:[gimuy]+\b)?/g,(e=>{const i=`__PRESERVED_ITEM_${s}__`;return t[s]=e,s++,i})),this.options.jsxComments&&(e=e.replace(/\{\/\*[\s\S]*?\*\/\}/g,"")),this.options.multiLine&&(e=e.replace(/\/\*[\s\S]*?\*\//g,"")),this.options.singleLine&&(e=e.replace(/^[ \t]*\/\/.*$/gm,""),e=e.replace(/([^:/])\/\/.*$/gm,"$1"));for(let i=0;i<s;i++){const s=`__PRESERVED_ITEM_${i}__`,r=new RegExp(s,"g");e=e.replace(r,(()=>t[i]))}return this.options.emptyLines&&(e=this.removeEmptyLines(e)),e.trim()}catch(t){throw new Error(`JavaScript comment removal failed: ${t.message}`)}}removeHTMLComments(t){let e=t;try{const t=[];let s=0;e=e.replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g,(e=>{const i=`__PRESERVED_ITEM_${s}__`;return t[s]=e,s++,i})),this.options.multiLine&&(e=e.replace(/<!--[\s\S]*?-->/g,""));for(let i=0;i<s;i++){const s=`__PRESERVED_ITEM_${i}__`,r=new RegExp(s,"g");e=e.replace(r,(()=>t[i]))}return this.options.emptyLines&&(e=this.removeEmptyLines(e)),e.trim()}catch(t){throw new Error(`HTML comment removal failed: ${t.message}`)}}removeCSSComments(t){let e=t;try{const t=[];let s=0;e=e.replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g,(e=>{const i=`__PRESERVED_ITEM_${s}__`;return t[s]=e,s++,i})),this.options.multiLine&&(e=e.replace(/\/\*[\s\S]*?\*\//g,""));for(let i=0;i<s;i++){const s=`__PRESERVED_ITEM_${i}__`,r=new RegExp(s,"g");e=e.replace(r,(()=>t[i]))}return this.options.emptyLines&&(e=this.removeEmptyLines(e)),e.trim()}catch(t){throw new Error(`CSS comment removal failed: ${t.message}`)}}removeEmptyLines(t){let e=t.replace(/^\s*[\r\n]/gm,"");return e=e.replace(/\n(\s*)\n(\s*)\n/g,"\n$2\n"),e=e.replace(/^(\s*\n)+/,""),e=e.replace(/(\n\s*)+$/,""),e}updateOptions(t){this.options={...this.options,...t}}getOptions(){return{...this.options}}async cleanFiles(t,e={}){return d(t,(async(t,e)=>this.removeComments(t,e)),e)}}class S{constructor(t){this.startTime=0,this.elapsedTime=0,this.isRunning=!1,this.intervalId=null,this.sessionHistory=[],this.currentSession=null,this.onTickCallback=null,this.onTickCallback=(null==t?void 0:t.onTick)||null,this.tickInterval=(null==t?void 0:t.tickInterval)||100}start(){this.isRunning||(this.startTime=Date.now()-this.elapsedTime,this.isRunning=!0,this.startInterval(),this.currentSession||(this.currentSession={id:Date.now(),startTime:new Date,duration:0,textSnapshots:[]}))}pause(){this.isRunning&&(this.clearInterval(),this.isRunning=!1,this.currentSession&&(this.currentSession.duration=this.elapsedTime))}stop(){this.clearInterval(),this.isRunning=!1,this.currentSession&&(this.currentSession.duration=this.elapsedTime,this.currentSession.endTime=new Date,this.sessionHistory.push(this.currentSession),this.currentSession=null),this.elapsedTime=0}reset(){this.clearInterval(),this.isRunning=!1,this.elapsedTime=0,this.currentSession=null}takeTextSnapshot(t){this.currentSession&&this.currentSession.textSnapshots.push({timestamp:new Date,text:t,elapsedTime:this.elapsedTime})}calculateWritingSpeed(){if(!this.currentSession||this.currentSession.textSnapshots.length<2)return{wordsPerMinute:0,charactersPerMinute:0,totalWords:0,totalCharacters:0,elapsedTimeMs:this.elapsedTime};const t=this.currentSession.textSnapshots,e=t[0],s=t[t.length-1],i=(s.elapsedTime-e.elapsedTime)/6e4;if(i<=0)return{wordsPerMinute:0,charactersPerMinute:0,totalWords:0,totalCharacters:0,elapsedTimeMs:this.elapsedTime};const r=""===e.text.trim()?0:e.text.trim().split(/\s+/).length,n=""===s.text.trim()?0:s.text.trim().split(/\s+/).length,a=Math.max(0,n-r),o=e.text.length,l=s.text.length,c=Math.max(0,l-o);return{wordsPerMinute:Math.round(a/i),charactersPerMinute:Math.round(c/i),totalWords:a,totalCharacters:c,elapsedTimeMs:this.elapsedTime}}get wpm(){const t=this.calculateWritingSpeed();return t?t.wordsPerMinute:0}get words(){const t=this.calculateWritingSpeed();return t?t.totalWords:0}getSessionHistory(){return[...this.sessionHistory]}getElapsedTime(){return this.elapsedTime}getFormattedTime(){return this.formatTime(this.elapsedTime)}isTimerRunning(){return this.isRunning}onTick(t){this.onTickCallback=t}formatTime(t){const e=Math.floor(t/1e3),s=Math.floor(e/3600),i=Math.floor(e%3600/60),r=e%60;return`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}`}startInterval(){this.intervalId=setInterval((()=>{this.elapsedTime=Date.now()-this.startTime,this.onTickCallback&&this.onTickCallback(this.elapsedTime)}),this.tickInterval)}clearInterval(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}}class f{constructor(t="",e=200,s=25,i=60,r){this.text=t,this.wordsPerMinute=e,this.handwritingWpm=s,this.keyboardWpm=i,this.stats=this.calculateStats(),this.handwritingTimer=new S(r)}setText(t){this.text=t,this.stats=this.calculateStats()}getText(){return this.text}setReadingSpeed(t){this.wordsPerMinute=t,this.stats=this.calculateStats()}getReadingSpeed(){return this.wordsPerMinute}getStats(){return{...this.stats}}getCharacterCount(){return this.stats.characters}getCharacterCountNoSpaces(){return this.stats.charactersNoSpaces}getWordCount(){return this.stats.words}getSentenceCount(){return this.stats.sentences}getParagraphCount(){return this.stats.paragraphs}getReadingTime(){return this.stats.readingTime}getHandwritingTime(){return this.stats.handwritingTime||"~0 min"}getKeyboardTime(){return this.stats.keyboardTime||"~0 min"}setHandwritingSpeed(t){this.handwritingWpm=t,this.stats=this.calculateStats()}getHandwritingSpeed(){return this.handwritingWpm}setKeyboardSpeed(t){this.keyboardWpm=t,this.stats=this.calculateStats()}getKeyboardSpeed(){return this.keyboardWpm}calculateStats(){const t=this.text.length,e=this.text.replace(/\s/g,"").length,s=""===this.text.trim()?0:this.text.trim().split(/\s+/).length,i=(t,e)=>{if(0===t)return"~0 min";const s=t/e;return this.formatTimeValue(s)};return{characters:t,charactersNoSpaces:e,words:s,sentences:""===this.text?0:this.text.split(/[.!?]+/).filter((t=>t.trim().length>0)).length,paragraphs:""===this.text?0:this.text.split(/\n\s*\n/).filter((t=>t.trim().length>0)).length,readingTime:i(s,this.wordsPerMinute),handwritingTime:this.estimateHandwritingTime(s,t),keyboardTime:i(s,this.keyboardWpm)}}formatTimeValue(t){if(t<1)return"< 1 min";if(t<60)return`~${Math.ceil(t)} min`;return`~${Math.floor(t/60)}h ${Math.ceil(t%60)}m`}estimateHandwritingTime(t,e){const s=t>0?e/t:0,i=t/(this.handwritingWpm/(1*Math.min(1.5,Math.max(1,s/5))));return this.formatTimeValue(i)}getWordFrequency(){if(!this.text.trim())return{};const t={},e=this.text.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter((t=>t.length>0));for(const s of e)t[s]=(t[s]||0)+1;return t}getMostFrequentWords(t=10){const e=this.getWordFrequency();return Object.entries(e).sort(((t,e)=>e[1]-t[1])).slice(0,t)}getReadabilityScore(){if(!this.text.trim())return 100;const t=this.stats.words,e=this.stats.sentences;if(0===t||0===e)return 100;const s=206.835-t/e*1.015-this.countSyllables()/t*84.6;return Math.max(0,Math.min(100,s))}countSyllables(){var t;if(!this.text.trim())return 0;const e=this.text.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter((t=>t.length>0));let s=0;for(const i of e){let e=(null===(t=i.match(/[aeiouy]{1,2}/g))||void 0===t?void 0:t.length)||0;i.length>3&&i.endsWith("e")&&e--,s+=Math.max(1,e)}return s}startWritingSession(){this.handwritingTimer.start()}pauseWritingSession(){this.handwritingTimer.pause()}stopWritingSession(){this.handwritingTimer.stop()}resetWritingSession(){this.handwritingTimer.reset()}updateText(t){this.handwritingTimer.takeTextSnapshot(t),this.setText(t)}getWritingSpeed(){return this.handwritingTimer.calculateWritingSpeed()}getWritingSessionHistory(){return this.handwritingTimer.getSessionHistory()}getElapsedTime(){return this.handwritingTimer.getElapsedTime()}getFormattedElapsedTime(){return this.handwritingTimer.getFormattedTime()}isTimerRunning(){return this.handwritingTimer.isTimerRunning()}onTimerTick(t){this.handwritingTimer.onTick(t)}async analyzeFiles(t,e={}){const s=await u(t,e),i=[];for(const t of s)try{const{content:e,fileType:s}=h(t),r=e.length;if(!e.trim()){i.push({path:t,success:!0,fileType:s,originalSize:r,newSize:r,diffSize:0,diffPercentage:0,stats:{characters:0,charactersNoSpaces:0,words:0,sentences:0,paragraphs:0,readingTime:"0 min",handwritingTime:"0 min",keyboardTime:"0 min"},frequentWords:[],readabilityScore:100});continue}this.setText(e);const n=this.getStats(),a=this.getMostFrequentWords(10),o=this.getReadabilityScore();i.push({path:t,success:!0,fileType:s,originalSize:r,newSize:r,diffSize:0,diffPercentage:0,stats:n,frequentWords:a,readabilityScore:o})}catch(e){i.push({path:t,success:!1,error:e.message})}return i}}class y{constructor(t=!1,e=!1){this.silent=t,this.verboseMode=e,this.spinner=null}log(t){this.silent||console.log(t)}verbose(t){!this.silent&&this.verboseMode&&console.log(n.gray(`[verbose] ${t}`))}info(t){this.silent||console.log(n.blue("ℹ ")+t)}success(t){this.silent||console.log(n.green("✓ ")+t)}warn(t){this.silent||console.log(n.yellow("⚠ ")+t)}error(t){this.silent||console.log(n.red("✗ ")+t)}startSpinner(t){this.silent||(this.spinner=a({text:t,color:"cyan",spinner:"dots"}).start())}stopSpinnerSuccess(t){!this.silent&&this.spinner&&this.spinner.isSpinning&&(this.spinner.succeed(t),this.spinner=null)}stopSpinnerError(t){!this.silent&&this.spinner&&this.spinner.isSpinning&&(this.spinner.fail(t),this.spinner=null)}logResults(t,e){if(this.silent)return;const s=t.filter((t=>t.success)).length,i=t.length-s;this.log("\n"+n.bold("Results:")),this.log(`${n.green(`${s} files`)} processed successfully`),i>0&&(this.log(`${n.red(`${i} files`)} failed to process`),this.log("\n"+n.bold("Errors:")),t.filter((t=>!t.success)).forEach((t=>{this.log(` ${n.red("✗")} ${t.path}: ${t.error}`)})));const r=t.filter((t=>t.success));if(r.length>0){const t=r.reduce(((t,e)=>t+(e.originalSize||0)),0),e=r.reduce(((t,e)=>t+(e.newSize||0)),0),s=t-e,i=t>0?s/t*100:0;this.log("\n"+n.bold("Size Changes:")),this.log(` Original: ${w(t)}`),this.log(` New: ${w(e)}`),s>0?this.log(` Reduced by: ${n.green(w(s))} (${i.toFixed(2)}%)`):s<0?this.log(` Increased by: ${n.yellow(w(Math.abs(s)))} (${Math.abs(i).toFixed(2)}%)`):this.log(" No size change")}this.log("\n"+n.bold.green(`${e} completed.`))}}function w(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}function T(t){return t.split(",").map((t=>t.trim()))}function v(t,e){const s=t.filter((t=>t.success&&t.stats&&t.stats[e]));if(0===s.length)return"~0 min";if("handwritingTime"===e){const t=s.reduce(((t,e)=>t+e.stats.words),0),e=s.reduce(((t,e)=>t+e.stats.characters),0),i=t>0?e/t:0;return x(t/(25/(Math.min(1.5,Math.max(1,i/5))*1)))}const i=s.map((t=>{const s=t.stats[e];if(s.includes("h")){return 60*(parseInt(s.split("h")[0].replace(/[^0-9]/g,""),10)||0)+(parseInt(s.split("h")[1].replace(/[^0-9]/g,""),10)||0)}return parseInt(s.replace(/[^0-9]/g,""),10)||0}));return x(i.reduce(((t,e)=>t+e),0)/i.length)}function x(t){if(t<1)return"< 1 min";if(t<60)return`~${Math.ceil(t)} min`;return`~${Math.floor(t/60)}h ${Math.ceil(t%60)}m`}exports.createAnalyzeCommand=function(){const t=new s.Command("devtools-analyze");return t.description("Analyze text content in files").argument("<patterns...>",'File patterns to analyze (e.g., "src/**/*.md")').option("--summary","Show summary only",!1).option("--ignore <pattern>","Files to ignore (comma-separated)",T).option("--output <path>","Write report to file").option("--silent","Suppress output",!1).action((async(t,e)=>{const s=new y(e.silent);try{const r=new f;s.startSpinner("Analyzing files...");const n=await r.analyzeFiles(t,{silent:e.silent,ignore:e.ignore});if(s.stopSpinnerSuccess(`Analyzed ${n.length} files`),!e.silent){e.summary||(s.log("\nDetailed Results:"),n.filter((t=>t.success)).forEach((t=>{var e;s.log(`\nFile: ${t.path}`),t.stats&&(s.log(` Characters: ${t.stats.characters}`),s.log(` Words: ${t.stats.words}`),s.log(` Sentences: ${t.stats.sentences}`),s.log(` Paragraphs: ${t.stats.paragraphs}`),s.log(` Reading Time: ${t.stats.readingTime}`),s.log(` Handwriting Time: ${t.stats.handwritingTime||"~0 min"}`),s.log(` Keyboard Time: ${t.stats.keyboardTime||"~0 min"}`),s.log(` Readability Score: ${null===(e=t.readabilityScore)||void 0===e?void 0:e.toFixed(2)}/100`),t.frequentWords&&t.frequentWords.length>0&&(s.log(" Most Frequent Words:"),t.frequentWords.forEach((([t,e])=>{s.log(` "${t}": ${e} occurrences`)}))))})));const t=n.filter((t=>t.success&&t.stats)).reduce(((t,e)=>{var s;return t+((null===(s=e.stats)||void 0===s?void 0:s.words)||0)}),0),i=n.filter((t=>t.success&&t.stats)).reduce(((t,e)=>{var s;return t+((null===(s=e.stats)||void 0===s?void 0:s.characters)||0)}),0),r=n.filter((t=>t.success&&void 0!==t.readabilityScore)).reduce(((t,e)=>t+(e.readabilityScore||0)),0)/n.filter((t=>t.success&&void 0!==t.readabilityScore)).length,a=v(n,"readingTime"),o=v(n,"handwritingTime"),l=v(n,"keyboardTime");s.log("\nSummary:"),s.log(` Total Files: ${n.length}`),s.log(` Total Words: ${t}`),s.log(` Total Characters: ${i}`),s.log(` Average Readability: ${r.toFixed(2)}/100`),s.log(` Estimated Reading Time: ${a}`),s.log(` Estimated Handwriting Time: ${o}`),s.log(` Estimated Keyboard Time: ${l}`)}if(e.output){const t={summary:{totalFiles:n.length,successfulFiles:n.filter((t=>t.success)).length,failedFiles:n.filter((t=>!t.success)).length,totalWords:n.filter((t=>t.success&&t.stats)).reduce(((t,e)=>{var s;return t+((null===(s=e.stats)||void 0===s?void 0:s.words)||0)}),0),totalCharacters:n.filter((t=>t.success&&t.stats)).reduce(((t,e)=>{var s;return t+((null===(s=e.stats)||void 0===s?void 0:s.characters)||0)}),0),averageReadability:n.filter((t=>t.success&&void 0!==t.readabilityScore)).reduce(((t,e)=>t+(e.readabilityScore||0)),0)/n.filter((t=>t.success&&void 0!==t.readabilityScore)).length,estimatedReadingTime:n.filter((t=>{var e;return t.success&&(null===(e=t.stats)||void 0===e?void 0:e.readingTime)})).map((t=>{var e;return null===(e=t.stats)||void 0===e?void 0:e.readingTime})).join(", "),estimatedHandwritingTime:n.filter((t=>{var e;return t.success&&(null===(e=t.stats)||void 0===e?void 0:e.handwritingTime)})).map((t=>{var e;return null===(e=t.stats)||void 0===e?void 0:e.handwritingTime})).join(", "),estimatedKeyboardTime:n.filter((t=>{var e;return t.success&&(null===(e=t.stats)||void 0===e?void 0:e.keyboardTime)})).map((t=>{var e;return null===(e=t.stats)||void 0===e?void 0:e.keyboardTime})).join(", ")},files:n};i.writeFileSync(e.output,JSON.stringify(t,null,2)),s.success(`Report written to ${e.output}`)}}catch(t){s.stopSpinnerError("Failed to analyze files"),s.error(t.message),process.exit(1)}})),t},exports.createBeautifyCommand=function(){const t=new s.Command("devtools-beautify");return t.description("Format and beautify code files").argument("<patterns...>",'File patterns to beautify (e.g., "src/**/*.js")').option("--config <path>","Path to prettier config").option("--ignore <pattern>","Files to ignore (comma-separated)",T).option("--write","Write changes to files",!0).option("--silent","Suppress output",!1).action((async(t,e)=>{const s=new y(e.silent);try{let r={};if(e.config){const t=o.resolve(e.config);i.existsSync(t)?(r=JSON.parse(i.readFileSync(t,"utf8")),s.info(`Loaded prettier config from ${t}`)):s.warn(`Config file not found: ${t}`)}const n=new p(r);s.startSpinner("Beautifying files...");const a=await n.formatFiles(t,{write:e.write,silent:e.silent,ignore:e.ignore});s.stopSpinnerSuccess(`Processed ${a.length} files`),s.logResults(a,"Beautification")}catch(t){s.stopSpinnerError("Failed to beautify files"),s.error(t.message),process.exit(1)}})),t},exports.createCleanCommand=function(){const t=new s.Command("devtools-clean");return t.description("Remove comments from code files").argument("<patterns...>",'File patterns to clean (e.g., "src/**/*.js")').option("--single-line","Remove single-line comments",!0).option("--multi-line","Remove multi-line comments",!0).option("--jsx","Remove JSX comments",!0).option("--empty-lines","Remove empty lines",!0).option("--ignore <pattern>","Files to ignore (comma-separated)",T).option("--write","Write changes to files",!0).option("--silent","Suppress output",!1).action((async(t,e)=>{const s=new y(e.silent);try{const i=new g({singleLine:e.singleLine,multiLine:e.multiLine,jsxComments:e.jsx,emptyLines:e.emptyLines});s.startSpinner("Removing comments...");const r=await i.cleanFiles(t,{write:e.write,silent:e.silent,ignore:e.ignore});s.stopSpinnerSuccess(`Processed ${r.length} files`),s.logResults(r,"Comment removal")}catch(t){s.stopSpinnerError("Failed to remove comments"),s.error(t.message),process.exit(1)}})),t}; //# sourceMappingURL=commands.js.map