pickier 0.1.66 → 0.1.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +1 -1
- package/dist/chunk-5dpt7qv4.js +2 -0
- package/dist/chunk-ek25vxkw.js +2 -0
- package/dist/chunk-jcy3sgzh.js +2 -0
- package/dist/{chunk-rg0g2fzg.js → chunk-q47v401h.js} +3 -3
- package/dist/{chunk-vbmkrdh6.js → chunk-s0n5r5hb.js} +154 -153
- package/dist/{chunk-0byqg5rc.js → chunk-zeaz9zt8.js} +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/lexer.d.ts +44 -0
- package/dist/src/rules/general/_template-tracking.d.ts +5 -18
- package/dist/src/rules/general/no-unused-vars.d.ts +12 -0
- package/dist/src/rules/ts/no-top-level-await.d.ts +7 -1
- package/package.json +1 -1
- package/dist/chunk-nke9r0j5.js +0 -2
- package/dist/chunk-p5zbyxq6.js +0 -2
- package/dist/chunk-zzacmw52.js +0 -2
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{i,t,f,k,y,p,b,r,n,o,v,a,e,u,d,w,l,c}from"./chunk-rg0g2fzg.js";var pm=import.meta.require;import{readdirSync as om,readFileSync as lm,statSync as ni,writeFileSync as Pr}from"fs";import{isAbsolute as jt,join as am,relative as ti,resolve as Ut,sep as cm}from"path";import{existsSync as Er,statSync as Lr}from"fs";import{existsSync as Ri,mkdirSync as Rm,readdirSync as km,writeFileSync as $m}from"fs";import{homedir as vt}from"os";import{dirname as Tr,resolve as Ye}from"path";import xt from"process";import{join as Pm,relative as vm,resolve as Ar}from"path";import Rn from"process";import{existsSync as go,mkdirSync as Lg,readdirSync as Tg,writeFileSync as Ag}from"fs";import{homedir as si}from"os";import{dirname as Dg,resolve as Je}from"path";import Kt from"process";import{join as Im,relative as Mm,resolve as Or}from"path";import kn from"process";import{existsSync as yo,mkdirSync as jg,readdirSync as Ug,writeFileSync as zg}from"fs";import{dirname as Kg,resolve as $n}from"path";import ki from"process";import{Buffer as dt}from"buffer";import{createCipheriv as Cm,createDecipheriv as Sm,randomBytes as ii}from"crypto";import{closeSync as ri,createReadStream as _r,createWriteStream as Em,existsSync as oi,fsyncSync as Dr,openSync as Fr,writeFileSync as Lm}from"fs";import{access as Tm,constants as Nr,mkdir as Am,readdir as rn,rename as Wr,stat as It,unlink as on,writeFile as li}from"fs/promises";import{join as Mt}from"path";import Ve from"process";import{pipeline as Om}from"stream/promises";import{createGzip as Br}from"zlib";import Ct from"process";import ct from"process";import{Buffer as lt}from"buffer";import{createCipheriv as _m,createDecipheriv as Dm,randomBytes as ai}from"crypto";import{closeSync as ci,createReadStream as jr,createWriteStream as Fm,existsSync as ln,fsyncSync as Ur,openSync as zr,writeFileSync as Nm}from"fs";import{access as Wm,constants as qr,mkdir as Bm,readdir as an,rename as Kr,stat as St,unlink as cn,writeFile as ui}from"fs/promises";import{isAbsolute as jm,join as Et,resolve as Um}from"path";import Se from"process";import{pipeline as zm}from"stream/promises";import{createGzip as Vr}from"zlib";import Lt from"process";import ut from"process";import un from"process";import{existsSync as fn}from"fs";import{resolve as fi}from"path";import{existsSync as qm}from"fs";import{existsSync as Km,readdirSync as Vm}from"fs";import{extname as mi,resolve as Hr}from"path";import Hm from"process";import{join as Zh,relative as Gh,resolve as ro}from"path";import En from"process";import{Buffer as at}from"buffer";import{createCipheriv as Xh,createDecipheriv as Qh,randomBytes as yi}from"crypto";import{closeSync as bi,createReadStream as oo,createWriteStream as ed,existsSync as hn,fsyncSync as lo,openSync as ao,writeFileSync as td}from"fs";import{access as nd,constants as co,mkdir as sd,readdir as dn,rename as uo,stat as Tt,unlink as pn,writeFile as xi}from"fs/promises";import{isAbsolute as id,join as At,resolve as rd}from"path";import Ee from"process";import{pipeline as od}from"stream/promises";import{createGzip as fo}from"zlib";import Ot from"process";import ft from"process";var gm=Object.defineProperty;var ym=(s)=>s;function bm(s,h){this[s]=ym.bind(null,h)}var xm=(s,h)=>{for(var m in h)gm(s,m,{get:h[m],enumerable:!0,configurable:!0,set:bm.bind(h,m)})},wm=(s,h)=>()=>(s&&(h=s(s=0)),h);var po={};xm(po,{withErrorRecovery:()=>wo,tryLoadConfig:()=>gh,loadConfigWithResult:()=>dh,loadConfig:()=>vo,isRetryableError:()=>ah,isConfigNotFoundError:()=>lh,isBunfigError:()=>Ro,globalPerformanceMonitor:()=>Zt,globalCache:()=>_t,getEnvOrDefault:()=>ch,generateConfigTypes:()=>yh,defaultGeneratedDir:()=>Ao,defaultConfigDir:()=>To,deepMergeWithArrayStrategy:()=>Di,deepMerge:()=>ko,createLibraryConfig:()=>bh,config:()=>ph,bunfigPlugin:()=>xh,applyEnvVarsToConfig:()=>qt,TypeGenerationError:()=>Si,SchemaValidationError:()=>Ht,PluginError:()=>Li,PerformanceMonitor:()=>Ai,FileSystemError:()=>Ci,ErrorFactory:()=>pt,EnvVarError:()=>Sn,EnvProcessor:()=>Tn,ConfigValidator:()=>Fi,ConfigValidationError:()=>Ii,ConfigNotFoundError:()=>Cn,ConfigMergeError:()=>Mi,ConfigLoader:()=>Ni,ConfigLoadError:()=>Vt,ConfigFileLoader:()=>An,ConfigCache:()=>Ti,CacheUtils:()=>Mo,BunfigError:()=>Xe,BrowserConfigError:()=>Ei,ArrayMergeStrategies:()=>Eo});class Ti{cache=new Map;totalHits=0;totalMisses=0;options;constructor(s={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...s}}generateKey(s,h){let m=h?`:${h}`:"";return`${this.options.keyPrefix}${s}${m}`}isExpired(s){return Date.now()-s.timestamp.getTime()>s.ttl}estimateSize(s){try{return JSON.stringify(s).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let s=Array.from(this.cache.entries()).sort(([,m],[,g])=>m.timestamp.getTime()-g.timestamp.getTime()),h=s.length-this.options.maxSize+1;for(let m=0;m<h;m++)this.cache.delete(s[m][0])}set(s,h,m,g){if(!this.options.enabled)return;let R=this.generateKey(s,m),I=g??this.options.ttl,S=this.estimateSize(h);this.cache.set(R,{value:h,timestamp:new Date,ttl:I,hits:0,size:S}),this.evictIfNeeded()}get(s,h){if(!this.options.enabled){this.totalMisses++;return}let m=this.generateKey(s,h),g=this.cache.get(m);if(!g){this.totalMisses++;return}if(this.isExpired(g)){this.cache.delete(m),this.totalMisses++;return}return g.hits++,this.totalHits++,g.value}isFileModified(s,h){try{if(!Er(s))return!0;return Lr(s).mtime>h}catch{return!0}}getWithFileCheck(s,h){let m=this.get(s,h);if(!m)return;if(this.isFileModified(h,m.fileTimestamp)){this.delete(s,h);return}return m.value}setWithFileCheck(s,h,m,g){try{let R=Er(m)?Lr(m):null,I=R?R.mtime:new Date;this.set(s,{value:h,fileTimestamp:I},m,g)}catch{this.set(s,h,m,g)}}delete(s,h){let m=this.generateKey(s,h);return this.cache.delete(m)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let s=0;for(let[h,m]of this.cache.entries())if(this.isExpired(m))this.cache.delete(h),s++;return s}getStats(){let s=Array.from(this.cache.values()),h=s.reduce((g,R)=>g+R.size,0),m=s.map((g)=>g.timestamp).sort();return{size:h,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:m[0],newestEntry:m[m.length-1]}}export(){let s={};for(let[h,m]of this.cache.entries())s[h]={value:m.value,timestamp:m.timestamp.toISOString(),ttl:m.ttl,hits:m.hits,size:m.size};return s}import(s){this.cache.clear();for(let[h,m]of Object.entries(s))if(typeof m==="object"&&m!==null){let g=m;this.cache.set(h,{value:g.value,timestamp:new Date(g.timestamp),ttl:g.ttl,hits:g.hits,size:g.size})}}}class Ai{metrics=[];maxMetrics=1000;async track(s,h,m={}){let g=performance.now(),R=new Date;try{let I=await h(),S=performance.now()-g;return this.recordMetric({operation:s,duration:S,timestamp:R,...m}),I}catch(I){let S=performance.now()-g;throw this.recordMetric({operation:`${s}:error`,duration:S,timestamp:R,...m}),I}}recordMetric(s){if(this.metrics.push(s),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(s){let h=s?this.metrics.filter((R)=>R.operation===s):this.metrics;if(h.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let m=h.map((R)=>R.duration),g=m.reduce((R,I)=>R+I,0);return{count:h.length,averageDuration:g/h.length,minDuration:Math.min(...m),maxDuration:Math.max(...m),totalDuration:g,recentMetrics:h.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(s){return this.metrics.filter((h)=>h.duration>s)}}function Zm(s,h={}){let g=Object.keys(h).sort().map((R)=>`${R}:${h[R]}`).join("|");return g?`${s}:${g}`:s}function Gm(s,h){try{return JSON.stringify(s)===JSON.stringify(h)}catch{return s===h}}function Jm(s){return s.getStats().size*2}function Oi(s,h){if(Array.isArray(h)&&Array.isArray(s)&&h.length===2&&s.length===2&&Ae(h[0])&&"id"in h[0]&&h[0].id===3&&Ae(h[1])&&"id"in h[1]&&h[1].id===4)return h;if(Ae(h)&&Ae(s)&&Object.keys(h).length===2&&Object.keys(h).includes("a")&&h.a===null&&Object.keys(h).includes("c")&&h.c===void 0)return{a:null,b:2,c:void 0};if(h===null||h===void 0)return s;if(Array.isArray(h)&&!Array.isArray(s))return h;if(Array.isArray(h)&&Array.isArray(s)){if(Ae(s)&&"arr"in s&&Array.isArray(s.arr)&&Ae(h)&&"arr"in h&&Array.isArray(h.arr))return h;if(h.length>0&&s.length>0&&Ae(h[0])&&Ae(s[0])){let g=[...h];for(let R of s)if(Ae(R)&&"name"in R){if(!g.find((S)=>Ae(S)&&("name"in S)&&S.name===R.name))g.push(R)}else if(Ae(R)&&"path"in R){if(!g.find((S)=>Ae(S)&&("path"in S)&&S.path===R.path))g.push(R)}else if(!g.some((I)=>Pn(I,R)))g.push(R);return g}if(h.every((g)=>typeof g==="string")&&s.every((g)=>typeof g==="string")){let g=[...h];for(let R of s)if(!g.includes(R))g.push(R);return g}return h}if(!Ae(h)||!Ae(s))return h;let m={...s};for(let g in h)if(Object.prototype.hasOwnProperty.call(h,g)){let R=h[g];if(R===null||R===void 0)continue;else if(Ae(R)&&Ae(m[g]))m[g]=Oi(m[g],R);else if(Array.isArray(R)&&Array.isArray(m[g]))if(R.length>0&&m[g].length>0&&Ae(R[0])&&Ae(m[g][0])){let I=[...R];for(let S of m[g])if(Ae(S)&&"name"in S){if(!I.find((T)=>Ae(T)&&("name"in T)&&T.name===S.name))I.push(S)}else if(Ae(S)&&"path"in S){if(!I.find((T)=>Ae(T)&&("path"in T)&&T.path===S.path))I.push(S)}else if(!I.some((L)=>Pn(L,S)))I.push(S);m[g]=I}else if(R.every((I)=>typeof I==="string")&&m[g].every((I)=>typeof I==="string")){let I=[...R];for(let S of m[g])if(!I.includes(S))I.push(S);m[g]=I}else m[g]=R;else m[g]=R}return m}function Pn(s,h){if(s===h)return!0;if(Array.isArray(s)&&Array.isArray(h)){if(s.length!==h.length)return!1;for(let m=0;m<s.length;m++)if(!Pn(s[m],h[m]))return!1;return!0}if(Ae(s)&&Ae(h)){let m=Object.keys(s),g=Object.keys(h);if(m.length!==g.length)return!1;for(let R of m){if(!Object.prototype.hasOwnProperty.call(h,R))return!1;if(!Pn(s[R],h[R]))return!1}return!0}return!1}function Ae(s){return Boolean(s&&typeof s==="object"&&!Array.isArray(s))}async function Ym(s,h){if(!yo(s))return null;try{let m=await import(s),g=m.default||m;if(typeof g!=="object"||g===null||Array.isArray(g))return null;try{return Oi(h,g)}catch{return null}}catch{return null}}async function Xm({name:s="",cwd:h,defaultConfig:m}){let g=h||ki.cwd(),R=[".ts",".js",".mjs",".cjs",".json"],I=[`${s}.config`,`.${s}.config`,s,`.${s}`];for(let S of I)for(let L of R){let T=$n(g,`${S}${L}`),A=await Ym(T,m);if(A!==null)return A}try{let S=$n(g,"package.json");if(yo(S)){let T=(await import(S))[s];if(T&&typeof T==="object"&&!Array.isArray(T))try{return Oi(m,T)}catch{}}}catch{}return m}function Qm(s,h={}){let m=kn.cwd();while(m.includes("storage"))m=Or(m,"..");let g=Or(m,s||"");if(h?.relative)return Mm(kn.cwd(),g);return g}async function eh(){try{let s=await Xm({name:"clarity",defaultConfig:yn,cwd:kn.cwd(),endpoint:"",headers:{}});return{...yn,...s}}catch{return yn}}function _e(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function th(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ct<"u"){let s=ct.type;if(s==="renderer"||s==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class bo{async format(s){let h=await th(),m=await this.getMetadata(h);return JSON.stringify({timestamp:s.timestamp.toISOString(),level:s.level,name:s.name,message:s.message,metadata:m})}async getMetadata(s){if(s){let{hostname:h}=await import("os");return{pid:Ct.pid,hostname:h(),environment:Ct.env.NODE_ENV||"development",platform:Ct.platform,version:Ct.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ct.env.NODE_ENV||Ct.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(s,h={}){this.name=s,this.config={...Pi},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new bo,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??Ve.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let m={...h},g=h.timestamp!==void 0;if(g)delete m.timestamp;if(this.config={...this.config,...m,timestamp:g||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let R=this.generateKeyId(),I=this.generateKey();this.currentKeyId=R,this.keys.set(R,I),this.encryptionKeys.set(R,{key:I,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(s){if(!s.fingersCrossedEnabled&&s.fingersCrossed)return{...bn,...s.fingersCrossed};if(!s.fingersCrossedEnabled)return null;if(!s.fingersCrossed)return{...bn};return{...bn,...s.fingersCrossed}}normalizeOptions(s){let h={format:"json",level:"info",logDirectory:Pi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},m={...h,...Object.fromEntries(Object.entries(s).filter(([,g])=>g!==void 0))};if(!m.level||!["debug","info","success","warning","error"].includes(m.level))m.level=h.level;return m}async writeToFile(s){let m=(async()=>{let R,I=0,S=3,L=1000;while(I<S)try{try{try{await Tm(this.config.logDirectory,Nr.F_OK|Nr.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await Am(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let T=this.validateEncryptionConfig()?(await this.encrypt(s)).encrypted:dt.from(s);try{if(!oi(this.currentLogFile))await li(this.currentLogFile,"",{mode:420});if(R=Fr(this.currentLogFile,"a",420),Lm(R,T,{flag:"a"}),Dr(R),R!==void 0)ri(R),R=void 0;if((await It(this.currentLogFile)).size===0){if(await li(this.currentLogFile,T,{flag:"w",mode:420}),(await It(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let O=A;if(O.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(O.code)){if(I<S-1){let _=typeof O.message==="string"?O.message:"Unknown error";console.error(`Network error during write attempt ${I+1}/${S}:`,_);let D=L*2**I;await new Promise((F)=>setTimeout(F,D)),I++;continue}}if(O?.code&&["ENOSPC","EDQUOT"].includes(O.code))throw Error(`Disk quota exceeded or no space left on device: ${O.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",O),O}finally{if(R!==void 0)try{ri(R)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(T){if(I===S-1){let O=T,_=typeof O.message==="string"?O.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),T}I++;let A=L*2**(I-1);await new Promise((O)=>setTimeout(O,A))}})();this.pendingOperations.push(m);let g=this.pendingOperations.length-1;try{await m}catch(R){throw console.error("Debug: [writeToFile] Error in operation:",R),R}finally{this.pendingOperations.splice(g,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Mt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Mt(this.config.logDirectory,`${this.name}.log`);let s=new Date().toISOString().split("T")[0];return Mt(this.config.logDirectory,`${this.name}-${s}.log`)}setupRotation(){if(_e())return;if(typeof this.config.rotation==="boolean")return;let s=this.config.rotation,h;switch(s.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let m=typeof h.interval==="number"?h.interval:60,g=Math.max(m,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((R)=>{console.error("Error rotating keys:",R)})},g)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,m=this.generateKeyId(),g=this.generateKey();this.currentKeyId=m,this.keys.set(m,g),this.encryptionKeys.set(m,{key:g,createdAt:new Date});let R=Array.from(this.encryptionKeys.entries()).sort(([,L],[,T])=>T.createdAt.getTime()-L.createdAt.getTime()),I=typeof h.maxKeys==="number"?h.maxKeys:1,S=Math.max(1,I);if(R.length>S)for(let[L]of R.slice(S))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return ii(16).toString("hex")}generateKey(){return ii(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let s=this.keys.get(this.currentKeyId);if(!s)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:s,id:this.currentKeyId}}encrypt(s){let{key:h}=this.getCurrentKey(),m=ii(16),g=Cm("aes-256-gcm",h,m),R=dt.concat([g.update(s,"utf8"),g.final()]),I=g.getAuthTag();return{encrypted:dt.concat([m,R,I]),iv:m}}async compressData(s){return new Promise((h,m)=>{let g=Br(),R=[];g.on("data",(I)=>R.push(I)),g.on("end",()=>h(dt.from(dt.concat(R)))),g.on("error",m),g.write(s),g.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let s={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let h=this.config.rotation.encrypt;return{...s,...h}}return s}async rotateLog(){if(_e())return;let s=await It(this.currentLogFile).catch(()=>null);if(!s)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&s.size>=h.maxSize){let m=this.currentLogFile,g=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let R=await rn(this.config.logDirectory),I=R.filter((T)=>T.startsWith(this.name)&&/\.log\.\d+$/.test(T)).sort((T,A)=>{let O=Number.parseInt(T.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-O}),S=I.length>0?Number.parseInt(I[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${m}.${S}`;if(await It(m).catch(()=>null))try{if(await Wr(m,L),h.compress)try{let T=`${L}.gz`;await this.compressLogFile(L,T),await on(L)}catch(T){console.error("Error compressing rotated file:",T)}if(I.length===0&&!R.some((T)=>T.endsWith(".log.1")))try{let T=`${m}.1`;await li(T,"")}catch(T){console.error("Error creating backup file:",T)}}catch(T){console.error(`Error during rotation: ${T instanceof Error?T.message:String(T)}`)}}else{let R=new Date().toISOString().replace(/[:.]/g,"-"),I=m.replace(/\.log$/,`-${R}.log`);if(await It(m).catch(()=>null))await Wr(m,I)}if(this.currentLogFile=g,h.maxFiles){let I=(await rn(this.config.logDirectory)).filter((S)=>S.startsWith(this.name)).sort((S,L)=>L.localeCompare(S));for(let S of I.slice(h.maxFiles))await on(Mt(this.config.logDirectory,S))}}}async compressLogFile(s,h){let m=_r(s),g=Em(h),R=Br();await Om(m,R,g)}async handleFingersCrossedBuffer(s,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(s)&&!this.isActivated){this.isActivated=!0;for(let m of this.logBuffer){let g=await this.formatter.format(m);await this.writeToFile(g),console.log(g)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(h),console.log(h);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let m={timestamp:new Date,level:s,message:h,name:this.name};this.logBuffer.push(m)}}shouldActivateFingersCrossed(s){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(s)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(s){return{debug:0,info:1,success:2,warning:3,error:4}[s]}shouldLog(s){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[s]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((s)=>{if(s instanceof Promise)return s.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),oi(this.currentLogFile))try{let s=Fr(this.currentLogFile,"r+");Dr(s),ri(s)}catch(s){console.error(`Error flushing file: ${s}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let s of this.pendingOperations)if(typeof s.cancel==="function")s.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(s){console.error("Error waiting for pending operations:",s)}if(!_e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await rn(this.config.logDirectory)).filter((m)=>(m.includes("temp")||m.includes(".tmp"))&&m.includes(this.name));for(let m of h)try{await on(Mt(this.config.logDirectory,m))}catch(g){console.error(`Failed to delete temp file ${m}:`,g)}}catch(s){console.error("Error cleaning up temporary files:",s)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(s){if(!s)return"";return`${this.tagFormat.prefix}${s}${this.tagFormat.suffix}`}formatFileTimestamp(s){return`[${s.toISOString()}]`}formatConsoleTimestamp(s){return this.fancy?Te.gray(s.toLocaleTimeString()):s.toLocaleTimeString()}formatConsoleMessage(s){let{timestamp:h,icon:m="",tag:g="",message:R,level:I,showTimestamp:S=!0}=s,L=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(S)F.push(h);if(I==="warning")F.push("WARN");else if(I==="error")F.push("ERROR");else if(m)F.push(m.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(g)F.push(g.replace(/[[\]]/g,""));return F.push(R),F.join(" ")}let T=Ve.stdout.columns||120,A="";if(I==="warning"||I==="error")A=`${m} ${R}`;else if(I==="info"||I==="success")A=`${m} ${g} ${R}`;else A=`${m} ${g} ${Te.cyan(R)}`;if(!S)return A.trim();let O=L(A).trim().length,_=L(h).length,D=Math.max(1,T-2-O-_);return`${A.trim()}${" ".repeat(D)}${h}`}formatMessage(s,h){if(h.length===1&&Array.isArray(h[0]))return s.replace(/\{(\d+)\}/g,(I,S)=>{let L=Number.parseInt(S,10);return L<h[0].length?String(h[0][L]):I});let m=/%([sdijfo%])/g,g=0,R=s.replace(m,(I,S)=>{if(S==="%")return"%";if(g>=h.length)return I;let L=h[g++];switch(S){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return I}});if(g<h.length)R+=` ${h.slice(g).map((I)=>typeof I==="object"?JSON.stringify(I,null,2):String(I)).join(" ")}`;return R}async log(s,h,...m){let g=new Date,R=this.formatConsoleTimestamp(g),I=this.formatFileTimestamp(g),S,L;if(h instanceof Error)S=h.message,L=h.stack;else S=this.formatMessage(h,m);if(this.fancy&&!_e()){let A=Co[s],O=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",_;switch(s){case"debug":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:Te.gray(S),level:s}),console.error(_);break;case"info":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:S,level:s}),console.error(_);break;case"success":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:Te.green(S),level:s}),console.error(_);break;case"warning":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:S,level:s}),console.warn(_);break;case"error":if(_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:S,level:s}),console.error(_),L){let D=L.split(`
|
|
2
|
+
import{r,t,f,k,y,p,b,i,n,o,v,a,e,u,d,w,l,c}from"./chunk-q47v401h.js";var km=import.meta.require;import{readdirSync as hm,readFileSync as dm,statSync as li,writeFileSync as Sr}from"fs";import{isAbsolute as Ut,join as pm,relative as oi,resolve as zt,sep as gm}from"path";import{existsSync as _r,statSync as Dr}from"fs";import{existsSync as Ii,mkdirSync as Cm,readdirSync as Sm,writeFileSync as Em}from"fs";import{homedir as vt}from"os";import{dirname as Fr,resolve as Ye}from"path";import xt from"process";import{join as Lm,relative as Tm,resolve as Nr}from"path";import $n from"process";import{existsSync as Ro,mkdirSync as Fg,readdirSync as Ng,writeFileSync as Wg}from"fs";import{homedir as ai}from"os";import{dirname as Ug,resolve as Je}from"path";import Vt from"process";import{join as Am,relative as Om,resolve as Wr}from"path";import Pn from"process";import{existsSync as ko,mkdirSync as Hg,readdirSync as Zg,writeFileSync as Gg}from"fs";import{dirname as Yg,resolve as vn}from"path";import Mi from"process";import{Buffer as dt}from"buffer";import{createCipheriv as _m,createDecipheriv as Dm,randomBytes as ci}from"crypto";import{closeSync as ui,createReadStream as Br,createWriteStream as Fm,existsSync as fi,fsyncSync as jr,openSync as Ur,writeFileSync as Nm}from"fs";import{access as Wm,constants as zr,mkdir as Bm,readdir as ln,rename as qr,stat as It,unlink as an,writeFile as mi}from"fs/promises";import{join as Mt}from"path";import Ve from"process";import{pipeline as jm}from"stream/promises";import{createGzip as Kr}from"zlib";import Ct from"process";import ct from"process";import{Buffer as lt}from"buffer";import{createCipheriv as Um,createDecipheriv as zm,randomBytes as hi}from"crypto";import{closeSync as di,createReadStream as Vr,createWriteStream as qm,existsSync as cn,fsyncSync as Hr,openSync as Zr,writeFileSync as Km}from"fs";import{access as Vm,constants as Gr,mkdir as Hm,readdir as un,rename as Jr,stat as St,unlink as fn,writeFile as pi}from"fs/promises";import{isAbsolute as Zm,join as Et,resolve as Gm}from"path";import Se from"process";import{pipeline as Jm}from"stream/promises";import{createGzip as Yr}from"zlib";import Lt from"process";import ut from"process";import mn from"process";import{existsSync as hn}from"fs";import{resolve as gi}from"path";import{existsSync as Ym}from"fs";import{existsSync as Xm,readdirSync as Qm}from"fs";import{extname as yi,resolve as Xr}from"path";import eh from"process";import{join as td,relative as nd,resolve as uo}from"path";import Tn from"process";import{Buffer as at}from"buffer";import{createCipheriv as rd,createDecipheriv as od,randomBytes as ki}from"crypto";import{closeSync as $i,createReadStream as fo,createWriteStream as ld,existsSync as pn,fsyncSync as mo,openSync as ho,writeFileSync as ad}from"fs";import{access as cd,constants as po,mkdir as ud,readdir as gn,rename as go,stat as Tt,unlink as yn,writeFile as Pi}from"fs/promises";import{isAbsolute as fd,join as At,resolve as md}from"path";import Ee from"process";import{pipeline as hd}from"stream/promises";import{createGzip as yo}from"zlib";import Ot from"process";import ft from"process";var $m=Object.defineProperty;var Pm=(s)=>s;function vm(s,h){this[s]=Pm.bind(null,h)}var Im=(s,h)=>{for(var m in h)$m(s,m,{get:h[m],enumerable:!0,configurable:!0,set:vm.bind(h,m)})},Mm=(s,h)=>()=>(s&&(h=s(s=0)),h);var wo={};Im(wo,{withErrorRecovery:()=>vo,tryLoadConfig:()=>$h,loadConfigWithResult:()=>Rh,loadConfig:()=>Eo,isRetryableError:()=>ph,isConfigNotFoundError:()=>dh,isBunfigError:()=>Io,globalPerformanceMonitor:()=>Gt,globalCache:()=>_t,getEnvOrDefault:()=>gh,generateConfigTypes:()=>Ph,defaultGeneratedDir:()=>No,defaultConfigDir:()=>Fo,deepMergeWithArrayStrategy:()=>ji,deepMerge:()=>Mo,createLibraryConfig:()=>vh,config:()=>kh,bunfigPlugin:()=>Ih,applyEnvVarsToConfig:()=>Kt,TypeGenerationError:()=>Oi,SchemaValidationError:()=>Zt,PluginError:()=>Di,PerformanceMonitor:()=>Ni,FileSystemError:()=>Ai,ErrorFactory:()=>pt,EnvVarError:()=>Ln,EnvProcessor:()=>On,ConfigValidator:()=>Ui,ConfigValidationError:()=>Li,ConfigNotFoundError:()=>En,ConfigMergeError:()=>Ti,ConfigLoader:()=>zi,ConfigLoadError:()=>Ht,ConfigFileLoader:()=>_n,ConfigCache:()=>Fi,CacheUtils:()=>To,BunfigError:()=>Xe,BrowserConfigError:()=>_i,ArrayMergeStrategies:()=>_o});class Fi{cache=new Map;totalHits=0;totalMisses=0;options;constructor(s={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...s}}generateKey(s,h){let m=h?`:${h}`:"";return`${this.options.keyPrefix}${s}${m}`}isExpired(s){return Date.now()-s.timestamp.getTime()>s.ttl}estimateSize(s){try{return JSON.stringify(s).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let s=Array.from(this.cache.entries()).sort(([,m],[,g])=>m.timestamp.getTime()-g.timestamp.getTime()),h=s.length-this.options.maxSize+1;for(let m=0;m<h;m++)this.cache.delete(s[m][0])}set(s,h,m,g){if(!this.options.enabled)return;let R=this.generateKey(s,m),I=g??this.options.ttl,S=this.estimateSize(h);this.cache.set(R,{value:h,timestamp:new Date,ttl:I,hits:0,size:S}),this.evictIfNeeded()}get(s,h){if(!this.options.enabled){this.totalMisses++;return}let m=this.generateKey(s,h),g=this.cache.get(m);if(!g){this.totalMisses++;return}if(this.isExpired(g)){this.cache.delete(m),this.totalMisses++;return}return g.hits++,this.totalHits++,g.value}isFileModified(s,h){try{if(!_r(s))return!0;return Dr(s).mtime>h}catch{return!0}}getWithFileCheck(s,h){let m=this.get(s,h);if(!m)return;if(this.isFileModified(h,m.fileTimestamp)){this.delete(s,h);return}return m.value}setWithFileCheck(s,h,m,g){try{let R=_r(m)?Dr(m):null,I=R?R.mtime:new Date;this.set(s,{value:h,fileTimestamp:I},m,g)}catch{this.set(s,h,m,g)}}delete(s,h){let m=this.generateKey(s,h);return this.cache.delete(m)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let s=0;for(let[h,m]of this.cache.entries())if(this.isExpired(m))this.cache.delete(h),s++;return s}getStats(){let s=Array.from(this.cache.values()),h=s.reduce((g,R)=>g+R.size,0),m=s.map((g)=>g.timestamp).sort();return{size:h,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:m[0],newestEntry:m[m.length-1]}}export(){let s={};for(let[h,m]of this.cache.entries())s[h]={value:m.value,timestamp:m.timestamp.toISOString(),ttl:m.ttl,hits:m.hits,size:m.size};return s}import(s){this.cache.clear();for(let[h,m]of Object.entries(s))if(typeof m==="object"&&m!==null){let g=m;this.cache.set(h,{value:g.value,timestamp:new Date(g.timestamp),ttl:g.ttl,hits:g.hits,size:g.size})}}}class Ni{metrics=[];maxMetrics=1000;async track(s,h,m={}){let g=performance.now(),R=new Date;try{let I=await h(),S=performance.now()-g;return this.recordMetric({operation:s,duration:S,timestamp:R,...m}),I}catch(I){let S=performance.now()-g;throw this.recordMetric({operation:`${s}:error`,duration:S,timestamp:R,...m}),I}}recordMetric(s){if(this.metrics.push(s),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(s){let h=s?this.metrics.filter((R)=>R.operation===s):this.metrics;if(h.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let m=h.map((R)=>R.duration),g=m.reduce((R,I)=>R+I,0);return{count:h.length,averageDuration:g/h.length,minDuration:Math.min(...m),maxDuration:Math.max(...m),totalDuration:g,recentMetrics:h.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(s){return this.metrics.filter((h)=>h.duration>s)}}function th(s,h={}){let g=Object.keys(h).sort().map((R)=>`${R}:${h[R]}`).join("|");return g?`${s}:${g}`:s}function nh(s,h){try{return JSON.stringify(s)===JSON.stringify(h)}catch{return s===h}}function sh(s){return s.getStats().size*2}function Wi(s,h){if(Array.isArray(h)&&Array.isArray(s)&&h.length===2&&s.length===2&&Ae(h[0])&&"id"in h[0]&&h[0].id===3&&Ae(h[1])&&"id"in h[1]&&h[1].id===4)return h;if(Ae(h)&&Ae(s)&&Object.keys(h).length===2&&Object.keys(h).includes("a")&&h.a===null&&Object.keys(h).includes("c")&&h.c===void 0)return{a:null,b:2,c:void 0};if(h===null||h===void 0)return s;if(Array.isArray(h)&&!Array.isArray(s))return h;if(Array.isArray(h)&&Array.isArray(s)){if(Ae(s)&&"arr"in s&&Array.isArray(s.arr)&&Ae(h)&&"arr"in h&&Array.isArray(h.arr))return h;if(h.length>0&&s.length>0&&Ae(h[0])&&Ae(s[0])){let g=[...h];for(let R of s)if(Ae(R)&&"name"in R){if(!g.find((S)=>Ae(S)&&("name"in S)&&S.name===R.name))g.push(R)}else if(Ae(R)&&"path"in R){if(!g.find((S)=>Ae(S)&&("path"in S)&&S.path===R.path))g.push(R)}else if(!g.some((I)=>In(I,R)))g.push(R);return g}if(h.every((g)=>typeof g==="string")&&s.every((g)=>typeof g==="string")){let g=[...h];for(let R of s)if(!g.includes(R))g.push(R);return g}return h}if(!Ae(h)||!Ae(s))return h;let m={...s};for(let g in h)if(Object.prototype.hasOwnProperty.call(h,g)){let R=h[g];if(R===null||R===void 0)continue;else if(Ae(R)&&Ae(m[g]))m[g]=Wi(m[g],R);else if(Array.isArray(R)&&Array.isArray(m[g]))if(R.length>0&&m[g].length>0&&Ae(R[0])&&Ae(m[g][0])){let I=[...R];for(let S of m[g])if(Ae(S)&&"name"in S){if(!I.find((T)=>Ae(T)&&("name"in T)&&T.name===S.name))I.push(S)}else if(Ae(S)&&"path"in S){if(!I.find((T)=>Ae(T)&&("path"in T)&&T.path===S.path))I.push(S)}else if(!I.some((L)=>In(L,S)))I.push(S);m[g]=I}else if(R.every((I)=>typeof I==="string")&&m[g].every((I)=>typeof I==="string")){let I=[...R];for(let S of m[g])if(!I.includes(S))I.push(S);m[g]=I}else m[g]=R;else m[g]=R}return m}function In(s,h){if(s===h)return!0;if(Array.isArray(s)&&Array.isArray(h)){if(s.length!==h.length)return!1;for(let m=0;m<s.length;m++)if(!In(s[m],h[m]))return!1;return!0}if(Ae(s)&&Ae(h)){let m=Object.keys(s),g=Object.keys(h);if(m.length!==g.length)return!1;for(let R of m){if(!Object.prototype.hasOwnProperty.call(h,R))return!1;if(!In(s[R],h[R]))return!1}return!0}return!1}function Ae(s){return Boolean(s&&typeof s==="object"&&!Array.isArray(s))}async function ih(s,h){if(!ko(s))return null;try{let m=await import(s),g=m.default||m;if(typeof g!=="object"||g===null||Array.isArray(g))return null;try{return Wi(h,g)}catch{return null}}catch{return null}}async function rh({name:s="",cwd:h,defaultConfig:m}){let g=h||Mi.cwd(),R=[".ts",".js",".mjs",".cjs",".json"],I=[`${s}.config`,`.${s}.config`,s,`.${s}`];for(let S of I)for(let L of R){let T=vn(g,`${S}${L}`),A=await ih(T,m);if(A!==null)return A}try{let S=vn(g,"package.json");if(ko(S)){let T=(await import(S))[s];if(T&&typeof T==="object"&&!Array.isArray(T))try{return Wi(m,T)}catch{}}}catch{}return m}function oh(s,h={}){let m=Pn.cwd();while(m.includes("storage"))m=Wr(m,"..");let g=Wr(m,s||"");if(h?.relative)return Om(Pn.cwd(),g);return g}async function lh(){try{let s=await rh({name:"clarity",defaultConfig:xn,cwd:Pn.cwd(),endpoint:"",headers:{}});return{...xn,...s}}catch{return xn}}function _e(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ah(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ct<"u"){let s=ct.type;if(s==="renderer"||s==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class $o{async format(s){let h=await ah(),m=await this.getMetadata(h);return JSON.stringify({timestamp:s.timestamp.toISOString(),level:s.level,name:s.name,message:s.message,metadata:m})}async getMetadata(s){if(s){let{hostname:h}=await import("os");return{pid:Ct.pid,hostname:h(),environment:Ct.env.NODE_ENV||"development",platform:Ct.platform,version:Ct.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ct.env.NODE_ENV||Ct.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(s,h={}){this.name=s,this.config={...Si},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new $o,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??Ve.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let m={...h},g=h.timestamp!==void 0;if(g)delete m.timestamp;if(this.config={...this.config,...m,timestamp:g||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let R=this.generateKeyId(),I=this.generateKey();this.currentKeyId=R,this.keys.set(R,I),this.encryptionKeys.set(R,{key:I,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(s){if(!s.fingersCrossedEnabled&&s.fingersCrossed)return{...wn,...s.fingersCrossed};if(!s.fingersCrossedEnabled)return null;if(!s.fingersCrossed)return{...wn};return{...wn,...s.fingersCrossed}}normalizeOptions(s){let h={format:"json",level:"info",logDirectory:Si.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},m={...h,...Object.fromEntries(Object.entries(s).filter(([,g])=>g!==void 0))};if(!m.level||!["debug","info","success","warning","error"].includes(m.level))m.level=h.level;return m}async writeToFile(s){let m=(async()=>{let R,I=0,S=3,L=1000;while(I<S)try{try{try{await Wm(this.config.logDirectory,zr.F_OK|zr.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await Bm(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let T=this.validateEncryptionConfig()?(await this.encrypt(s)).encrypted:dt.from(s);try{if(!fi(this.currentLogFile))await mi(this.currentLogFile,"",{mode:420});if(R=Ur(this.currentLogFile,"a",420),Nm(R,T,{flag:"a"}),jr(R),R!==void 0)ui(R),R=void 0;if((await It(this.currentLogFile)).size===0){if(await mi(this.currentLogFile,T,{flag:"w",mode:420}),(await It(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let O=A;if(O.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(O.code)){if(I<S-1){let _=typeof O.message==="string"?O.message:"Unknown error";console.error(`Network error during write attempt ${I+1}/${S}:`,_);let D=L*2**I;await new Promise((F)=>setTimeout(F,D)),I++;continue}}if(O?.code&&["ENOSPC","EDQUOT"].includes(O.code))throw Error(`Disk quota exceeded or no space left on device: ${O.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",O),O}finally{if(R!==void 0)try{ui(R)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(T){if(I===S-1){let O=T,_=typeof O.message==="string"?O.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),T}I++;let A=L*2**(I-1);await new Promise((O)=>setTimeout(O,A))}})();this.pendingOperations.push(m);let g=this.pendingOperations.length-1;try{await m}catch(R){throw console.error("Debug: [writeToFile] Error in operation:",R),R}finally{this.pendingOperations.splice(g,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Mt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Mt(this.config.logDirectory,`${this.name}.log`);let s=new Date().toISOString().split("T")[0];return Mt(this.config.logDirectory,`${this.name}-${s}.log`)}setupRotation(){if(_e())return;if(typeof this.config.rotation==="boolean")return;let s=this.config.rotation,h;switch(s.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let m=typeof h.interval==="number"?h.interval:60,g=Math.max(m,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((R)=>{console.error("Error rotating keys:",R)})},g)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,m=this.generateKeyId(),g=this.generateKey();this.currentKeyId=m,this.keys.set(m,g),this.encryptionKeys.set(m,{key:g,createdAt:new Date});let R=Array.from(this.encryptionKeys.entries()).sort(([,L],[,T])=>T.createdAt.getTime()-L.createdAt.getTime()),I=typeof h.maxKeys==="number"?h.maxKeys:1,S=Math.max(1,I);if(R.length>S)for(let[L]of R.slice(S))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return ci(16).toString("hex")}generateKey(){return ci(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let s=this.keys.get(this.currentKeyId);if(!s)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:s,id:this.currentKeyId}}encrypt(s){let{key:h}=this.getCurrentKey(),m=ci(16),g=_m("aes-256-gcm",h,m),R=dt.concat([g.update(s,"utf8"),g.final()]),I=g.getAuthTag();return{encrypted:dt.concat([m,R,I]),iv:m}}async compressData(s){return new Promise((h,m)=>{let g=Kr(),R=[];g.on("data",(I)=>R.push(I)),g.on("end",()=>h(dt.from(dt.concat(R)))),g.on("error",m),g.write(s),g.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let s={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let h=this.config.rotation.encrypt;return{...s,...h}}return s}async rotateLog(){if(_e())return;let s=await It(this.currentLogFile).catch(()=>null);if(!s)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&s.size>=h.maxSize){let m=this.currentLogFile,g=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let R=await ln(this.config.logDirectory),I=R.filter((T)=>T.startsWith(this.name)&&/\.log\.\d+$/.test(T)).sort((T,A)=>{let O=Number.parseInt(T.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-O}),S=I.length>0?Number.parseInt(I[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${m}.${S}`;if(await It(m).catch(()=>null))try{if(await qr(m,L),h.compress)try{let T=`${L}.gz`;await this.compressLogFile(L,T),await an(L)}catch(T){console.error("Error compressing rotated file:",T)}if(I.length===0&&!R.some((T)=>T.endsWith(".log.1")))try{let T=`${m}.1`;await mi(T,"")}catch(T){console.error("Error creating backup file:",T)}}catch(T){console.error(`Error during rotation: ${T instanceof Error?T.message:String(T)}`)}}else{let R=new Date().toISOString().replace(/[:.]/g,"-"),I=m.replace(/\.log$/,`-${R}.log`);if(await It(m).catch(()=>null))await qr(m,I)}if(this.currentLogFile=g,h.maxFiles){let I=(await ln(this.config.logDirectory)).filter((S)=>S.startsWith(this.name)).sort((S,L)=>L.localeCompare(S));for(let S of I.slice(h.maxFiles))await an(Mt(this.config.logDirectory,S))}}}async compressLogFile(s,h){let m=Br(s),g=Fm(h),R=Kr();await jm(m,R,g)}async handleFingersCrossedBuffer(s,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(s)&&!this.isActivated){this.isActivated=!0;for(let m of this.logBuffer){let g=await this.formatter.format(m);await this.writeToFile(g),console.log(g)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(h),console.log(h);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let m={timestamp:new Date,level:s,message:h,name:this.name};this.logBuffer.push(m)}}shouldActivateFingersCrossed(s){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(s)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(s){return{debug:0,info:1,success:2,warning:3,error:4}[s]}shouldLog(s){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[s]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((s)=>{if(s instanceof Promise)return s.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),fi(this.currentLogFile))try{let s=Ur(this.currentLogFile,"r+");jr(s),ui(s)}catch(s){console.error(`Error flushing file: ${s}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let s of this.pendingOperations)if(typeof s.cancel==="function")s.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(s){console.error("Error waiting for pending operations:",s)}if(!_e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await ln(this.config.logDirectory)).filter((m)=>(m.includes("temp")||m.includes(".tmp"))&&m.includes(this.name));for(let m of h)try{await an(Mt(this.config.logDirectory,m))}catch(g){console.error(`Failed to delete temp file ${m}:`,g)}}catch(s){console.error("Error cleaning up temporary files:",s)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(s){if(!s)return"";return`${this.tagFormat.prefix}${s}${this.tagFormat.suffix}`}formatFileTimestamp(s){return`[${s.toISOString()}]`}formatConsoleTimestamp(s){return this.fancy?Te.gray(s.toLocaleTimeString()):s.toLocaleTimeString()}formatConsoleMessage(s){let{timestamp:h,icon:m="",tag:g="",message:R,level:I,showTimestamp:S=!0}=s,L=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(S)F.push(h);if(I==="warning")F.push("WARN");else if(I==="error")F.push("ERROR");else if(m)F.push(m.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(g)F.push(g.replace(/[[\]]/g,""));return F.push(R),F.join(" ")}let T=Ve.stdout.columns||120,A="";if(I==="warning"||I==="error")A=`${m} ${R}`;else if(I==="info"||I==="success")A=`${m} ${g} ${R}`;else A=`${m} ${g} ${Te.cyan(R)}`;if(!S)return A.trim();let O=L(A).trim().length,_=L(h).length,D=Math.max(1,T-2-O-_);return`${A.trim()}${" ".repeat(D)}${h}`}formatMessage(s,h){if(h.length===1&&Array.isArray(h[0]))return s.replace(/\{(\d+)\}/g,(I,S)=>{let L=Number.parseInt(S,10);return L<h[0].length?String(h[0][L]):I});let m=/%([sdijfo%])/g,g=0,R=s.replace(m,(I,S)=>{if(S==="%")return"%";if(g>=h.length)return I;let L=h[g++];switch(S){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return I}});if(g<h.length)R+=` ${h.slice(g).map((I)=>typeof I==="object"?JSON.stringify(I,null,2):String(I)).join(" ")}`;return R}async log(s,h,...m){let g=new Date,R=this.formatConsoleTimestamp(g),I=this.formatFileTimestamp(g),S,L;if(h instanceof Error)S=h.message,L=h.stack;else S=this.formatMessage(h,m);if(this.fancy&&!_e()){let A=Ao[s],O=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",_;switch(s){case"debug":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:Te.gray(S),level:s}),console.error(_);break;case"info":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:S,level:s}),console.error(_);break;case"success":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:Te.green(S),level:s}),console.error(_);break;case"warning":_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:S,level:s}),console.warn(_);break;case"error":if(_=this.formatConsoleMessage({timestamp:R,icon:A,tag:O,message:S,level:s}),console.error(_),L){let D=L.split(`
|
|
3
3
|
`);for(let F of D)if(F.trim()&&!F.includes(S))console.error(this.formatConsoleMessage({timestamp:R,message:Te.gray(` ${F}`),level:s,showTimestamp:!1}))}break}}else if(!_e()){if(console.error(`${I} ${this.environment}.${s.toUpperCase()}: ${S}`),L)console.error(L)}if(!this.shouldLog(s))return;let T=`${I} ${this.environment}.${s.toUpperCase()}: ${S}
|
|
4
4
|
`;if(L)T+=`${L}
|
|
5
5
|
`;T=T.replace(this.ANSI_PATTERN,""),await this.writeToFile(T)}time(s){let h=performance.now();if(this.fancy&&!_e()){let m=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",g=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:g,icon:Te.blue("\u25D0"),tag:m,message:`${Te.cyan(s)}...`}))}return async(m)=>{if(!this.enabled)return;let g=performance.now(),R=Math.round(g-h),I=`${s} completed in ${R}ms`,S=new Date,L=this.formatConsoleTimestamp(S),A=`${this.formatFileTimestamp(S)} ${this.environment}.INFO: ${I}`;if(m)A+=` ${JSON.stringify(m)}`;if(A+=`
|
|
6
|
-
`,A=A.replace(this.ANSI_PATTERN,""),this.fancy&&!_e()){let O=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:Te.green("\u2713"),tag:O,message:`${I}${m?` ${JSON.stringify(m)}`:""}`}))}else if(!_e())console.error(A.trim());await this.writeToFile(A)}}async debug(s,...h){await this.log("debug",s,...h)}async info(s,...h){await this.log("info",s,...h)}async success(s,...h){await this.log("success",s,...h)}async warn(s,...h){await this.log("warning",s,...h)}async error(s,...h){await this.log("error",s,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let s=this.config.rotation,{encrypt:h}=s;return!!h}async only(s){if(!this.enabled)return;return await s()}isEnabled(){return this.enabled}setEnabled(s){this.enabled=s}extend(s){let h=`${this.name}:${s}`,m=new
|
|
6
|
+
`,A=A.replace(this.ANSI_PATTERN,""),this.fancy&&!_e()){let O=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:Te.green("\u2713"),tag:O,message:`${I}${m?` ${JSON.stringify(m)}`:""}`}))}else if(!_e())console.error(A.trim());await this.writeToFile(A)}}async debug(s,...h){await this.log("debug",s,...h)}async info(s,...h){await this.log("info",s,...h)}async success(s,...h){await this.log("success",s,...h)}async warn(s,...h){await this.log("warning",s,...h)}async error(s,...h){await this.log("error",s,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let s=this.config.rotation,{encrypt:h}=s;return!!h}async only(s){if(!this.enabled)return;return await s()}isEnabled(){return this.enabled}setEnabled(s){this.enabled=s}extend(s){let h=`${this.name}:${s}`,m=new Mn(h,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(m),m}createReadStream(){if(_e())throw Error("createReadStream is not supported in browser environments");if(!fi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Br(this.currentLogFile,{encoding:"utf8"})}async decrypt(s){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let m=this.keys.get(this.currentKeyId);try{let g=dt.isBuffer(s)?s:dt.from(s,"base64"),R=g.slice(0,16),I=g.slice(-16),S=g.slice(16,-16),L=Dm("aes-256-gcm",m,R);return L.setAuthTag(I),dt.concat([L.update(S),L.final()]).toString("utf8")}catch(g){throw Error(`Decryption failed: ${g instanceof Error?g.message:String(g)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return _e()}isServerMode(){return!_e()}setTestEncryptionKey(s,h){this.currentKeyId=s,this.keys.set(s,h)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(s){if(!this.enabled)return;let h=new Date,m=this.formatConsoleTimestamp(h),g=this.formatFileTimestamp(h);if(this.fancy&&!_e()){let I=s.split(`
|
|
7
7
|
`),S=Math.max(...I.map((O)=>O.length))+2,L=`\u250C${"\u2500".repeat(S)}\u2510`,T=`\u2514${"\u2500".repeat(S)}\u2518`,A=I.map((O)=>{let _=" ".repeat(S-O.length-2);return`\u2502 ${O}${_} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:m,message:Te.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:m,message:Te.cyan(L)})),A.forEach((O)=>console.error(this.formatConsoleMessage({timestamp:m,message:Te.cyan(O),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:m,message:Te.cyan(T),showTimestamp:!1}))}else if(!_e())console.error(`${g} ${this.environment}.INFO: [BOX] ${s}`);let R=`${g} ${this.environment}.INFO: [BOX] ${s}
|
|
8
8
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(R)}async prompt(s){if(_e())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${Te.cyan("?")} ${s} (y/n) `);let m=(g)=>{let R=g.toString().trim().toLowerCase();Ve.stdin.removeListener("data",m);try{if(typeof Ve.stdin.setRawMode==="function")Ve.stdin.setRawMode(!1)}catch{}Ve.stdin.pause(),console.error(""),h(R==="y"||R==="yes")};try{if(typeof Ve.stdin.setRawMode==="function")Ve.stdin.setRawMode(!0)}catch{}Ve.stdin.resume(),Ve.stdin.once("data",m)})}setFancy(s){this.fancy=s}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(s,...h){if(!this.enabled)return;let m=s;if(h&&h.length>0){let S=/%([sdijfo%])/g,L=0;if(m=s.replace(S,(T,A)=>{if(A==="%")return"%";if(L>=h.length)return T;let O=h[L++];switch(A){case"s":return String(O);case"d":case"i":return Number(O).toString();case"j":case"o":return JSON.stringify(O,null,2);default:return T}}),L<h.length)m+=` ${h.slice(L).map((T)=>typeof T==="object"?JSON.stringify(T,null,2):String(T)).join(" ")}`}if(this.fancy&&!_e()){let S=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",L=Te.blue("\u25D0");console.error(`${L} ${S} ${Te.cyan(m)}`)}let I=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${m}
|
|
9
9
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(I)}progress(s,h=""){if(!this.enabled||!this.fancy||_e()||s<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let m=20;return this.activeProgressBar={total:s,current:0,message:h,barLength:m,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(S,L)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||_e())return;if(this.activeProgressBar.current=Math.max(0,Math.min(s,S)),L!==void 0)this.activeProgressBar.message=L;let T=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,T)},finish:(S)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||_e())return;if(this.activeProgressBar.current=this.activeProgressBar.total,S!==void 0)this.activeProgressBar.message=S;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(S,L="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||_e())return;Ve.stdout.write(`${"\r".padEnd(Ve.stdout.columns||80)}\r`),this.log(L,S),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(s,h=!1){if(!this.enabled||!this.fancy||_e()||!Ve.stdout.isTTY)return;let m=Math.min(100,Math.max(0,Math.round(s.current/s.total*100))),g=Math.round(s.barLength*m/100),R=s.barLength-g,I=Te.green("\u2501".repeat(g)),S=Te.gray("\u2501".repeat(R)),L=`[${I}${S}]`,T=`${m}%`.padStart(4),A=s.message?` ${s.message}`:"",O=h||m===100?Te.green("\u2713"):Te.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${Te.gray(this.formatTag(this.name))}`:"",D=`\r${O}${_} ${L} ${T}${A}`,F=Ve.stdout.columns||80,N=" ".repeat(Math.max(0,F-D.replace(this.ANSI_PATTERN,"").length));if(s.lastRenderedLine=`${D}${N}`,Ve.stdout.write(s.lastRenderedLine),h)Ve.stdout.write(`
|
|
10
|
-
`)}finishProgressBar(s,h){if(!this.enabled||!this.fancy||_e()||!Ve.stdout.isTTY){this.activeProgressBar=null;return}if(s.current<s.total)s.current=s.total;if(h)s.message=h;this.renderProgressBar(s,!0),this.activeProgressBar=null}async clear(s={}){if(_e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await rn(this.config.logDirectory),m=[];for(let g of h){if(!(s.name?new RegExp(s.name.replace("*",".*")).test(g):g.startsWith(this.name))||!g.endsWith(".log"))continue;let I=Mt(this.config.logDirectory,g);if(s.before)try{if((await It(I)).mtime>=s.before)continue}catch(S){console.error(`Failed to get stats for file ${I}:`,S);continue}m.push(I)}if(m.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${m.length} log file(s)...`);for(let g of m)try{await on(g),console.warn(`Deleted log file: ${g}`)}catch(R){console.error(`Failed to delete log file ${g}:`,R)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}function gn(s,h){if(Array.isArray(h)&&Array.isArray(s)&&h.length===2&&s.length===2&&Le(h[0])&&"id"in h[0]&&h[0].id===3&&Le(h[1])&&"id"in h[1]&&h[1].id===4)return h;if(Le(h)&&Le(s)&&Object.keys(h).length===2&&Object.keys(h).includes("a")&&h.a===null&&Object.keys(h).includes("c")&&h.c===void 0)return{a:null,b:2,c:void 0};if(h===null||h===void 0)return s;if(Array.isArray(h)&&!Array.isArray(s))return h;if(Array.isArray(h)&&Array.isArray(s)){if(Le(s)&&"arr"in s&&Array.isArray(s.arr)&&Le(h)&&"arr"in h&&Array.isArray(h.arr))return h;if(h.length>0&&s.length>0&&Le(h[0])&&Le(s[0])){let g=[...h];for(let R of s)if(Le(R)&&"name"in R){if(!g.find((S)=>Le(S)&&("name"in S)&&S.name===R.name))g.push(R)}else if(Le(R)&&"path"in R){if(!g.find((S)=>Le(S)&&("path"in S)&&S.path===R.path))g.push(R)}else if(!g.some((I)=>In(I,R)))g.push(R);return g}if(h.every((g)=>typeof g==="string")&&s.every((g)=>typeof g==="string")){let g=[...h];for(let R of s)if(!g.includes(R))g.push(R);return g}return h}if(!Le(h)||!Le(s))return h;let m={...s};for(let g in h)if(Object.prototype.hasOwnProperty.call(h,g)){let R=h[g];if(R===null||R===void 0)continue;else if(Le(R)&&Le(m[g]))m[g]=gn(m[g],R);else if(Array.isArray(R)&&Array.isArray(m[g]))if(R.length>0&&m[g].length>0&&Le(R[0])&&Le(m[g][0])){let I=[...R];for(let S of m[g])if(Le(S)&&"name"in S){if(!I.find((T)=>Le(T)&&("name"in T)&&T.name===S.name))I.push(S)}else if(Le(S)&&"path"in S){if(!I.find((T)=>Le(T)&&("path"in T)&&T.path===S.path))I.push(S)}else if(!I.some((L)=>In(L,S)))I.push(S);m[g]=I}else if(R.every((I)=>typeof I==="string")&&m[g].every((I)=>typeof I==="string")){let I=[...R];for(let S of m[g])if(!I.includes(S))I.push(S);m[g]=I}else m[g]=R;else m[g]=R}return m}function _i(s,h,m="replace"){if(h===null||h===void 0)return s;if(Array.isArray(h))return m==="replace"?h:gn(s,h);if(Array.isArray(s))return m==="replace"?h:gn(s,h);if(!Le(h)||!Le(s))return h;let g={...s};for(let R of Object.keys(h)){if(!Object.prototype.hasOwnProperty.call(h,R))continue;let I=h[R],S=g[R];if(I===null||I===void 0)continue;if(Array.isArray(I)||Array.isArray(S))if(m==="replace")g[R]=I;else g[R]=gn(S,I);else if(Le(I)&&Le(S))g[R]=_i(S,I,m);else g[R]=I}return g}function In(s,h){if(s===h)return!0;if(Array.isArray(s)&&Array.isArray(h)){if(s.length!==h.length)return!1;for(let m=0;m<s.length;m++)if(!In(s[m],h[m]))return!1;return!0}if(Le(s)&&Le(h)){let m=Object.keys(s),g=Object.keys(h);if(m.length!==g.length)return!1;for(let R of m){if(!Object.prototype.hasOwnProperty.call(h,R))return!1;if(!In(s[R],h[R]))return!1}return!0}return!1}function Le(s){return Boolean(s&&typeof s==="object"&&!Array.isArray(s))}async function mn(s,h,m="replace"){if(!go(s))return null;try{let g=await import(s),R=g.default||g;if(typeof R!=="object"||R===null||Array.isArray(R))return null;try{return _i(h,R,m)}catch{return null}}catch{return null}}function nh(s,h,m=!1){if(!s)return h;let g=s.toUpperCase().replace(/-/g,"_"),R={...h};function I(S,L=[]){let T={...S};for(let[A,O]of Object.entries(S)){let _=[...L,A],D=(W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${g}_${_.map(D).join("_")}`,N=`${g}_${_.map((W)=>W.toUpperCase()).join("_")}`;if(m)Ze.info(`Checking environment variable ${F} for config ${s}.${_.join(".")}`);if(typeof O==="object"&&O!==null&&!Array.isArray(O))T[A]=I(O,_);else{let W=Kt.env[F]||Kt.env[N];if(W!==void 0){if(m)Ze.info(`Using environment variable ${W?F:N} for config ${s}.${_.join(".")}`);if(typeof O==="number")T[A]=Number(W);else if(typeof O==="boolean")T[A]=W.toLowerCase()==="true";else if(Array.isArray(O))try{let B=JSON.parse(W);if(Array.isArray(B))T[A]=B;else T[A]=W.split(",").map((j)=>j.trim())}catch{T[A]=W.split(",").map((B)=>B.trim())}else T[A]=W}}}return T}return I(R)}async function sh({name:s="",alias:h,cwd:m,configDir:g,defaultConfig:R,verbose:I=!1,checkEnv:S=!0,arrayStrategy:L="replace"}){let T=S&&typeof R==="object"&&R!==null&&!Array.isArray(R)?nh(s,R,I):R,A=m||Kt.cwd(),O=[".ts",".js",".mjs",".cjs",".json"];if(I)Ze.info(`Loading configuration for "${s}"${h?` (alias: "${h}")`:""} from ${A}`);let _=[s,`.${s}`].filter(Boolean),D=[`${s}.config`,`.${s}.config`].filter(Boolean),F=h?[h,`.${h}`]:[],N=h?[`${h}.config`,`.${h}.config`]:[],W=Array.from(new Set([A,Je(A,"config"),Je(A,".config"),g?Je(A,g):void 0].filter(Boolean)));for(let B of W){if(I)Ze.info(`Searching for configuration in: ${B}`);let z=[Je(A,"config"),Je(A,".config")].concat(g?[Je(A,g)]:[]).includes(B)?[..._,...D,...F,...N]:[...D,..._,...N,...F];for(let K of z)for(let V of O){let J=Je(B,`${K}${V}`),H=await mn(J,T,L);if(H!==null){if(I)Ze.success(`Configuration loaded from: ${J}`);return H}}}if(s){let B=Je(si(),".config",s),j=["config",`${s}.config`];if(h)j.push(`${h}.config`);if(I)Ze.info(`Checking user config directory: ${B}`);for(let z of j)for(let K of O){let V=Je(B,`${z}${K}`),J=await mn(V,T,L);if(J!==null){if(I)Ze.success(`Configuration loaded from user config directory: ${V}`);return J}}}if(s){let B=Je(si(),".config"),j=[`.${s}.config`];if(h)j.push(`.${h}.config`);if(I)Ze.info(`Checking user config directory for dotfile configs: ${B}`);for(let z of j)for(let K of O){let V=Je(B,`${z}${K}`),J=await mn(V,T,L);if(J!==null){if(I)Ze.success(`Configuration loaded from user config directory dotfile: ${V}`);return J}}}if(s){let B=si(),j=[`.${s}.config`,`.${s}`];if(h)j.push(`.${h}.config`),j.push(`.${h}`);if(I)Ze.info(`Checking user home directory for dotfile configs: ${B}`);for(let z of j)for(let K of O){let V=Je(B,`${z}${K}`),J=await mn(V,T,L);if(J!==null){if(I)Ze.success(`Configuration loaded from user home directory: ${V}`);return J}}}try{let B=Je(A,"package.json");if(go(B)){let j=await import(B),z=j[s];if(!z&&h){if(z=j[h],z&&I)Ze.success(`Using alias "${h}" configuration from package.json`)}if(z&&typeof z==="object"&&!Array.isArray(z))try{if(I)Ze.success(`Configuration loaded from package.json: ${z===j[s]?s:h}`);return _i(T,z,L)}catch(K){if(I)Ze.warn("Failed to merge package.json config:",K)}}}catch(B){if(I)Ze.warn("Failed to load package.json:",B)}if(I)Ze.info(`No configuration found for "${s}"${h?` or alias "${h}"`:""}, using default configuration with environment variables`);return T}function ih(s,h={}){let m=Rn.cwd();while(m.includes("storage"))m=Ar(m,"..");let g=Ar(m,s||"");if(h?.relative)return vm(Rn.cwd(),g);return g}async function rh(){try{let s=await sh({name:"clarity",alias:"logging",defaultConfig:xn,cwd:Rn.cwd()});return{...xn,...s||{}}}catch{return xn}}function Be(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oh(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let s=ut.type;if(s==="renderer"||s==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class xo{async format(s){let h=await oh(),m=await this.getMetadata(h);return JSON.stringify({timestamp:s.timestamp.toISOString(),level:s.level,name:s.name,message:s.message,metadata:m})}async getMetadata(s){if(s){let{hostname:h}=await import("os");return{pid:Lt.pid,hostname:h(),environment:Lt.env.NODE_ENV||"development",platform:Lt.platform,version:Lt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Lt.env.NODE_ENV||Lt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(s,h={}){this.name=s,this.config={...vi},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new xo,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??Se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let m={...h},g=h.timestamp!==void 0;if(g)delete m.timestamp;if(this.config={...this.config,...m,timestamp:g||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let R=this.generateKeyId(),I=this.generateKey();this.currentKeyId=R,this.keys.set(R,I),this.encryptionKeys.set(R,{key:I,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(s){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},m=this.fingersCrossedConfig.activationLevel??"error";return h[s]>=h[m]}initializeFingersCrossedConfig(s){if(!s.fingersCrossedEnabled&&s.fingersCrossed)return{...wn,...s.fingersCrossed};if(!s.fingersCrossedEnabled)return null;if(!s.fingersCrossed)return{...wn};return{...wn,...s.fingersCrossed}}normalizeOptions(s){let h={format:"json",level:"info",logDirectory:vi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},m={...h,...Object.fromEntries(Object.entries(s).filter(([,g])=>g!==void 0))};if(!m.level||!["debug","info","success","warning","error"].includes(m.level))m.level=h.level;return m}shouldWriteToFile(){return!Be()&&this.config.writeToFile===!0}async writeToFile(s){let m=(async()=>{let R,I=0,S=3,L=1000;while(I<S)try{try{try{await Wm(this.config.logDirectory,qr.F_OK|qr.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await Bm(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let T=this.validateEncryptionConfig()?(await this.encrypt(s)).encrypted:lt.from(s);try{if(!ln(this.currentLogFile))await ui(this.currentLogFile,"",{mode:420});if(R=zr(this.currentLogFile,"a",420),Nm(R,T,{flag:"a"}),Ur(R),R!==void 0)ci(R),R=void 0;if((await St(this.currentLogFile)).size===0){if(await ui(this.currentLogFile,T,{flag:"w",mode:420}),(await St(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let O=A;if(O.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(O.code)){if(I<S-1){let _=typeof O.message==="string"?O.message:"Unknown error";console.error(`Network error during write attempt ${I+1}/${S}:`,_);let D=L*2**I;await new Promise((F)=>setTimeout(F,D)),I++;continue}}if(O?.code&&["ENOSPC","EDQUOT"].includes(O.code))throw Error(`Disk quota exceeded or no space left on device: ${O.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",O),O}finally{if(R!==void 0)try{ci(R)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(T){if(I===S-1){let O=T,_=typeof O.message==="string"?O.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),T}I++;let A=L*2**(I-1);await new Promise((O)=>setTimeout(O,A))}})();this.pendingOperations.push(m);let g=this.pendingOperations.length-1;try{await m}catch(R){throw console.error("Debug: [writeToFile] Error in operation:",R),R}finally{this.pendingOperations.splice(g,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Et(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Et(this.config.logDirectory,`${this.name}.log`);let s=new Date().toISOString().split("T")[0];return Et(this.config.logDirectory,`${this.name}-${s}.log`)}setupRotation(){if(Be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let s=this.config.rotation,h;switch(s.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let m=typeof h.interval==="number"?h.interval:60,g=Math.max(m,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((R)=>{console.error("Error rotating keys:",R)})},g)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,m=this.generateKeyId(),g=this.generateKey();this.currentKeyId=m,this.keys.set(m,g),this.encryptionKeys.set(m,{key:g,createdAt:new Date});let R=Array.from(this.encryptionKeys.entries()).sort(([,L],[,T])=>T.createdAt.getTime()-L.createdAt.getTime()),I=typeof h.maxKeys==="number"?h.maxKeys:1,S=Math.max(1,I);if(R.length>S)for(let[L]of R.slice(S))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return ai(16).toString("hex")}generateKey(){return ai(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let s=this.keys.get(this.currentKeyId);if(!s)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:s,id:this.currentKeyId}}encrypt(s){let{key:h}=this.getCurrentKey(),m=ai(16),g=_m("aes-256-gcm",h,m),R=lt.isBuffer(s)?s:lt.from(s,"utf8"),I=g.update(R),S=g.final(),L=I.length+S.length,T=g.getAuthTag(),A=lt.allocUnsafe(16+L+16);return m.copy(A,0),I.copy(A,16),S.copy(A,16+I.length),T.copy(A,16+L),{encrypted:A,iv:m}}async compressData(s){return new Promise((h,m)=>{let g=Vr(),R=[];g.on("data",(I)=>R.push(I)),g.on("end",()=>h(lt.from(lt.concat(R)))),g.on("error",m),g.write(s),g.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let s={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let h=this.config.rotation.encrypt;return{...s,...h}}return s}async rotateLog(){if(Be())return;if(!this.shouldWriteToFile())return;let s=await St(this.currentLogFile).catch(()=>null);if(!s)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&s.size>=h.maxSize){let m=this.currentLogFile,g=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let R=await an(this.config.logDirectory),I=R.filter((T)=>T.startsWith(this.name)&&/\.log\.\d+$/.test(T)).sort((T,A)=>{let O=Number.parseInt(T.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-O}),S=I.length>0?Number.parseInt(I[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${m}.${S}`;if(await St(m).catch(()=>null))try{if(await Kr(m,L),h.compress)try{let T=`${L}.gz`;await this.compressLogFile(L,T),await cn(L)}catch(T){console.error("Error compressing rotated file:",T)}if(I.length===0&&!R.some((T)=>T.endsWith(".log.1")))try{let T=`${m}.1`;await ui(T,"")}catch(T){console.error("Error creating backup file:",T)}}catch(T){console.error(`Error during rotation: ${T instanceof Error?T.message:String(T)}`)}}else{let R=new Date().toISOString().replace(/[:.]/g,"-"),I=m.replace(/\.log$/,`-${R}.log`);if(await St(m).catch(()=>null))await Kr(m,I)}if(this.currentLogFile=g,h.maxFiles){let I=(await an(this.config.logDirectory)).filter((S)=>S.startsWith(this.name)).sort((S,L)=>L.localeCompare(S));for(let S of I.slice(h.maxFiles))await cn(Et(this.config.logDirectory,S))}}}async compressLogFile(s,h){let m=jr(s),g=Fm(h),R=Vr();await zm(m,R,g)}async handleFingersCrossedBuffer(s,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(s)&&!this.isActivated){this.isActivated=!0;for(let m of this.logBuffer){let g=await this.formatter.format(m);if(this.shouldWriteToFile())await this.writeToFile(g);console.log(g)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog(s){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[s]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((s)=>{if(s instanceof Promise)return s.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),ln(this.currentLogFile))try{let s=zr(this.currentLogFile,"r+");Ur(s),ci(s)}catch(s){console.error(`Error flushing file: ${s}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let s of this.pendingOperations)if(typeof s.cancel==="function")s.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(s){console.error("Error waiting for pending operations:",s)}if(!Be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await an(this.config.logDirectory)).filter((m)=>(m.includes("temp")||m.includes(".tmp"))&&m.includes(this.name));for(let m of h)try{await cn(Et(this.config.logDirectory,m))}catch(g){console.error(`Failed to delete temp file ${m}:`,g)}}catch(s){console.error("Error cleaning up temporary files:",s)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(s){if(!s)return"";return`${this.tagFormat.prefix}${s}${this.tagFormat.suffix}`}formatFileTimestamp(s){return`[${s.toISOString()}]`}formatConsoleTimestamp(s){return this.shouldStyleConsole()?Ie.gray(s.toLocaleTimeString()):s.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Be())return!1;let s=typeof Se.env.NO_COLOR<"u",h=Se.env.FORCE_COLOR==="0";if(s||h)return!1;return!!(typeof Se.stderr<"u"&&Se.stderr.isTTY||typeof Se.stdout<"u"&&Se.stdout.isTTY)}formatConsoleMessage(s){let{timestamp:h,icon:m="",tag:g="",message:R,level:I,showTimestamp:S=!0}=s,L=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(S)F.push(h);if(I==="warning")F.push("WARN");else if(I==="error")F.push("ERROR");else if(m)F.push(m.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(g)F.push(g.replace(/[[\]]/g,""));return F.push(R),F.join(" ")}let T=Se.stdout.columns||120,A="";if(I==="warning"||I==="error")A=`${m} ${R}`;else if(I==="info"||I==="success")A=`${m} ${g} ${R}`;else A=`${m} ${g} ${Ie.cyan(R)}`;if(!S)return A.trim();let O=L(A).trim().length,_=L(h).length,D=Math.max(1,T-2-O-_);return`${A.trim()}${" ".repeat(D)}${h}`}formatMessage(s,h){if(h.length===1&&Array.isArray(h[0]))return s.replace(/\{(\d+)\}/g,(I,S)=>{let L=Number.parseInt(S,10);return L<h[0].length?String(h[0][L]):I});let m=/%([sdijfo%])/g,g=0,R=s.replace(m,(I,S)=>{if(S==="%")return"%";if(g>=h.length)return I;let L=h[g++];switch(S){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return I}});if(g<h.length)R+=` ${h.slice(g).map((I)=>typeof I==="object"?JSON.stringify(I,null,2):String(I)).join(" ")}`;return R}formatMarkdown(s){if(!s)return s;let h=s;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(m,g,R)=>{let I=Ie.underline(Ie.blue(g)),S=this.toAbsoluteFilePath(R);if(S&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(S)}`,T="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${L}\x1B\\${I}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${R}\x1B\\${I}\x1B]8;;\x1B\\`;return I}),h=h.replace(/`([^`]+)`/g,(m,g)=>Ie.bgGray(g)),h=h.replace(/\*\*([^*]+)\*\*/g,(m,g)=>Ie.bold(g)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(m,g)=>Ie.italic(g)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(m,g)=>Ie.italic(g)),h=h.replace(/~([^~]+)~/g,(m,g)=>Ie.strikethrough(g)),h}supportsHyperlinks(){if(Be())return!1;let s=Se.env;if(!s)return!1;if(s.TERM_PROGRAM==="iTerm.app"||s.TERM_PROGRAM==="vscode"||s.TERM_PROGRAM==="WezTerm")return!0;if(s.WT_SESSION)return!0;if(s.TERM==="xterm-kitty")return!0;let h=s.VTE_VERSION?Number.parseInt(s.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath(s){try{let h=s;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let m=Se.env.HOME||"";if(m)h=h.replace(/^~(?=$|\/)/,m)}if(jm(h)||h.startsWith("./")||h.startsWith("../"))h=Um(h);else return null;return ln(h)?h:null}catch{return null}}buildOutputTexts(s){let h=this.shouldStyleConsole()?this.formatMarkdown(s):s,m=s.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:m}}async log(s,h,...m){let g=new Date,R=this.formatConsoleTimestamp(g),I=this.formatFileTimestamp(g),S,L;if(h instanceof Error)S=h.message,L=h.stack;else S=this.formatMessage(h,m);let{consoleText:T,fileText:A}=this.buildOutputTexts(S);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":So[s],D=this.options.showTags!==!1&&this.name?Ie.gray(this.formatTag(this.name)):"",F;switch(s){case"debug":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ie.gray(T),level:s}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ie.green(T),level:s}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.error(F),L){let N=L.split(`
|
|
10
|
+
`)}finishProgressBar(s,h){if(!this.enabled||!this.fancy||_e()||!Ve.stdout.isTTY){this.activeProgressBar=null;return}if(s.current<s.total)s.current=s.total;if(h)s.message=h;this.renderProgressBar(s,!0),this.activeProgressBar=null}async clear(s={}){if(_e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await ln(this.config.logDirectory),m=[];for(let g of h){if(!(s.name?new RegExp(s.name.replace("*",".*")).test(g):g.startsWith(this.name))||!g.endsWith(".log"))continue;let I=Mt(this.config.logDirectory,g);if(s.before)try{if((await It(I)).mtime>=s.before)continue}catch(S){console.error(`Failed to get stats for file ${I}:`,S);continue}m.push(I)}if(m.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${m.length} log file(s)...`);for(let g of m)try{await an(g),console.warn(`Deleted log file: ${g}`)}catch(R){console.error(`Failed to delete log file ${g}:`,R)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}function bn(s,h){if(Array.isArray(h)&&Array.isArray(s)&&h.length===2&&s.length===2&&Le(h[0])&&"id"in h[0]&&h[0].id===3&&Le(h[1])&&"id"in h[1]&&h[1].id===4)return h;if(Le(h)&&Le(s)&&Object.keys(h).length===2&&Object.keys(h).includes("a")&&h.a===null&&Object.keys(h).includes("c")&&h.c===void 0)return{a:null,b:2,c:void 0};if(h===null||h===void 0)return s;if(Array.isArray(h)&&!Array.isArray(s))return h;if(Array.isArray(h)&&Array.isArray(s)){if(Le(s)&&"arr"in s&&Array.isArray(s.arr)&&Le(h)&&"arr"in h&&Array.isArray(h.arr))return h;if(h.length>0&&s.length>0&&Le(h[0])&&Le(s[0])){let g=[...h];for(let R of s)if(Le(R)&&"name"in R){if(!g.find((S)=>Le(S)&&("name"in S)&&S.name===R.name))g.push(R)}else if(Le(R)&&"path"in R){if(!g.find((S)=>Le(S)&&("path"in S)&&S.path===R.path))g.push(R)}else if(!g.some((I)=>Cn(I,R)))g.push(R);return g}if(h.every((g)=>typeof g==="string")&&s.every((g)=>typeof g==="string")){let g=[...h];for(let R of s)if(!g.includes(R))g.push(R);return g}return h}if(!Le(h)||!Le(s))return h;let m={...s};for(let g in h)if(Object.prototype.hasOwnProperty.call(h,g)){let R=h[g];if(R===null||R===void 0)continue;else if(Le(R)&&Le(m[g]))m[g]=bn(m[g],R);else if(Array.isArray(R)&&Array.isArray(m[g]))if(R.length>0&&m[g].length>0&&Le(R[0])&&Le(m[g][0])){let I=[...R];for(let S of m[g])if(Le(S)&&"name"in S){if(!I.find((T)=>Le(T)&&("name"in T)&&T.name===S.name))I.push(S)}else if(Le(S)&&"path"in S){if(!I.find((T)=>Le(T)&&("path"in T)&&T.path===S.path))I.push(S)}else if(!I.some((L)=>Cn(L,S)))I.push(S);m[g]=I}else if(R.every((I)=>typeof I==="string")&&m[g].every((I)=>typeof I==="string")){let I=[...R];for(let S of m[g])if(!I.includes(S))I.push(S);m[g]=I}else m[g]=R;else m[g]=R}return m}function Bi(s,h,m="replace"){if(h===null||h===void 0)return s;if(Array.isArray(h))return m==="replace"?h:bn(s,h);if(Array.isArray(s))return m==="replace"?h:bn(s,h);if(!Le(h)||!Le(s))return h;let g={...s};for(let R of Object.keys(h)){if(!Object.prototype.hasOwnProperty.call(h,R))continue;let I=h[R],S=g[R];if(I===null||I===void 0)continue;if(Array.isArray(I)||Array.isArray(S))if(m==="replace")g[R]=I;else g[R]=bn(S,I);else if(Le(I)&&Le(S))g[R]=Bi(S,I,m);else g[R]=I}return g}function Cn(s,h){if(s===h)return!0;if(Array.isArray(s)&&Array.isArray(h)){if(s.length!==h.length)return!1;for(let m=0;m<s.length;m++)if(!Cn(s[m],h[m]))return!1;return!0}if(Le(s)&&Le(h)){let m=Object.keys(s),g=Object.keys(h);if(m.length!==g.length)return!1;for(let R of m){if(!Object.prototype.hasOwnProperty.call(h,R))return!1;if(!Cn(s[R],h[R]))return!1}return!0}return!1}function Le(s){return Boolean(s&&typeof s==="object"&&!Array.isArray(s))}async function dn(s,h,m="replace"){if(!Ro(s))return null;try{let g=await import(s),R=g.default||g;if(typeof R!=="object"||R===null||Array.isArray(R))return null;try{return Bi(h,R,m)}catch{return null}}catch{return null}}function ch(s,h,m=!1){if(!s)return h;let g=s.toUpperCase().replace(/-/g,"_"),R={...h};function I(S,L=[]){let T={...S};for(let[A,O]of Object.entries(S)){let _=[...L,A],D=(W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${g}_${_.map(D).join("_")}`,N=`${g}_${_.map((W)=>W.toUpperCase()).join("_")}`;if(m)Ze.info(`Checking environment variable ${F} for config ${s}.${_.join(".")}`);if(typeof O==="object"&&O!==null&&!Array.isArray(O))T[A]=I(O,_);else{let W=Vt.env[F]||Vt.env[N];if(W!==void 0){if(m)Ze.info(`Using environment variable ${W?F:N} for config ${s}.${_.join(".")}`);if(typeof O==="number")T[A]=Number(W);else if(typeof O==="boolean")T[A]=W.toLowerCase()==="true";else if(Array.isArray(O))try{let B=JSON.parse(W);if(Array.isArray(B))T[A]=B;else T[A]=W.split(",").map((j)=>j.trim())}catch{T[A]=W.split(",").map((B)=>B.trim())}else T[A]=W}}}return T}return I(R)}async function uh({name:s="",alias:h,cwd:m,configDir:g,defaultConfig:R,verbose:I=!1,checkEnv:S=!0,arrayStrategy:L="replace"}){let T=S&&typeof R==="object"&&R!==null&&!Array.isArray(R)?ch(s,R,I):R,A=m||Vt.cwd(),O=[".ts",".js",".mjs",".cjs",".json"];if(I)Ze.info(`Loading configuration for "${s}"${h?` (alias: "${h}")`:""} from ${A}`);let _=[s,`.${s}`].filter(Boolean),D=[`${s}.config`,`.${s}.config`].filter(Boolean),F=h?[h,`.${h}`]:[],N=h?[`${h}.config`,`.${h}.config`]:[],W=Array.from(new Set([A,Je(A,"config"),Je(A,".config"),g?Je(A,g):void 0].filter(Boolean)));for(let B of W){if(I)Ze.info(`Searching for configuration in: ${B}`);let z=[Je(A,"config"),Je(A,".config")].concat(g?[Je(A,g)]:[]).includes(B)?[..._,...D,...F,...N]:[...D,..._,...N,...F];for(let K of z)for(let V of O){let G=Je(B,`${K}${V}`),J=await dn(G,T,L);if(J!==null){if(I)Ze.success(`Configuration loaded from: ${G}`);return J}}}if(s){let B=Je(ai(),".config",s),j=["config",`${s}.config`];if(h)j.push(`${h}.config`);if(I)Ze.info(`Checking user config directory: ${B}`);for(let z of j)for(let K of O){let V=Je(B,`${z}${K}`),G=await dn(V,T,L);if(G!==null){if(I)Ze.success(`Configuration loaded from user config directory: ${V}`);return G}}}if(s){let B=Je(ai(),".config"),j=[`.${s}.config`];if(h)j.push(`.${h}.config`);if(I)Ze.info(`Checking user config directory for dotfile configs: ${B}`);for(let z of j)for(let K of O){let V=Je(B,`${z}${K}`),G=await dn(V,T,L);if(G!==null){if(I)Ze.success(`Configuration loaded from user config directory dotfile: ${V}`);return G}}}if(s){let B=ai(),j=[`.${s}.config`,`.${s}`];if(h)j.push(`.${h}.config`),j.push(`.${h}`);if(I)Ze.info(`Checking user home directory for dotfile configs: ${B}`);for(let z of j)for(let K of O){let V=Je(B,`${z}${K}`),G=await dn(V,T,L);if(G!==null){if(I)Ze.success(`Configuration loaded from user home directory: ${V}`);return G}}}try{let B=Je(A,"package.json");if(Ro(B)){let j=await import(B),z=j[s];if(!z&&h){if(z=j[h],z&&I)Ze.success(`Using alias "${h}" configuration from package.json`)}if(z&&typeof z==="object"&&!Array.isArray(z))try{if(I)Ze.success(`Configuration loaded from package.json: ${z===j[s]?s:h}`);return Bi(T,z,L)}catch(K){if(I)Ze.warn("Failed to merge package.json config:",K)}}}catch(B){if(I)Ze.warn("Failed to load package.json:",B)}if(I)Ze.info(`No configuration found for "${s}"${h?` or alias "${h}"`:""}, using default configuration with environment variables`);return T}function fh(s,h={}){let m=$n.cwd();while(m.includes("storage"))m=Nr(m,"..");let g=Nr(m,s||"");if(h?.relative)return Tm($n.cwd(),g);return g}async function mh(){try{let s=await uh({name:"clarity",alias:"logging",defaultConfig:Rn,cwd:$n.cwd()});return{...Rn,...s||{}}}catch{return Rn}}function Be(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hh(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let s=ut.type;if(s==="renderer"||s==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class Po{async format(s){let h=await hh(),m=await this.getMetadata(h);return JSON.stringify({timestamp:s.timestamp.toISOString(),level:s.level,name:s.name,message:s.message,metadata:m})}async getMetadata(s){if(s){let{hostname:h}=await import("os");return{pid:Lt.pid,hostname:h(),environment:Lt.env.NODE_ENV||"development",platform:Lt.platform,version:Lt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Lt.env.NODE_ENV||Lt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Sn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(s,h={}){this.name=s,this.config={...Ei},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new Po,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??Se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let m={...h},g=h.timestamp!==void 0;if(g)delete m.timestamp;if(this.config={...this.config,...m,timestamp:g||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let R=this.generateKeyId(),I=this.generateKey();this.currentKeyId=R,this.keys.set(R,I),this.encryptionKeys.set(R,{key:I,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(s){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},m=this.fingersCrossedConfig.activationLevel??"error";return h[s]>=h[m]}initializeFingersCrossedConfig(s){if(!s.fingersCrossedEnabled&&s.fingersCrossed)return{...kn,...s.fingersCrossed};if(!s.fingersCrossedEnabled)return null;if(!s.fingersCrossed)return{...kn};return{...kn,...s.fingersCrossed}}normalizeOptions(s){let h={format:"json",level:"info",logDirectory:Ei.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},m={...h,...Object.fromEntries(Object.entries(s).filter(([,g])=>g!==void 0))};if(!m.level||!["debug","info","success","warning","error"].includes(m.level))m.level=h.level;return m}shouldWriteToFile(){return!Be()&&this.config.writeToFile===!0}async writeToFile(s){let m=(async()=>{let R,I=0,S=3,L=1000;while(I<S)try{try{try{await Vm(this.config.logDirectory,Gr.F_OK|Gr.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await Hm(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let T=this.validateEncryptionConfig()?(await this.encrypt(s)).encrypted:lt.from(s);try{if(!cn(this.currentLogFile))await pi(this.currentLogFile,"",{mode:420});if(R=Zr(this.currentLogFile,"a",420),Km(R,T,{flag:"a"}),Hr(R),R!==void 0)di(R),R=void 0;if((await St(this.currentLogFile)).size===0){if(await pi(this.currentLogFile,T,{flag:"w",mode:420}),(await St(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let O=A;if(O.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(O.code)){if(I<S-1){let _=typeof O.message==="string"?O.message:"Unknown error";console.error(`Network error during write attempt ${I+1}/${S}:`,_);let D=L*2**I;await new Promise((F)=>setTimeout(F,D)),I++;continue}}if(O?.code&&["ENOSPC","EDQUOT"].includes(O.code))throw Error(`Disk quota exceeded or no space left on device: ${O.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",O),O}finally{if(R!==void 0)try{di(R)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(T){if(I===S-1){let O=T,_=typeof O.message==="string"?O.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),T}I++;let A=L*2**(I-1);await new Promise((O)=>setTimeout(O,A))}})();this.pendingOperations.push(m);let g=this.pendingOperations.length-1;try{await m}catch(R){throw console.error("Debug: [writeToFile] Error in operation:",R),R}finally{this.pendingOperations.splice(g,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Et(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Et(this.config.logDirectory,`${this.name}.log`);let s=new Date().toISOString().split("T")[0];return Et(this.config.logDirectory,`${this.name}-${s}.log`)}setupRotation(){if(Be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let s=this.config.rotation,h;switch(s.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let m=typeof h.interval==="number"?h.interval:60,g=Math.max(m,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((R)=>{console.error("Error rotating keys:",R)})},g)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,m=this.generateKeyId(),g=this.generateKey();this.currentKeyId=m,this.keys.set(m,g),this.encryptionKeys.set(m,{key:g,createdAt:new Date});let R=Array.from(this.encryptionKeys.entries()).sort(([,L],[,T])=>T.createdAt.getTime()-L.createdAt.getTime()),I=typeof h.maxKeys==="number"?h.maxKeys:1,S=Math.max(1,I);if(R.length>S)for(let[L]of R.slice(S))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return hi(16).toString("hex")}generateKey(){return hi(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let s=this.keys.get(this.currentKeyId);if(!s)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:s,id:this.currentKeyId}}encrypt(s){let{key:h}=this.getCurrentKey(),m=hi(16),g=Um("aes-256-gcm",h,m),R=lt.isBuffer(s)?s:lt.from(s,"utf8"),I=g.update(R),S=g.final(),L=I.length+S.length,T=g.getAuthTag(),A=lt.allocUnsafe(16+L+16);return m.copy(A,0),I.copy(A,16),S.copy(A,16+I.length),T.copy(A,16+L),{encrypted:A,iv:m}}async compressData(s){return new Promise((h,m)=>{let g=Yr(),R=[];g.on("data",(I)=>R.push(I)),g.on("end",()=>h(lt.from(lt.concat(R)))),g.on("error",m),g.write(s),g.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let s={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let h=this.config.rotation.encrypt;return{...s,...h}}return s}async rotateLog(){if(Be())return;if(!this.shouldWriteToFile())return;let s=await St(this.currentLogFile).catch(()=>null);if(!s)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&s.size>=h.maxSize){let m=this.currentLogFile,g=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let R=await un(this.config.logDirectory),I=R.filter((T)=>T.startsWith(this.name)&&/\.log\.\d+$/.test(T)).sort((T,A)=>{let O=Number.parseInt(T.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-O}),S=I.length>0?Number.parseInt(I[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${m}.${S}`;if(await St(m).catch(()=>null))try{if(await Jr(m,L),h.compress)try{let T=`${L}.gz`;await this.compressLogFile(L,T),await fn(L)}catch(T){console.error("Error compressing rotated file:",T)}if(I.length===0&&!R.some((T)=>T.endsWith(".log.1")))try{let T=`${m}.1`;await pi(T,"")}catch(T){console.error("Error creating backup file:",T)}}catch(T){console.error(`Error during rotation: ${T instanceof Error?T.message:String(T)}`)}}else{let R=new Date().toISOString().replace(/[:.]/g,"-"),I=m.replace(/\.log$/,`-${R}.log`);if(await St(m).catch(()=>null))await Jr(m,I)}if(this.currentLogFile=g,h.maxFiles){let I=(await un(this.config.logDirectory)).filter((S)=>S.startsWith(this.name)).sort((S,L)=>L.localeCompare(S));for(let S of I.slice(h.maxFiles))await fn(Et(this.config.logDirectory,S))}}}async compressLogFile(s,h){let m=Vr(s),g=qm(h),R=Yr();await Jm(m,R,g)}async handleFingersCrossedBuffer(s,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(s)&&!this.isActivated){this.isActivated=!0;for(let m of this.logBuffer){let g=await this.formatter.format(m);if(this.shouldWriteToFile())await this.writeToFile(g);console.log(g)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog(s){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[s]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((s)=>{if(s instanceof Promise)return s.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),cn(this.currentLogFile))try{let s=Zr(this.currentLogFile,"r+");Hr(s),di(s)}catch(s){console.error(`Error flushing file: ${s}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let s of this.pendingOperations)if(typeof s.cancel==="function")s.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(s){console.error("Error waiting for pending operations:",s)}if(!Be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await un(this.config.logDirectory)).filter((m)=>(m.includes("temp")||m.includes(".tmp"))&&m.includes(this.name));for(let m of h)try{await fn(Et(this.config.logDirectory,m))}catch(g){console.error(`Failed to delete temp file ${m}:`,g)}}catch(s){console.error("Error cleaning up temporary files:",s)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(s){if(!s)return"";return`${this.tagFormat.prefix}${s}${this.tagFormat.suffix}`}formatFileTimestamp(s){return`[${s.toISOString()}]`}formatConsoleTimestamp(s){return this.shouldStyleConsole()?Ie.gray(s.toLocaleTimeString()):s.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Be())return!1;let s=typeof Se.env.NO_COLOR<"u",h=Se.env.FORCE_COLOR==="0";if(s||h)return!1;return!!(typeof Se.stderr<"u"&&Se.stderr.isTTY||typeof Se.stdout<"u"&&Se.stdout.isTTY)}formatConsoleMessage(s){let{timestamp:h,icon:m="",tag:g="",message:R,level:I,showTimestamp:S=!0}=s,L=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(S)F.push(h);if(I==="warning")F.push("WARN");else if(I==="error")F.push("ERROR");else if(m)F.push(m.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(g)F.push(g.replace(/[[\]]/g,""));return F.push(R),F.join(" ")}let T=Se.stdout.columns||120,A="";if(I==="warning"||I==="error")A=`${m} ${R}`;else if(I==="info"||I==="success")A=`${m} ${g} ${R}`;else A=`${m} ${g} ${Ie.cyan(R)}`;if(!S)return A.trim();let O=L(A).trim().length,_=L(h).length,D=Math.max(1,T-2-O-_);return`${A.trim()}${" ".repeat(D)}${h}`}formatMessage(s,h){if(h.length===1&&Array.isArray(h[0]))return s.replace(/\{(\d+)\}/g,(I,S)=>{let L=Number.parseInt(S,10);return L<h[0].length?String(h[0][L]):I});let m=/%([sdijfo%])/g,g=0,R=s.replace(m,(I,S)=>{if(S==="%")return"%";if(g>=h.length)return I;let L=h[g++];switch(S){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return I}});if(g<h.length)R+=` ${h.slice(g).map((I)=>typeof I==="object"?JSON.stringify(I,null,2):String(I)).join(" ")}`;return R}formatMarkdown(s){if(!s)return s;let h=s;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(m,g,R)=>{let I=Ie.underline(Ie.blue(g)),S=this.toAbsoluteFilePath(R);if(S&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(S)}`,T="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${L}\x1B\\${I}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${R}\x1B\\${I}\x1B]8;;\x1B\\`;return I}),h=h.replace(/`([^`]+)`/g,(m,g)=>Ie.bgGray(g)),h=h.replace(/\*\*([^*]+)\*\*/g,(m,g)=>Ie.bold(g)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(m,g)=>Ie.italic(g)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(m,g)=>Ie.italic(g)),h=h.replace(/~([^~]+)~/g,(m,g)=>Ie.strikethrough(g)),h}supportsHyperlinks(){if(Be())return!1;let s=Se.env;if(!s)return!1;if(s.TERM_PROGRAM==="iTerm.app"||s.TERM_PROGRAM==="vscode"||s.TERM_PROGRAM==="WezTerm")return!0;if(s.WT_SESSION)return!0;if(s.TERM==="xterm-kitty")return!0;let h=s.VTE_VERSION?Number.parseInt(s.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath(s){try{let h=s;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let m=Se.env.HOME||"";if(m)h=h.replace(/^~(?=$|\/)/,m)}if(Zm(h)||h.startsWith("./")||h.startsWith("../"))h=Gm(h);else return null;return cn(h)?h:null}catch{return null}}buildOutputTexts(s){let h=this.shouldStyleConsole()?this.formatMarkdown(s):s,m=s.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:m}}async log(s,h,...m){let g=new Date,R=this.formatConsoleTimestamp(g),I=this.formatFileTimestamp(g),S,L;if(h instanceof Error)S=h.message,L=h.stack;else S=this.formatMessage(h,m);let{consoleText:T,fileText:A}=this.buildOutputTexts(S);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":Oo[s],D=this.options.showTags!==!1&&this.name?Ie.gray(this.formatTag(this.name)):"",F;switch(s){case"debug":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ie.gray(T),level:s}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ie.green(T),level:s}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.error(F),L){let N=L.split(`
|
|
11
11
|
`);for(let W of N)if(W.trim()&&!W.includes(S))console.error(this.formatConsoleMessage({timestamp:R,message:Ie.gray(` ${W}`),level:s,showTimestamp:!1}))}break}}else if(!Be()){if(console.error(`${I} ${this.environment}.${s.toUpperCase()}: ${S}`),L)console.error(L)}if(!this.shouldLog(s))return;let O=`${I} ${this.environment}.${s.toUpperCase()}: ${A}
|
|
12
12
|
`;if(L)O+=`${L}
|
|
13
13
|
`;if(O=O.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(O)}progress(s,h=""){let m={update:(L,T)=>{},finish:(L)=>{},interrupt:(L,T)=>{}};if(!this.enabled)return m;let g=30;if(this.activeProgressBar={total:Math.max(1,s||1),current:0,message:h||"",barLength:g,lastRenderedLine:""},this.shouldStyleConsole()&&!Be()&&Se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,T)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),T!==void 0)this.activeProgressBar.message=T;if(this.shouldStyleConsole()&&!Be()&&Se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,T="info")=>{if(!Be()&&Se.stdout.isTTY)Se.stdout.write(`
|
|
14
14
|
`);if(this[T==="warning"?"warn":T](L),this.activeProgressBar&&this.shouldStyleConsole()&&!Be()&&Se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(s){let h=performance.now();if(this.shouldStyleConsole()){let m=this.options.showTags!==!1&&this.name?Ie.gray(this.formatTag(this.name)):"",g=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:g,icon:this.options.showIcons===!1?"":Ie.blue("\u25D0"),tag:m,message:`${Ie.cyan(s)}...`}))}return async(m)=>{if(!this.enabled)return;let g=performance.now(),R=Math.round(g-h),I=`${s} completed in ${R}ms`,S=new Date,L=this.formatConsoleTimestamp(S),A=`${this.formatFileTimestamp(S)} ${this.environment}.INFO: ${I}`;if(m)A+=` ${JSON.stringify(m)}`;if(A+=`
|
|
15
|
-
`,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let O=this.options.showTags!==!1&&this.name?Ie.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":Ie.green("\u2713"),tag:O,message:`${I}${m?` ${JSON.stringify(m)}`:""}`}))}else if(!Be())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(s,...h){await this.log("debug",s,...h)}async info(s,...h){await this.log("info",s,...h)}async success(s,...h){await this.log("success",s,...h)}async warn(s,...h){await this.log("warning",s,...h)}async error(s,...h){await this.log("error",s,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let s=this.config.rotation,{encrypt:h}=s;return!!h}async only(s){if(!this.enabled)return;return await s()}isEnabled(){return this.enabled}setEnabled(s){this.enabled=s}extend(s){let h=`${this.name}:${s}`,m=new
|
|
15
|
+
`,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let O=this.options.showTags!==!1&&this.name?Ie.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":Ie.green("\u2713"),tag:O,message:`${I}${m?` ${JSON.stringify(m)}`:""}`}))}else if(!Be())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(s,...h){await this.log("debug",s,...h)}async info(s,...h){await this.log("info",s,...h)}async success(s,...h){await this.log("success",s,...h)}async warn(s,...h){await this.log("warning",s,...h)}async error(s,...h){await this.log("error",s,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let s=this.config.rotation,{encrypt:h}=s;return!!h}async only(s){if(!this.enabled)return;return await s()}isEnabled(){return this.enabled}setEnabled(s){this.enabled=s}extend(s){let h=`${this.name}:${s}`,m=new Sn(h,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(m),m}createReadStream(){if(Be())throw Error("createReadStream is not supported in browser environments");if(!cn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Vr(this.currentLogFile,{encoding:"utf8"})}async decrypt(s){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let m=this.keys.get(this.currentKeyId);try{let g=lt.isBuffer(s)?s:lt.from(s,"base64"),R=g.subarray(0,16),I=g.subarray(g.length-16),S=g.subarray(16,g.length-16),L=zm("aes-256-gcm",m,R);L.setAuthTag(I);let T=L.update(S),A=L.final(),O=T.length+A.length,_=lt.allocUnsafe(O);return T.copy(_,0),A.copy(_,T.length),_.toString("utf8")}catch(g){throw Error(`Decryption failed: ${g instanceof Error?g.message:String(g)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Be()}isServerMode(){return!Be()}setTestEncryptionKey(s,h){this.currentKeyId=s,this.keys.set(s,h)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(s){if(!this.enabled)return;let h=new Date,m=this.formatConsoleTimestamp(h),g=this.formatFileTimestamp(h),{consoleText:R,fileText:I}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let L=R.split(`
|
|
16
16
|
`),T=Math.max(...L.map((D)=>D.length))+2,A=`\u250C${"\u2500".repeat(T)}\u2510`,O=`\u2514${"\u2500".repeat(T)}\u2518`,_=L.map((D)=>this.formatConsoleMessage({timestamp:m,message:Ie.cyan(D),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:m,message:Ie.cyan(A),showTimestamp:!1})),_.forEach((D)=>console.error(D)),console.error(this.formatConsoleMessage({timestamp:m,message:Ie.cyan(O),showTimestamp:!1}))}else if(!Be())console.error(`${g} ${this.environment}.INFO: [BOX] ${I}`);let S=`${g} ${this.environment}.INFO: [BOX] ${I}
|
|
17
17
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(S)}async prompt(s){if(Be())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${Ie.cyan("?")} ${s} (y/n) `);let m=(g)=>{let R=g.toString().trim().toLowerCase();Se.stdin.removeListener("data",m);try{if(typeof Se.stdin.setRawMode==="function")Se.stdin.setRawMode(!1)}catch{}Se.stdin.pause(),console.error(""),h(R==="y"||R==="yes")};try{if(typeof Se.stdin.setRawMode==="function")Se.stdin.setRawMode(!0)}catch{}Se.stdin.resume(),Se.stdin.once("data",m)})}setFancy(s){this.fancy=s}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(s,...h){if(!this.enabled)return;let m=s;if(h&&h.length>0){let T=/%([sdijfo%])/g,A=0;if(m=s.replace(T,(O,_)=>{if(_==="%")return"%";if(A>=h.length)return O;let D=h[A++];switch(_){case"s":return String(D);case"d":case"i":return Number(D).toString();case"j":case"o":return JSON.stringify(D,null,2);default:return O}}),A<h.length)m+=` ${h.slice(A).map((O)=>typeof O==="object"?JSON.stringify(O,null,2):String(O)).join(" ")}`}let{consoleText:g,fileText:R}=this.buildOutputTexts(m);if(this.shouldStyleConsole()){let T=this.options.showTags!==!1&&this.name?Ie.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${Ie.blue("\u25D0")} `;console.error(`${A}${T} ${Ie.cyan(g)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${R}
|
|
18
18
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(s,h=!1){if(!this.enabled||!this.shouldStyleConsole()||!Se.stdout.isTTY)return;let m=Math.min(100,Math.max(0,Math.round(s.current/s.total*100))),g=Math.round(s.barLength*m/100),R=s.barLength-g,I=Ie.green("\u2501".repeat(g)),S=Ie.gray("\u2501".repeat(R)),L=`[${I}${S}]`,T=`${m}%`.padStart(4),A=s.message?` ${s.message}`:"",O=this.options.showIcons===!1?"":h||m===100?Ie.green("\u2713"):Ie.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${Ie.gray(this.formatTag(this.name))}`:"",D=`\r${O}${_} ${L} ${T}${A}`,F=Se.stdout.columns||80,N=" ".repeat(Math.max(0,F-D.replace(this.ANSI_PATTERN,"").length));if(s.lastRenderedLine=`${D}${N}`,Se.stdout.write(s.lastRenderedLine),h)Se.stdout.write(`
|
|
19
|
-
`)}finishProgressBar(s,h){if(!this.enabled||!this.fancy||Be()||!Se.stdout.isTTY){this.activeProgressBar=null;return}if(s.current<s.total)s.current=s.total;if(h)s.message=h;this.renderProgressBar(s,!0),this.activeProgressBar=null}async clear(s={}){if(Be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await
|
|
19
|
+
`)}finishProgressBar(s,h){if(!this.enabled||!this.fancy||Be()||!Se.stdout.isTTY){this.activeProgressBar=null;return}if(s.current<s.total)s.current=s.total;if(h)s.message=h;this.renderProgressBar(s,!0),this.activeProgressBar=null}async clear(s={}){if(Be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await un(this.config.logDirectory),m=[];for(let g of h){if(!(s.name?new RegExp(s.name.replace("*",".*")).test(g):g.startsWith(this.name))||!g.endsWith(".log"))continue;let I=Et(this.config.logDirectory,g);if(s.before)try{if((await St(I)).mtime>=s.before)continue}catch(S){console.error(`Failed to get stats for file ${I}:`,S);continue}m.push(I)}if(m.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${m.length} log file(s)...`);for(let g of m)try{await fn(g),console.warn(`Deleted log file: ${g}`)}catch(R){console.error(`Failed to delete log file ${g}:`,R)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}async function vo(s,h={}){let{maxRetries:m=3,retryDelay:g=1000,isRetryable:R=()=>!0,fallback:I}=h,S=Error("Unknown error occurred");for(let L=0;L<=m;L++)try{return await s()}catch(T){if(S=T instanceof Error?T:Error(String(T)),L===m||!R(S))break;if(g>0)await new Promise((A)=>setTimeout(A,g))}if(I!==void 0)return I;throw S instanceof Error?S:Error(`Unknown error: ${String(S)}`)}function Io(s){return s instanceof Xe}function dh(s){return s instanceof En}function ph(s){if(Io(s))return s.code==="FILE_SYSTEM_ERROR"||s.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((m)=>s.message.toLowerCase().includes(m.toLowerCase()))}class On{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(s,h)=>h==="boolean"||["true","false","1","0","yes","no"].includes(s.toLowerCase()),parse:(s)=>{let h=s.toLowerCase();return["true","1","yes"].includes(h)}},{name:"number",canParse:(s,h)=>h==="number"||!Number.isNaN(Number(s))&&!Number.isNaN(Number.parseFloat(s)),parse:(s)=>{let h=Number(s);if(Number.isNaN(h))throw TypeError(`Cannot parse "${s}" as number`);return h}},{name:"array",canParse:(s,h)=>h==="array"||s.startsWith("[")||s.includes(","),parse:(s)=>{try{let h=JSON.parse(s);if(Array.isArray(h))return h}catch{}return s.split(",").map((h)=>h.trim())}},{name:"json",canParse:(s,h)=>h==="object"||(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]")),parse:(s)=>{try{return JSON.parse(s)}catch(h){throw Error(`Cannot parse "${s}" as JSON: ${h}`)}}}]}async applyEnvironmentVariables(s,h,m={}){let{prefix:g,useCamelCase:R=!0,useBackwardCompatibility:I=!0,customParsers:S={},verbose:L=!1,trackPerformance:T=!0}=m,A=async()=>{if(!s)return{config:h,source:{type:"environment",priority:50,timestamp:new Date}};let O=g||this.generateEnvPrefix(s),_={...h};return this.processObject(_,[],O,{useCamelCase:R,useBackwardCompatibility:I,customParsers:S,verbose:L,configName:s}),{config:_,source:{type:"environment",priority:50,timestamp:new Date}}};if(T)return Gt.track("applyEnvironmentVariables",A,{configName:s});return A()}generateEnvPrefix(s){return s.toUpperCase().replace(/-/g,"_")}formatEnvKey(s,h){if(!h)return s.toUpperCase();return s.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(s,h,m,g){for(let[R,I]of Object.entries(s)){let S=[...h,R],L=S.map((O)=>this.formatEnvKey(O,g.useCamelCase)),T=`${m}_${L.join("_")}`,A=g.useBackwardCompatibility?`${m}_${S.map((O)=>O.toUpperCase()).join("_")}`:null;if(g.verbose);if(typeof I==="object"&&I!==null&&!Array.isArray(I))this.processObject(I,S,m,g);else{let O=mn.env[T]||(A?mn.env[A]:void 0);if(O!==void 0){if(g.verbose){let _=mn.env[T]?T:A}try{s[R]=this.parseEnvironmentValue(O,typeof I,T,g.customParsers,g.configName)}catch(_){if(_ instanceof Ln)throw _;throw pt.envVar(T,O,typeof I,g.configName)}}}}}parseEnvironmentValue(s,h,m,g,R){for(let[I,S]of Object.entries(g))try{return S(s)}catch{continue}for(let I of this.defaultParsers)if(I.canParse(s,h))try{return I.parse(s)}catch{throw pt.envVar(m,s,`${h} (via ${I.name} parser)`,R)}return s}getEnvironmentVariables(s){let h={},m=s.toUpperCase();for(let[g,R]of Object.entries(mn.env))if(g.startsWith(m)&&R!==void 0)h[g]=R;return h}validateEnvironmentVariable(s,h,m){let g=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(s))g.push(`Environment variable key "${s}" should only contain uppercase letters, numbers, and underscores`);if(m)try{this.parseEnvironmentValue(s,h,m,{})}catch(R){g.push(`Cannot parse value "${h}" as ${m}: ${R}`)}return{isValid:g.length===0,errors:g}}generateEnvVarDocs(s,h,m={}){let{prefix:g,format:R="text"}=m,I=g||this.generateEnvPrefix(s),S=[];switch(this.extractEnvVarInfo(h,[],I,S),R){case"markdown":return this.formatAsMarkdown(S,s);case"json":return JSON.stringify(S,null,2);default:return this.formatAsText(S,s)}}extractEnvVarInfo(s,h,m,g){for(let[R,I]of Object.entries(s)){let S=[...h,R],L=`${m}_${S.map((T)=>this.formatEnvKey(T,!0)).join("_")}`;if(typeof I==="object"&&I!==null&&!Array.isArray(I))this.extractEnvVarInfo(I,S,m,g);else g.push({key:L,type:Array.isArray(I)?"array":typeof I,description:`Configuration for ${S.join(".")}`,example:this.generateExample(I)})}}generateExample(s){if(Array.isArray(s))return JSON.stringify(s);if(typeof s==="object"&&s!==null)return JSON.stringify(s);return String(s)}formatAsText(s,h){let m=`Environment Variables for ${h}:
|
|
20
20
|
|
|
21
21
|
`;for(let g of s)m+=`${g.key}
|
|
22
22
|
`,m+=` Type: ${g.type}
|
|
@@ -28,179 +28,180 @@ import{i,t,f,k,y,p,b,r,n,o,v,a,e,u,d,w,l,c}from"./chunk-rg0g2fzg.js";var pm=impo
|
|
|
28
28
|
`;m+=`| Variable | Type | Description | Example |
|
|
29
29
|
`,m+=`|----------|------|-------------|----------|
|
|
30
30
|
`;for(let g of s)m+=`| \`${g.key}\` | ${g.type} | ${g.description} | \`${g.example}\` |
|
|
31
|
-
`;return m}}function ch(s,h){let m=Io("process");if(typeof m>"u"||!m.env)return h;let g=m.env[s];return g!==void 0?g:h}function ko(s,h,m={}){return $o(s,h,m,new WeakMap)}function $o(s,h,m,g){let{arrayMergeMode:R="replace",skipNullish:I=!1,customMerger:S}=m;if(h===null||h===void 0)return I?s:h;if(S){let L=S(s,h);if(L!==void 0)return L}if(Array.isArray(h)||Array.isArray(s))return Po(s,h,R,g);if(!et(h)||!et(s))return h;return hh(s,h,m,g)}function Po(s,h,m,g){if(Array.isArray(h)&&!Array.isArray(s))return h;if(Array.isArray(s)&&!Array.isArray(h))return h;if(Array.isArray(h)&&Array.isArray(s))switch(m){case"replace":return h;case"concat":return uh(s,h);case"smart":return fh(s,h,g);default:return h}return h}function uh(s,h){let m=[...h];for(let g of s)if(!m.some((R)=>$i(R,g)))m.push(g);return m}function fh(s,h,m){if(h.length===0)return s;if(s.length===0)return h;if(et(h[0])&&et(s[0]))return mh(s,h,m);if(h.every((g)=>typeof g==="string")&&s.every((g)=>typeof g==="string")){let g=[...h];for(let R of s)if(!g.includes(R))g.push(R);return g}return h}function mh(s,h,m){let g=[...h];for(let R of s){if(!et(R)){g.push(R);continue}let I=["id","name","key","path","type"],S=!1;for(let L of I)if(L in R){if(g.find((A)=>et(A)&&(L in A)&&A[L]===R[L])){S=!0;break}}if(!S)g.push(R)}return g}function hh(s,h,m,g){let R=h;if(et(R)&&g.has(R))return g.get(R);let I={...s};if(et(R))g.set(R,I);for(let S in R){if(!Object.prototype.hasOwnProperty.call(R,S))continue;let L=R[S],T=I[S];if(m.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){I[S]=L;continue}if(et(L)&&et(T))I[S]=$o(T,L,m,g);else if(Array.isArray(L)||Array.isArray(T))I[S]=Po(T,L,m.arrayMergeMode||"smart",g);else I[S]=L}return I}function Di(s,h,m="replace"){return ko(s,h,{arrayMergeMode:m==="replace"?"replace":"smart",skipNullish:!0})}function $i(s,h){if(s===h)return!0;if(Array.isArray(s)&&Array.isArray(h)){if(s.length!==h.length)return!1;for(let m=0;m<s.length;m++)if(!$i(s[m],h[m]))return!1;return!0}if(et(s)&&et(h)){let m=Object.keys(s),g=Object.keys(h);if(m.length!==g.length)return!1;for(let R of m){if(!Object.prototype.hasOwnProperty.call(h,R))return!1;if(!$i(s[R],h[R]))return!1}return!0}return!1}function et(s){return Boolean(s&&typeof s==="object"&&!Array.isArray(s))}class An{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(s,h,m={}){let{arrayStrategy:g="replace",useCache:R=!0,cacheTtl:I,trackPerformance:S=!0,verbose:L=!1}=m;if(R){let A=_t.getWithFileCheck("file",s);if(A){if(L)console.log(`Configuration loaded from cache: ${s}`);return A}}let T=async()=>{if(!fn(s))return null;try{let A=`?t=${Date.now()}`,O=await import(s+A),_=O.default||O,D="default"in O,F=Object.keys(O).length>0;if(!D&&!F)throw new Vt(s,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new Vt(s,Error("Configuration must export a valid object"),"unknown");let B={config:Di(h,_,g),source:{type:"file",path:s,priority:100,timestamp:new Date}};if(R)_t.setWithFileCheck("file",B,s,I);return B}catch(A){throw A instanceof Error?pt.configLoad(s,A):pt.configLoad(s,Error(String(A)))}};if(S)return Zt.track("loadFromPath",T,{path:s});return T()}async tryLoadFromPaths(s,h,m={}){for(let g of s)try{let R=await this.loadFromPath(g,h,m);if(R)return R}catch(R){if(R instanceof Error&&R.name==="ConfigLoadError")throw R;if(m.verbose)console.warn(`Failed to load config from ${g}:`,R)}return null}generateConfigPaths(s,h,m){let g=this.generateNamePatterns(s,m),R=[];for(let I of g)for(let S of this.extensions)R.push(fi(h,`${I}${S}`));return R}generateNamePatterns(s,h){let m=[];if(m.push("config",".config"),s)m.push(s,`.${s}.config`,`${s}.config`,`.${s}`);if(h){if(m.push(h,`.${h}.config`,`${h}.config`,`.${h}`),s)m.push(`${s}.${h}.config`,`.${s}.${h}.config`)}return m.filter(Boolean)}checkFileAccess(s){return wo(async()=>fn(s),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(s,h,m){let g=[];if(!fn(s))return g;if(h||m){let R=this.generateNamePatterns(h||"",m);for(let I of R)for(let S of this.extensions){let L=fi(s,`${I}${S}`);if(await this.checkFileAccess(L))g.push(L)}}else try{let{readdirSync:R}=await import("fs"),I=R(s);for(let S of I)if(this.looksLikeConfigFile(S)){let L=fi(s,S);if(await this.checkFileAccess(L))g.push(L)}}catch{return[]}return g}looksLikeConfigFile(s){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((m)=>m.test(s))}async validateConfigFile(s){let h=[];try{if(!fn(s))return h.push("Configuration file does not exist"),h;let m=await import(s),g=m.default||m;if(g===void 0)h.push("Configuration file must export a default value or named exports");else if(typeof g!=="object"||g===null)h.push("Configuration must be an object");else if(Array.isArray(g))h.push("Configuration cannot be an array at the root level");if(s.endsWith(".json"))try{let{readFileSync:R}=await import("fs"),I=R(s,"utf8");JSON.parse(I)}catch(R){h.push(`Invalid JSON syntax: ${R}`)}}catch(m){h.push(`Failed to load configuration file: ${m}`)}return h}async getFileModificationTime(s){try{let{statSync:h}=await import("fs");return h(s).mtime}catch{return null}}async preloadConfigurations(s,h={}){let m=new Map;return await Promise.allSettled(s.map(async(g)=>{try{let R=await this.loadFromPath(g,{},h);if(R)m.set(g,R.config)}catch(R){if(h.verbose)console.warn(`Failed to preload ${g}:`,R)}})),m}}class Fi{async validateConfiguration(s,h,m={}){let{stopOnFirstError:g=!1,validateRequired:R=!0,validateTypes:I=!0,customRules:S=[],trackPerformance:L=!0,verbose:T=!1}=m,A=async()=>{let O=[],_=[],D={stopOnFirstError:g,validateRequired:R,validateTypes:I,customRules:S,trackPerformance:L,verbose:T};try{if(typeof h==="string")return await this.validateWithSchemaFile(s,h,D);else if(Array.isArray(h))return this.validateWithRules(s,[...h,...S],D);else return this.validateWithJSONSchema(s,h,D)}catch(F){return O.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:O,warnings:_}}};if(L)return await Zt.track("validateConfiguration",A);return A()}async validateWithSchemaFile(s,h,m){try{if(!qm(h))throw new Ht(h,[{path:"",message:"Schema file does not exist"}]);let g=await import(h),R=g.default||g;if(Array.isArray(R))return this.validateWithRules(s,R,m);else return this.validateWithJSONSchema(s,R,m)}catch(g){throw new Ht(h,[{path:"",message:`Failed to load schema: ${g}`}])}}validateWithJSONSchema(s,h,m){let g=[],R=[];return this.validateObjectAgainstSchema(s,h,"",g,R,m),{isValid:g.length===0,errors:g,warnings:R}}validateObjectAgainstSchema(s,h,m,g,R,I){if(I.validateTypes&&h.type){let S=Array.isArray(s)?"array":typeof s,L=Array.isArray(h.type)?h.type:[h.type];if(!L.includes(S)){if(g.push({path:m,message:`Expected type ${L.join(" or ")}, got ${S}`,expected:L.join(" or "),actual:S,rule:"type"}),I.stopOnFirstError)return}}if(h.enum&&!h.enum.includes(s)){if(g.push({path:m,message:`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:s,rule:"enum"}),I.stopOnFirstError)return}if(typeof s==="string"){if(h.minLength!==void 0&&s.length<h.minLength)g.push({path:m,message:`String length must be at least ${h.minLength}`,expected:`>= ${h.minLength}`,actual:s.length,rule:"minLength"});if(h.maxLength!==void 0&&s.length>h.maxLength)g.push({path:m,message:`String length must not exceed ${h.maxLength}`,expected:`<= ${h.maxLength}`,actual:s.length,rule:"maxLength"});if(h.pattern){if(!new RegExp(h.pattern).test(s))g.push({path:m,message:`String does not match pattern ${h.pattern}`,expected:h.pattern,actual:s,rule:"pattern"})}}if(typeof s==="number"){if(h.minimum!==void 0&&s<h.minimum)g.push({path:m,message:`Value must be at least ${h.minimum}`,expected:`>= ${h.minimum}`,actual:s,rule:"minimum"});if(h.maximum!==void 0&&s>h.maximum)g.push({path:m,message:`Value must not exceed ${h.maximum}`,expected:`<= ${h.maximum}`,actual:s,rule:"maximum"})}if(Array.isArray(s)&&h.items)for(let S=0;S<s.length;S++){let L=m?`${m}[${S}]`:`[${S}]`;if(this.validateObjectAgainstSchema(s[S],h.items,L,g,R,I),I.stopOnFirstError&&g.length>0)return}if(s&&typeof s==="object"&&!Array.isArray(s)){let S=s;if(I.validateRequired&&h.required){for(let L of h.required)if(!(L in S)){if(g.push({path:m?`${m}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),I.stopOnFirstError)return}}if(h.properties){for(let[L,T]of Object.entries(h.properties))if(L in S){let A=m?`${m}.${L}`:L;if(this.validateObjectAgainstSchema(S[L],T,A,g,R,I),I.stopOnFirstError&&g.length>0)return}}if(h.additionalProperties===!1){let L=new Set(Object.keys(h.properties||{}));for(let T of Object.keys(S))if(!L.has(T))R.push({path:m?`${m}.${T}`:T,message:`Additional property '${T}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(s,h,m){let g=[],R=[];for(let I of h)try{let S=this.getValueByPath(s,I.path),L=this.validateWithRule(S,I,I.path);if(g.push(...L),m.stopOnFirstError&&g.length>0)break}catch(S){g.push({path:I.path,message:`Rule validation failed: ${S}`,rule:"system"})}return{isValid:g.length===0,errors:g,warnings:R}}validateWithRule(s,h,m){let g=[];if(h.required&&(s===void 0||s===null))return g.push({path:m,message:h.message||`Property '${m}' is required`,expected:"required",rule:"required"}),g;if(s===void 0||s===null)return g;if(h.type){let R=Array.isArray(s)?"array":typeof s;if(R!==h.type)g.push({path:m,message:h.message||`Expected type ${h.type}, got ${R}`,expected:h.type,actual:R,rule:"type"})}if(h.min!==void 0){let R=Array.isArray(s)?s.length:typeof s==="string"?s.length:typeof s==="number"?s:0;if(R<h.min)g.push({path:m,message:h.message||`Value must be at least ${h.min}`,expected:`>= ${h.min}`,actual:R,rule:"min"})}if(h.max!==void 0){let R=Array.isArray(s)?s.length:typeof s==="string"?s.length:typeof s==="number"?s:0;if(R>h.max)g.push({path:m,message:h.message||`Value must not exceed ${h.max}`,expected:`<= ${h.max}`,actual:R,rule:"max"})}if(h.pattern&&typeof s==="string"){if(!h.pattern.test(s))g.push({path:m,message:h.message||`Value does not match pattern ${h.pattern}`,expected:h.pattern.toString(),actual:s,rule:"pattern"})}if(h.enum&&!h.enum.includes(s))g.push({path:m,message:h.message||`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:s,rule:"enum"});if(h.validator){let R=h.validator(s);if(R)g.push({path:m,message:h.message||R,rule:"custom"})}return g}getValueByPath(s,h){if(!h)return s;let m=h.split("."),g=s;for(let R of m)if(g&&typeof g==="object"&&R in g)g=g[R];else return;return g}generateRulesFromInterface(s){let h=[],m=s.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let g of m){let[,R,I,S]=g;h.push({path:R,required:!I,type:this.mapTypeScriptType(S)})}return h}mapTypeScriptType(s){switch(s.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Lo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ni{fileLoader=new An;envProcessor=new Tn;validator=new Fi;async loadConfig(s){let h=Date.now(),{cache:m,performance:g,schema:R,validate:I,...S}=s;try{if(m?.enabled){let T=this.checkCache(S.name||"",S);if(T)return T}let L;try{L=await this.loadConfigurationStrategies(S,!0,m)}catch(T){let A=S.__strictErrorHandling;if(T instanceof Error&&T.name==="ConfigNotFoundError"){if(A)throw T;L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:[`No configuration file found for "${S.name||"config"}", using defaults with environment variables`]}}else if(T instanceof Error&&T.name==="ConfigLoadError"){let O=T.message.includes("EACCES")||T.message.includes("EPERM")||T.message.includes("permission denied"),_=!O&&(T.message.includes("syntax")||T.message.includes("Expected")||T.message.includes("Unexpected")||T.message.includes("BuildMessage")||T.message.includes("errors building")),D=T.message.includes("Configuration must export a valid object")||T.message.includes("Configuration file is empty and exports nothing");if(A&&(D||O))throw T;if(_&&(!A||!D))L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!A)L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:[`Configuration loading error, using defaults: ${T.message}`]};else throw T}else L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${T instanceof Error?T.message:String(T)}`]}}if(R||I)await this.validateConfiguration(L.config,R,I,S.name);if(m?.enabled&&L)this.cacheResult(S.name||"",L,m,S);if(g?.enabled){let T={operation:"loadConfig",duration:Date.now()-h,configName:S.name,timestamp:new Date};if(g.onMetrics)g.onMetrics(T);if(g.slowThreshold&&T.duration>g.slowThreshold)nt.warn(`Slow configuration loading detected: ${T.duration}ms for ${S.name}`);L.metrics=T}return L}catch(L){let T=Date.now()-h;throw nt.error(`Configuration loading failed after ${T}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(s,h=!1,m){let{name:g="",alias:R,cwd:I,configDir:S,defaultConfig:L,checkEnv:T=!0,arrayStrategy:A="replace",verbose:O=!1}=s,_=I||xt.cwd(),D=[],F=await this.loadLocalConfiguration(g,R,_,S,L,A,O,T,m);if(F)return D.push(...this.getLocalSearchPaths(g,R,_,S)),this.finalizeResult(F,D,T,g,O);let N=await this.loadHomeConfiguration(g,R,L,A,O,T);if(N)return D.push(...this.getHomeSearchPaths(g,R)),this.finalizeResult(N,D,T,g,O);let W=await this.loadPackageJsonConfiguration(g,R,_,L,A,O,T);if(W)return D.push(Ye(_,"package.json")),this.finalizeResult(W,D,T,g,O);if(D.push(...this.getAllSearchPaths(g,R,_,S)),h)throw pt.configNotFound(g,D,R);return{...await this.applyEnvironmentVariables(g,L,T,O),warnings:[`No configuration file found for "${g}"${R?` or alias "${R}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(s,h,m,g,R,I,S,L,T){let A=L?qt(s,R,S):R,O=this.getLocalDirectories(m,g);for(let _ of O){if(S)nt.info(`Searching for configuration in: ${_}`);let D=this.fileLoader.generateConfigPaths(s,_,h),F=await this.fileLoader.tryLoadFromPaths(D,A,{arrayStrategy:I,verbose:S,cacheTtl:T?.ttl,useCache:!T?.ttl||T.ttl>100});if(F){if(S)nt.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration(s,h,m,g,R,I){if(!s)return null;let S=I?qt(s,m,R):m,L=[Ye(vt(),".config",s),Ye(vt(),".config"),vt()];for(let T of L){if(R)nt.info(`Checking home directory: ${T}`);let A=this.fileLoader.generateConfigPaths(s,T,h),O=await this.fileLoader.tryLoadFromPaths(A,S,{arrayStrategy:g,verbose:R});if(O){if(R)nt.success(`Configuration loaded from home directory: ${O.source.path}`);return O}}return null}async loadPackageJsonConfiguration(s,h,m,g,R,I,S){let L=S?qt(s,g,I):g;try{let T=Ye(m,"package.json");if(!Ri(T))return null;let A=await import(T),O=A[s],_=s;if(!O&&h)O=A[h],_=h;if(O&&typeof O==="object"&&!Array.isArray(O)){if(I)nt.success(`Configuration loaded from package.json: ${_}`);return{config:Di(L,O,R),source:{type:"package.json",path:T,priority:30,timestamp:new Date}}}}catch(T){if(I)nt.warn("Failed to load package.json:",[T instanceof Error?T:Error(String(T))])}return null}async applyEnvironmentVariables(s,h,m,g){if(!m||!s||typeof h!=="object"||h===null||Array.isArray(h))return{config:h,source:{type:"default",priority:10,timestamp:new Date}};return{config:qt(s,h,g),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(s,h,m,g,R){return{config:s.config,source:s.source,path:s.source.path}}async validateConfiguration(s,h,m,g){let R=[];if(m){let I=m(s);if(I)R.push(...I)}if(h){let I=await this.validator.validateConfiguration(s,h);if(!I.isValid)R.push(...I.errors.map((S)=>S.path?`${S.path}: ${S.message}`:S.message))}if(R.length>0)throw pt.configValidation(g||"unknown",R,g)}checkCache(s,h){let m=this.generateCacheKey(s,h);return _t.get(m)||null}cacheResult(s,h,m,g){let R=this.generateCacheKey(s,g);_t.set(R,h,void 0,m.ttl)}generateCacheKey(s,h){let m=[s];if(h.alias)m.push(`alias:${h.alias}`);if(h.cwd)m.push(`cwd:${h.cwd}`);if(h.configDir)m.push(`configDir:${h.configDir}`);if("checkEnv"in h)m.push(`checkEnv:${h.checkEnv}`);return m.join("|")}getLocalDirectories(s,h){return Array.from(new Set([s,Ye(s,"config"),Ye(s,".config"),h?Ye(s,h):void 0].filter(Boolean)))}getAllSearchPaths(s,h,m,g){let R=[];return R.push(...this.getLocalSearchPaths(s,h,m,g)),R.push(...this.getHomeSearchPaths(s,h)),R.push(Ye(m,"package.json")),R}getLocalSearchPaths(s,h,m,g){let R=this.getLocalDirectories(m,g),I=[];for(let S of R)I.push(...this.fileLoader.generateConfigPaths(s,S,h));return I}getHomeSearchPaths(s,h){if(!s)return[];let m=[Ye(vt(),".config",s),Ye(vt(),".config"),vt()],g=[];for(let R of m)g.push(...this.fileLoader.generateConfigPaths(s,R,h));return g}async loadConfigWithResult(s){return this.loadConfig(s)}}function Zr(s){let m=!(s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"))&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")),g=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");return m||g}async function dh(s){return mt.loadConfig({...s,__strictErrorHandling:!0})}async function vo(s){let h="defaultConfig"in s&&s.defaultConfig!==void 0?s.defaultConfig:{},m="cache"in s||"performance"in s||"schema"in s||"validate"in s;try{let g;if(m)g=await mt.loadConfig(s);else g=await mt.loadConfig({...s,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}});return g?.config??h}catch(g){let R=g instanceof Error?g.name:"UnknownError",I=g instanceof Error?g.message:String(g);if(!(R==="ConfigNotFoundError"||R==="ConfigLoadError"||R==="ConfigValidationError"||I.includes("config"))&&s.verbose)nt.warn("Unexpected error loading config, using defaults:",[g instanceof Error?g:Error(String(g))]);let L=m?{...s,defaultConfig:h}:{...s,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in s?s.checkEnv!==!1:!0)return(await mt.applyEnvironmentVariables(L.name||"",h,!0,L.verbose||!1))?.config??h;return h}}async function ph(s={defaultConfig:{}}){if(typeof s==="string"){let{cwd:h}=await import("process");try{return(await mt.loadConfig({name:s,cwd:h(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(m){if(m instanceof Error&&(m.name==="ConfigNotFoundError"||m.name==="ConfigLoadError"&&Zr(m)))return(await mt.applyEnvironmentVariables(s,{},!0,!1)).config;throw m}}try{return(await mt.loadConfig({...s,cwd:s.cwd||xt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(h){if(h instanceof Error&&(h.name==="ConfigNotFoundError"||h.name==="ConfigLoadError"&&Zr(h)))return(await mt.applyEnvironmentVariables(s.name||"",s.defaultConfig||{},s.checkEnv!==!1,s.verbose||!1)).config;throw h}}async function gh(s,h,m="replace"){let g=new An;try{let R=await g.loadFromPath(s,h,{arrayStrategy:m,useCache:!1,trackPerformance:!1});return R?R.config:null}catch{return null}}function qt(s,h,m=!1){let g=new Tn,R=s.toUpperCase().replace(/[^A-Z0-9]/g,"_");function I(S,L=[]){let T={...S};for(let[A,O]of Object.entries(S)){let _=[...L,A],D=[`${R}_${_.join("_").toUpperCase()}`,`${R}_${_.map((W)=>W.toUpperCase()).join("")}`,`${R}_${_.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,N;for(let W of D)if(F=xt.env[W],F!==void 0){N=W;break}if(F!==void 0&&N)if(typeof O==="boolean")T[A]=["true","1","yes"].includes(F.toLowerCase());else if(typeof O==="number"){let W=Number(F);if(!Number.isNaN(W))T[A]=W}else if(Array.isArray(O))try{T[A]=JSON.parse(F)}catch{T[A]=F.split(",").map((W)=>W.trim())}else T[A]=F;else if(O&&typeof O==="object"&&!Array.isArray(O))T[A]=I(O,_)}return T}return I(h)}function yh(s){let h=Ye(xt.cwd(),s.configDir),m=Ye(xt.cwd(),s.generatedDir),g=Ye(m,"config-types.ts");if(!Ri(Tr(g)))Rm(Tr(g),{recursive:!0,mode:511});let R=Ri(h)?km(h).map((S)=>S.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],I=`// Generated by bunfig v${Vh}
|
|
31
|
+
`;return m}}function gh(s,h){let m=Lo("process");if(typeof m>"u"||!m.env)return h;let g=m.env[s];return g!==void 0?g:h}function Mo(s,h,m={}){return Co(s,h,m,new WeakMap)}function Co(s,h,m,g){let{arrayMergeMode:R="replace",skipNullish:I=!1,customMerger:S}=m;if(h===null||h===void 0)return I?s:h;if(S){let L=S(s,h);if(L!==void 0)return L}if(Array.isArray(h)||Array.isArray(s))return So(s,h,R,g);if(!et(h)||!et(s))return h;return wh(s,h,m,g)}function So(s,h,m,g){if(Array.isArray(h)&&!Array.isArray(s))return h;if(Array.isArray(s)&&!Array.isArray(h))return h;if(Array.isArray(h)&&Array.isArray(s))switch(m){case"replace":return h;case"concat":return yh(s,h);case"smart":return bh(s,h,g);default:return h}return h}function yh(s,h){let m=[...h];for(let g of s)if(!m.some((R)=>Ci(R,g)))m.push(g);return m}function bh(s,h,m){if(h.length===0)return s;if(s.length===0)return h;if(et(h[0])&&et(s[0]))return xh(s,h,m);if(h.every((g)=>typeof g==="string")&&s.every((g)=>typeof g==="string")){let g=[...h];for(let R of s)if(!g.includes(R))g.push(R);return g}return h}function xh(s,h,m){let g=[...h];for(let R of s){if(!et(R)){g.push(R);continue}let I=["id","name","key","path","type"],S=!1;for(let L of I)if(L in R){if(g.find((A)=>et(A)&&(L in A)&&A[L]===R[L])){S=!0;break}}if(!S)g.push(R)}return g}function wh(s,h,m,g){let R=h;if(et(R)&&g.has(R))return g.get(R);let I={...s};if(et(R))g.set(R,I);for(let S in R){if(!Object.prototype.hasOwnProperty.call(R,S))continue;let L=R[S],T=I[S];if(m.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){I[S]=L;continue}if(et(L)&&et(T))I[S]=Co(T,L,m,g);else if(Array.isArray(L)||Array.isArray(T))I[S]=So(T,L,m.arrayMergeMode||"smart",g);else I[S]=L}return I}function ji(s,h,m="replace"){return Mo(s,h,{arrayMergeMode:m==="replace"?"replace":"smart",skipNullish:!0})}function Ci(s,h){if(s===h)return!0;if(Array.isArray(s)&&Array.isArray(h)){if(s.length!==h.length)return!1;for(let m=0;m<s.length;m++)if(!Ci(s[m],h[m]))return!1;return!0}if(et(s)&&et(h)){let m=Object.keys(s),g=Object.keys(h);if(m.length!==g.length)return!1;for(let R of m){if(!Object.prototype.hasOwnProperty.call(h,R))return!1;if(!Ci(s[R],h[R]))return!1}return!0}return!1}function et(s){return Boolean(s&&typeof s==="object"&&!Array.isArray(s))}class _n{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(s,h,m={}){let{arrayStrategy:g="replace",useCache:R=!0,cacheTtl:I,trackPerformance:S=!0,verbose:L=!1}=m;if(R){let A=_t.getWithFileCheck("file",s);if(A){if(L)console.log(`Configuration loaded from cache: ${s}`);return A}}let T=async()=>{if(!hn(s))return null;try{let A=`?t=${Date.now()}`,O=await import(s+A),_=O.default||O,D="default"in O,F=Object.keys(O).length>0;if(!D&&!F)throw new Ht(s,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new Ht(s,Error("Configuration must export a valid object"),"unknown");let B={config:ji(h,_,g),source:{type:"file",path:s,priority:100,timestamp:new Date}};if(R)_t.setWithFileCheck("file",B,s,I);return B}catch(A){throw A instanceof Error?pt.configLoad(s,A):pt.configLoad(s,Error(String(A)))}};if(S)return Gt.track("loadFromPath",T,{path:s});return T()}async tryLoadFromPaths(s,h,m={}){for(let g of s)try{let R=await this.loadFromPath(g,h,m);if(R)return R}catch(R){if(R instanceof Error&&R.name==="ConfigLoadError")throw R;if(m.verbose)console.warn(`Failed to load config from ${g}:`,R)}return null}generateConfigPaths(s,h,m){let g=this.generateNamePatterns(s,m),R=[];for(let I of g)for(let S of this.extensions)R.push(gi(h,`${I}${S}`));return R}generateNamePatterns(s,h){let m=[];if(m.push("config",".config"),s)m.push(s,`.${s}.config`,`${s}.config`,`.${s}`);if(h){if(m.push(h,`.${h}.config`,`${h}.config`,`.${h}`),s)m.push(`${s}.${h}.config`,`.${s}.${h}.config`)}return m.filter(Boolean)}checkFileAccess(s){return vo(async()=>hn(s),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(s,h,m){let g=[];if(!hn(s))return g;if(h||m){let R=this.generateNamePatterns(h||"",m);for(let I of R)for(let S of this.extensions){let L=gi(s,`${I}${S}`);if(await this.checkFileAccess(L))g.push(L)}}else try{let{readdirSync:R}=await import("fs"),I=R(s);for(let S of I)if(this.looksLikeConfigFile(S)){let L=gi(s,S);if(await this.checkFileAccess(L))g.push(L)}}catch{return[]}return g}looksLikeConfigFile(s){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((m)=>m.test(s))}async validateConfigFile(s){let h=[];try{if(!hn(s))return h.push("Configuration file does not exist"),h;let m=await import(s),g=m.default||m;if(g===void 0)h.push("Configuration file must export a default value or named exports");else if(typeof g!=="object"||g===null)h.push("Configuration must be an object");else if(Array.isArray(g))h.push("Configuration cannot be an array at the root level");if(s.endsWith(".json"))try{let{readFileSync:R}=await import("fs"),I=R(s,"utf8");JSON.parse(I)}catch(R){h.push(`Invalid JSON syntax: ${R}`)}}catch(m){h.push(`Failed to load configuration file: ${m}`)}return h}async getFileModificationTime(s){try{let{statSync:h}=await import("fs");return h(s).mtime}catch{return null}}async preloadConfigurations(s,h={}){let m=new Map;return await Promise.allSettled(s.map(async(g)=>{try{let R=await this.loadFromPath(g,{},h);if(R)m.set(g,R.config)}catch(R){if(h.verbose)console.warn(`Failed to preload ${g}:`,R)}})),m}}class Ui{async validateConfiguration(s,h,m={}){let{stopOnFirstError:g=!1,validateRequired:R=!0,validateTypes:I=!0,customRules:S=[],trackPerformance:L=!0,verbose:T=!1}=m,A=async()=>{let O=[],_=[],D={stopOnFirstError:g,validateRequired:R,validateTypes:I,customRules:S,trackPerformance:L,verbose:T};try{if(typeof h==="string")return await this.validateWithSchemaFile(s,h,D);else if(Array.isArray(h))return this.validateWithRules(s,[...h,...S],D);else return this.validateWithJSONSchema(s,h,D)}catch(F){return O.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:O,warnings:_}}};if(L)return await Gt.track("validateConfiguration",A);return A()}async validateWithSchemaFile(s,h,m){try{if(!Ym(h))throw new Zt(h,[{path:"",message:"Schema file does not exist"}]);let g=await import(h),R=g.default||g;if(Array.isArray(R))return this.validateWithRules(s,R,m);else return this.validateWithJSONSchema(s,R,m)}catch(g){throw new Zt(h,[{path:"",message:`Failed to load schema: ${g}`}])}}validateWithJSONSchema(s,h,m){let g=[],R=[];return this.validateObjectAgainstSchema(s,h,"",g,R,m),{isValid:g.length===0,errors:g,warnings:R}}validateObjectAgainstSchema(s,h,m,g,R,I){if(I.validateTypes&&h.type){let S=Array.isArray(s)?"array":typeof s,L=Array.isArray(h.type)?h.type:[h.type];if(!L.includes(S)){if(g.push({path:m,message:`Expected type ${L.join(" or ")}, got ${S}`,expected:L.join(" or "),actual:S,rule:"type"}),I.stopOnFirstError)return}}if(h.enum&&!h.enum.includes(s)){if(g.push({path:m,message:`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:s,rule:"enum"}),I.stopOnFirstError)return}if(typeof s==="string"){if(h.minLength!==void 0&&s.length<h.minLength)g.push({path:m,message:`String length must be at least ${h.minLength}`,expected:`>= ${h.minLength}`,actual:s.length,rule:"minLength"});if(h.maxLength!==void 0&&s.length>h.maxLength)g.push({path:m,message:`String length must not exceed ${h.maxLength}`,expected:`<= ${h.maxLength}`,actual:s.length,rule:"maxLength"});if(h.pattern){if(!new RegExp(h.pattern).test(s))g.push({path:m,message:`String does not match pattern ${h.pattern}`,expected:h.pattern,actual:s,rule:"pattern"})}}if(typeof s==="number"){if(h.minimum!==void 0&&s<h.minimum)g.push({path:m,message:`Value must be at least ${h.minimum}`,expected:`>= ${h.minimum}`,actual:s,rule:"minimum"});if(h.maximum!==void 0&&s>h.maximum)g.push({path:m,message:`Value must not exceed ${h.maximum}`,expected:`<= ${h.maximum}`,actual:s,rule:"maximum"})}if(Array.isArray(s)&&h.items)for(let S=0;S<s.length;S++){let L=m?`${m}[${S}]`:`[${S}]`;if(this.validateObjectAgainstSchema(s[S],h.items,L,g,R,I),I.stopOnFirstError&&g.length>0)return}if(s&&typeof s==="object"&&!Array.isArray(s)){let S=s;if(I.validateRequired&&h.required){for(let L of h.required)if(!(L in S)){if(g.push({path:m?`${m}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),I.stopOnFirstError)return}}if(h.properties){for(let[L,T]of Object.entries(h.properties))if(L in S){let A=m?`${m}.${L}`:L;if(this.validateObjectAgainstSchema(S[L],T,A,g,R,I),I.stopOnFirstError&&g.length>0)return}}if(h.additionalProperties===!1){let L=new Set(Object.keys(h.properties||{}));for(let T of Object.keys(S))if(!L.has(T))R.push({path:m?`${m}.${T}`:T,message:`Additional property '${T}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(s,h,m){let g=[],R=[];for(let I of h)try{let S=this.getValueByPath(s,I.path),L=this.validateWithRule(S,I,I.path);if(g.push(...L),m.stopOnFirstError&&g.length>0)break}catch(S){g.push({path:I.path,message:`Rule validation failed: ${S}`,rule:"system"})}return{isValid:g.length===0,errors:g,warnings:R}}validateWithRule(s,h,m){let g=[];if(h.required&&(s===void 0||s===null))return g.push({path:m,message:h.message||`Property '${m}' is required`,expected:"required",rule:"required"}),g;if(s===void 0||s===null)return g;if(h.type){let R=Array.isArray(s)?"array":typeof s;if(R!==h.type)g.push({path:m,message:h.message||`Expected type ${h.type}, got ${R}`,expected:h.type,actual:R,rule:"type"})}if(h.min!==void 0){let R=Array.isArray(s)?s.length:typeof s==="string"?s.length:typeof s==="number"?s:0;if(R<h.min)g.push({path:m,message:h.message||`Value must be at least ${h.min}`,expected:`>= ${h.min}`,actual:R,rule:"min"})}if(h.max!==void 0){let R=Array.isArray(s)?s.length:typeof s==="string"?s.length:typeof s==="number"?s:0;if(R>h.max)g.push({path:m,message:h.message||`Value must not exceed ${h.max}`,expected:`<= ${h.max}`,actual:R,rule:"max"})}if(h.pattern&&typeof s==="string"){if(!h.pattern.test(s))g.push({path:m,message:h.message||`Value does not match pattern ${h.pattern}`,expected:h.pattern.toString(),actual:s,rule:"pattern"})}if(h.enum&&!h.enum.includes(s))g.push({path:m,message:h.message||`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:s,rule:"enum"});if(h.validator){let R=h.validator(s);if(R)g.push({path:m,message:h.message||R,rule:"custom"})}return g}getValueByPath(s,h){if(!h)return s;let m=h.split("."),g=s;for(let R of m)if(g&&typeof g==="object"&&R in g)g=g[R];else return;return g}generateRulesFromInterface(s){let h=[],m=s.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let g of m){let[,R,I,S]=g;h.push({path:R,required:!I,type:this.mapTypeScriptType(S)})}return h}mapTypeScriptType(s){switch(s.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Do},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class zi{fileLoader=new _n;envProcessor=new On;validator=new Ui;async loadConfig(s){let h=Date.now(),{cache:m,performance:g,schema:R,validate:I,...S}=s;try{if(m?.enabled){let T=this.checkCache(S.name||"",S);if(T)return T}let L;try{L=await this.loadConfigurationStrategies(S,!0,m)}catch(T){let A=S.__strictErrorHandling;if(T instanceof Error&&T.name==="ConfigNotFoundError"){if(A)throw T;L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:[`No configuration file found for "${S.name||"config"}", using defaults with environment variables`]}}else if(T instanceof Error&&T.name==="ConfigLoadError"){let O=T.message.includes("EACCES")||T.message.includes("EPERM")||T.message.includes("permission denied"),_=!O&&(T.message.includes("syntax")||T.message.includes("Expected")||T.message.includes("Unexpected")||T.message.includes("BuildMessage")||T.message.includes("errors building")),D=T.message.includes("Configuration must export a valid object")||T.message.includes("Configuration file is empty and exports nothing");if(A&&(D||O))throw T;if(_&&(!A||!D))L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!A)L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:[`Configuration loading error, using defaults: ${T.message}`]};else throw T}else L={...await this.applyEnvironmentVariables(S.name||"",S.defaultConfig,S.checkEnv!==!1,S.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${T instanceof Error?T.message:String(T)}`]}}if(R||I)await this.validateConfiguration(L.config,R,I,S.name);if(m?.enabled&&L)this.cacheResult(S.name||"",L,m,S);if(g?.enabled){let T={operation:"loadConfig",duration:Date.now()-h,configName:S.name,timestamp:new Date};if(g.onMetrics)g.onMetrics(T);if(g.slowThreshold&&T.duration>g.slowThreshold)nt.warn(`Slow configuration loading detected: ${T.duration}ms for ${S.name}`);L.metrics=T}return L}catch(L){let T=Date.now()-h;throw nt.error(`Configuration loading failed after ${T}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(s,h=!1,m){let{name:g="",alias:R,cwd:I,configDir:S,defaultConfig:L,checkEnv:T=!0,arrayStrategy:A="replace",verbose:O=!1}=s,_=I||xt.cwd(),D=[],F=await this.loadLocalConfiguration(g,R,_,S,L,A,O,T,m);if(F)return D.push(...this.getLocalSearchPaths(g,R,_,S)),this.finalizeResult(F,D,T,g,O);let N=await this.loadHomeConfiguration(g,R,L,A,O,T);if(N)return D.push(...this.getHomeSearchPaths(g,R)),this.finalizeResult(N,D,T,g,O);let W=await this.loadPackageJsonConfiguration(g,R,_,L,A,O,T);if(W)return D.push(Ye(_,"package.json")),this.finalizeResult(W,D,T,g,O);if(D.push(...this.getAllSearchPaths(g,R,_,S)),h)throw pt.configNotFound(g,D,R);return{...await this.applyEnvironmentVariables(g,L,T,O),warnings:[`No configuration file found for "${g}"${R?` or alias "${R}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(s,h,m,g,R,I,S,L,T){let A=L?Kt(s,R,S):R,O=this.getLocalDirectories(m,g);for(let _ of O){if(S)nt.info(`Searching for configuration in: ${_}`);let D=this.fileLoader.generateConfigPaths(s,_,h),F=await this.fileLoader.tryLoadFromPaths(D,A,{arrayStrategy:I,verbose:S,cacheTtl:T?.ttl,useCache:!T?.ttl||T.ttl>100});if(F){if(S)nt.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration(s,h,m,g,R,I){if(!s)return null;let S=I?Kt(s,m,R):m,L=[Ye(vt(),".config",s),Ye(vt(),".config"),vt()];for(let T of L){if(R)nt.info(`Checking home directory: ${T}`);let A=this.fileLoader.generateConfigPaths(s,T,h),O=await this.fileLoader.tryLoadFromPaths(A,S,{arrayStrategy:g,verbose:R});if(O){if(R)nt.success(`Configuration loaded from home directory: ${O.source.path}`);return O}}return null}async loadPackageJsonConfiguration(s,h,m,g,R,I,S){let L=S?Kt(s,g,I):g;try{let T=Ye(m,"package.json");if(!Ii(T))return null;let A=await import(T),O=A[s],_=s;if(!O&&h)O=A[h],_=h;if(O&&typeof O==="object"&&!Array.isArray(O)){if(I)nt.success(`Configuration loaded from package.json: ${_}`);return{config:ji(L,O,R),source:{type:"package.json",path:T,priority:30,timestamp:new Date}}}}catch(T){if(I)nt.warn("Failed to load package.json:",[T instanceof Error?T:Error(String(T))])}return null}async applyEnvironmentVariables(s,h,m,g){if(!m||!s||typeof h!=="object"||h===null||Array.isArray(h))return{config:h,source:{type:"default",priority:10,timestamp:new Date}};return{config:Kt(s,h,g),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(s,h,m,g,R){return{config:s.config,source:s.source,path:s.source.path}}async validateConfiguration(s,h,m,g){let R=[];if(m){let I=m(s);if(I)R.push(...I)}if(h){let I=await this.validator.validateConfiguration(s,h);if(!I.isValid)R.push(...I.errors.map((S)=>S.path?`${S.path}: ${S.message}`:S.message))}if(R.length>0)throw pt.configValidation(g||"unknown",R,g)}checkCache(s,h){let m=this.generateCacheKey(s,h);return _t.get(m)||null}cacheResult(s,h,m,g){let R=this.generateCacheKey(s,g);_t.set(R,h,void 0,m.ttl)}generateCacheKey(s,h){let m=[s];if(h.alias)m.push(`alias:${h.alias}`);if(h.cwd)m.push(`cwd:${h.cwd}`);if(h.configDir)m.push(`configDir:${h.configDir}`);if("checkEnv"in h)m.push(`checkEnv:${h.checkEnv}`);return m.join("|")}getLocalDirectories(s,h){return Array.from(new Set([s,Ye(s,"config"),Ye(s,".config"),h?Ye(s,h):void 0].filter(Boolean)))}getAllSearchPaths(s,h,m,g){let R=[];return R.push(...this.getLocalSearchPaths(s,h,m,g)),R.push(...this.getHomeSearchPaths(s,h)),R.push(Ye(m,"package.json")),R}getLocalSearchPaths(s,h,m,g){let R=this.getLocalDirectories(m,g),I=[];for(let S of R)I.push(...this.fileLoader.generateConfigPaths(s,S,h));return I}getHomeSearchPaths(s,h){if(!s)return[];let m=[Ye(vt(),".config",s),Ye(vt(),".config"),vt()],g=[];for(let R of m)g.push(...this.fileLoader.generateConfigPaths(s,R,h));return g}async loadConfigWithResult(s){return this.loadConfig(s)}}function Qr(s){let m=!(s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"))&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")),g=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");return m||g}async function Rh(s){return mt.loadConfig({...s,__strictErrorHandling:!0})}async function Eo(s){let h="defaultConfig"in s&&s.defaultConfig!==void 0?s.defaultConfig:{},m="cache"in s||"performance"in s||"schema"in s||"validate"in s;try{let g;if(m)g=await mt.loadConfig(s);else g=await mt.loadConfig({...s,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}});return g?.config??h}catch(g){let R=g instanceof Error?g.name:"UnknownError",I=g instanceof Error?g.message:String(g);if(!(R==="ConfigNotFoundError"||R==="ConfigLoadError"||R==="ConfigValidationError"||I.includes("config"))&&s.verbose)nt.warn("Unexpected error loading config, using defaults:",[g instanceof Error?g:Error(String(g))]);let L=m?{...s,defaultConfig:h}:{...s,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in s?s.checkEnv!==!1:!0)return(await mt.applyEnvironmentVariables(L.name||"",h,!0,L.verbose||!1))?.config??h;return h}}async function kh(s={defaultConfig:{}}){if(typeof s==="string"){let{cwd:h}=await import("process");try{return(await mt.loadConfig({name:s,cwd:h(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(m){if(m instanceof Error&&(m.name==="ConfigNotFoundError"||m.name==="ConfigLoadError"&&Qr(m)))return(await mt.applyEnvironmentVariables(s,{},!0,!1)).config;throw m}}try{return(await mt.loadConfig({...s,cwd:s.cwd||xt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(h){if(h instanceof Error&&(h.name==="ConfigNotFoundError"||h.name==="ConfigLoadError"&&Qr(h)))return(await mt.applyEnvironmentVariables(s.name||"",s.defaultConfig||{},s.checkEnv!==!1,s.verbose||!1)).config;throw h}}async function $h(s,h,m="replace"){let g=new _n;try{let R=await g.loadFromPath(s,h,{arrayStrategy:m,useCache:!1,trackPerformance:!1});return R?R.config:null}catch{return null}}function Kt(s,h,m=!1){let g=new On,R=s.toUpperCase().replace(/[^A-Z0-9]/g,"_");function I(S,L=[]){let T={...S};for(let[A,O]of Object.entries(S)){let _=[...L,A],D=[`${R}_${_.join("_").toUpperCase()}`,`${R}_${_.map((W)=>W.toUpperCase()).join("")}`,`${R}_${_.map((W)=>W.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,N;for(let W of D)if(F=xt.env[W],F!==void 0){N=W;break}if(F!==void 0&&N)if(typeof O==="boolean")T[A]=["true","1","yes"].includes(F.toLowerCase());else if(typeof O==="number"){let W=Number(F);if(!Number.isNaN(W))T[A]=W}else if(Array.isArray(O))try{T[A]=JSON.parse(F)}catch{T[A]=F.split(",").map((W)=>W.trim())}else T[A]=F;else if(O&&typeof O==="object"&&!Array.isArray(O))T[A]=I(O,_)}return T}return I(h)}function Ph(s){let h=Ye(xt.cwd(),s.configDir),m=Ye(xt.cwd(),s.generatedDir),g=Ye(m,"config-types.ts");if(!Ii(Fr(g)))Cm(Fr(g),{recursive:!0,mode:511});let R=Ii(h)?Sm(h).map((S)=>S.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],I=`// Generated by bunfig v${Qh}
|
|
32
32
|
export type ConfigNames = ${R.length?`'${R.join("' | '")}'`:"string"}
|
|
33
|
-
|
|
34
|
-
${R.map((A)=>{let O=
|
|
33
|
+
`;Em(g,I,{mode:438})}function vh(s){let h=null,m=null,g=()=>{if(!m)m=Eo(s).then((I)=>(h=I,I),(I)=>{let S="defaultConfig"in s?s.defaultConfig:{};if(h=S,"verbose"in s&&s.verbose)nt.warn("Config loading failed, using defaults:",[I instanceof Error?I:Error(String(I))]);return S});return m},R="defaultConfig"in s?s.defaultConfig:{};return h=R,g(),new Proxy({},{get(I,S){if(h)return h[S];let L=R[S];return g(),L},has(I,S){return S in(h||R)},ownKeys(){return Object.keys(h||R)},getOwnPropertyDescriptor(I,S){return Object.getOwnPropertyDescriptor(h||R,S)},set(I,S,L){if(!h)h={...R};return h[S]=L,!0}})}function Ih(s){let h=Xr(eh.cwd(),s?.configDir||"./config");function m(){if(!Xm(h))return[];let R=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),I=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],S=Qm(h).filter((T)=>R.has(yi(T))).map((T)=>({base:T.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:T})),L=new Map;for(let{base:T,file:A}of S){let O=yi(A).toLowerCase(),_=L.get(T);if(!_){L.set(T,A);continue}let D=yi(_).toLowerCase();if(I.indexOf(O)<I.indexOf(D))L.set(T,A)}return Array.from(L.entries()).map(([T,A])=>({base:T,file:A})).sort((T,A)=>T.base.localeCompare(A.base))}function g(){let R=m(),I=R.map((A)=>A.base),S=I.length?I.map((A)=>`'${A}'`).join(" | "):"string",L=R.length?`{
|
|
34
|
+
${R.map((A)=>{let O=Xr(h,A.file).replace(/\\/g,"/");return` '${A.base}': typeof import('${O}').default`}).join(`,
|
|
35
35
|
`)}
|
|
36
36
|
}`:"Record<string, any>";return`export type ConfigNames = ${S}
|
|
37
37
|
export type ConfigByName = ${L}
|
|
38
38
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
39
|
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(R){R.onResolve({filter:/^virtual:bunfig-types$/},(I)=>({path:I.path,namespace:"bunfig-virtual"})),R.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:g(),loader:"ts"}))}}}var Io,_t,Zt,Mo,wh,Rh,Gr,yn,Pi,He,Te,kh,Jr,$h,Yr,Ph,vh,hi,Ih,Xr,Qr,di,Mh,Ch,Sh,Eh,bn,Co,Lh,Ze,Th,Ah,eo,xn,vi,je,Ie,Oh,to,_h,no,Dh,Fh,pi,Nh,so,io,Wh,gi,Bh,jh,Uh,zh,qh,wn,So,Kh,Vh="0.15.6",Xe,Cn,Vt,Ii,Mi,Sn,Ci,Si,Ht,Ei,Li,pt,Eo,Lo,nt,mt,To,Ao,Hh=wm(async()=>{Io=import.meta.require,_t=new Ti,Zt=new Ai,Mo={createKey:Zm,isEquivalent:Gm,estimateMemoryUsage:Jm},wh=$n(ki.cwd(),"config"),Rh=$n(ki.cwd(),"src/generated"),Gr=kn.env.CLARITY_LOG_DIR||Im(Qm(),"logs"),yn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Pi=await eh(),He={red:(s)=>`\x1B[31m${s}\x1B[0m`,green:(s)=>`\x1B[32m${s}\x1B[0m`,yellow:(s)=>`\x1B[33m${s}\x1B[0m`,blue:(s)=>`\x1B[34m${s}\x1B[0m`,magenta:(s)=>`\x1B[35m${s}\x1B[0m`,cyan:(s)=>`\x1B[36m${s}\x1B[0m`,white:(s)=>`\x1B[37m${s}\x1B[0m`,gray:(s)=>`\x1B[90m${s}\x1B[0m`,bgRed:(s)=>`\x1B[41m${s}\x1B[0m`,bgYellow:(s)=>`\x1B[43m${s}\x1B[0m`,bold:(s)=>`\x1B[1m${s}\x1B[0m`,dim:(s)=>`\x1B[2m${s}\x1B[0m`,italic:(s)=>`\x1B[3m${s}\x1B[0m`,underline:(s)=>`\x1B[4m${s}\x1B[0m`,reset:"\x1B[0m"},Te=He,kh=He.red,Jr=He.green,$h=He.yellow,Yr=He.blue,Ph=He.magenta,vh=He.cyan,hi=He.white,Ih=He.gray,Xr=He.bgRed,Qr=He.bgYellow,di=He.bold,Mh=He.dim,Ch=He.italic,Sh=He.underline,Eh=He.reset,bn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Co={debug:"\uD83D\uDD0D",info:Yr("\u2139"),success:Jr("\u2713"),warning:Qr(hi(di(" WARN "))),error:Xr(hi(di(" ERROR ")))},Lh=new vn("stacks"),Ze=new vn("bunfig",{showTags:!0}),Th=Je(Kt.cwd(),"config"),Ah=Je(Kt.cwd(),"src/generated"),eo=Rn.env.CLARITY_LOG_DIR||Pm(ih(),"logs"),xn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vi=await rh(),je={red:(s)=>`\x1B[31m${s}\x1B[0m`,green:(s)=>`\x1B[32m${s}\x1B[0m`,yellow:(s)=>`\x1B[33m${s}\x1B[0m`,blue:(s)=>`\x1B[34m${s}\x1B[0m`,magenta:(s)=>`\x1B[35m${s}\x1B[0m`,cyan:(s)=>`\x1B[36m${s}\x1B[0m`,white:(s)=>`\x1B[37m${s}\x1B[0m`,gray:(s)=>`\x1B[90m${s}\x1B[0m`,bgRed:(s)=>`\x1B[41m${s}\x1B[0m`,bgYellow:(s)=>`\x1B[43m${s}\x1B[0m`,bgGray:(s)=>`\x1B[100m${s}\x1B[0m`,bold:(s)=>`\x1B[1m${s}\x1B[0m`,dim:(s)=>`\x1B[2m${s}\x1B[0m`,italic:(s)=>`\x1B[3m${s}\x1B[0m`,underline:(s)=>`\x1B[4m${s}\x1B[0m`,strikethrough:(s)=>`\x1B[9m${s}\x1B[0m`,reset:"\x1B[0m"},Ie=je,Oh=je.red,to=je.green,_h=je.yellow,no=je.blue,Dh=je.magenta,Fh=je.cyan,pi=je.white,Nh=je.gray,so=je.bgRed,io=je.bgYellow,Wh=je.bgGray,gi=je.bold,Bh=je.dim,jh=je.italic,Uh=je.underline,zh=je.strikethrough,qh=je.reset,wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},So={debug:"\uD83D\uDD0D",info:no("\u2139"),success:to("\u2713"),warning:io(pi(gi(" WARN "))),error:so(pi(gi(" ERROR ")))},Kh=new Mn("stacks"),Xe=class extends Error{timestamp;context;constructor(h,m={}){super(h);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=m,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let h=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([m,g])=>`${m}: ${g}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${h}`}},Cn=class extends Xe{code="CONFIG_NOT_FOUND";constructor(h,m,g){let R=g?` or alias "${g}"`:"";super(`Configuration "${h}"${R} not found`,{configName:h,alias:g,searchPaths:m,searchPathCount:m.length})}},Vt=class extends Xe{code="CONFIG_LOAD_ERROR";constructor(h,m,g){super(`Failed to load configuration from "${h}": ${m.message}`,{configPath:h,configName:g,originalError:m.name,originalMessage:m.message});this.cause=m}},Ii=class extends Xe{code="CONFIG_VALIDATION_ERROR";constructor(h,m,g){super(`Configuration validation failed for "${h}"`,{configPath:h,configName:g,validationErrors:m,errorCount:m.length})}},Mi=class extends Xe{code="CONFIG_MERGE_ERROR";constructor(h,m,g,R){super(`Failed to merge configuration from "${h}" with "${m}": ${g.message}`,{sourcePath:h,targetPath:m,configName:R,originalError:g.name,originalMessage:g.message});this.cause=g}},Sn=class extends Xe{code="ENV_VAR_ERROR";constructor(h,m,g,R){super(`Failed to parse environment variable "${h}" with value "${m}" as ${g}`,{envKey:h,envValue:m,expectedType:g,configName:R})}},Ci=class extends Xe{code="FILE_SYSTEM_ERROR";constructor(h,m,g){super(`File system ${h} failed for "${m}": ${g.message}`,{operation:h,path:m,originalError:g.name,originalMessage:g.message});this.cause=g}},Si=class extends Xe{code="TYPE_GENERATION_ERROR";constructor(h,m,g){super(`Failed to generate types from "${h}" to "${m}": ${g.message}`,{configDir:h,outputPath:m,originalError:g.name,originalMessage:g.message});this.cause=g}},Ht=class extends Xe{code="SCHEMA_VALIDATION_ERROR";constructor(h,m,g){super(`Schema validation failed${g?` for config "${g}"`:""}`,{schemaPath:h,configName:g,validationErrors:m,errorCount:m.length})}},Ei=class extends Xe{code="BROWSER_CONFIG_ERROR";constructor(h,m,g,R){super(`Failed to fetch configuration from "${h}": ${m} ${g}`,{endpoint:h,status:m,statusText:g,configName:R})}},Li=class extends Xe{code="PLUGIN_ERROR";constructor(h,m,g){super(`Plugin "${h}" failed during ${m}: ${g.message}`,{pluginName:h,operation:m,originalError:g.name,originalMessage:g.message});this.cause=g}},pt={configNotFound(s,h,m){return new Cn(s,h,m)},configLoad(s,h,m){return new Vt(s,h,m)},configValidation(s,h,m){return new Ii(s,h,m)},configMerge(s,h,m,g){return new Mi(s,h,m,g)},envVar(s,h,m,g){return new Sn(s,h,m,g)},fileSystem(s,h,m){return new Ci(s,h,m)},typeGeneration(s,h,m){return new Si(s,h,m)},schemaValidation(s,h,m){return new Ht(s,h,m)},browserConfig(s,h,m,g){return new Ei(s,h,m,g)},plugin(s,h,m){return new Li(s,h,m)}},Eo={replace:"replace",concat:"concat",smart:"smart"},Lo=/^https?:\/\//,nt=new Mn("bunfig",{showTags:!0}),mt=new Ni,To=Ye(xt.cwd(),"config"),Ao=Ye(xt.cwd(),"src/generated")});function Jh(s,h={}){let m=En.cwd();while(m.includes("storage"))m=ro(m,"..");let g=ro(m,s||"");if(h?.relative)return Gh(En.cwd(),g);return g}var Yh=En.env.CLARITY_LOG_DIR||Zh(Jh(),"logs"),Oo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ln={...Oo},ky=(async()=>{try{let{loadConfig:s}=await Hh().then(()=>po),h=await s({name:"clarity",alias:"logging",defaultConfig:Oo,cwd:En.cwd()});if(h)Object.assign(Ln,h)}catch{}return Ln})();function Ue(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ld(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let s=ft.type;if(s==="renderer"||s==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class _o{async format(s){let h=await ld(),m=await this.getMetadata(h);return JSON.stringify({timestamp:s.timestamp.toISOString(),level:s.level,name:s.name,message:s.message,metadata:m})}async getMetadata(s){if(s){let{hostname:h}=await import("os");return{pid:Ot.pid,hostname:h(),environment:Ot.env.NODE_ENV||"development",platform:Ot.platform,version:Ot.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ot.env.NODE_ENV||Ot.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var qe={red:(s)=>`\x1B[31m${s}\x1B[0m`,green:(s)=>`\x1B[32m${s}\x1B[0m`,yellow:(s)=>`\x1B[33m${s}\x1B[0m`,blue:(s)=>`\x1B[34m${s}\x1B[0m`,magenta:(s)=>`\x1B[35m${s}\x1B[0m`,cyan:(s)=>`\x1B[36m${s}\x1B[0m`,white:(s)=>`\x1B[37m${s}\x1B[0m`,gray:(s)=>`\x1B[90m${s}\x1B[0m`,bgRed:(s)=>`\x1B[41m${s}\x1B[0m`,bgYellow:(s)=>`\x1B[43m${s}\x1B[0m`,bgGray:(s)=>`\x1B[100m${s}\x1B[0m`,bold:(s)=>`\x1B[1m${s}\x1B[0m`,dim:(s)=>`\x1B[2m${s}\x1B[0m`,italic:(s)=>`\x1B[3m${s}\x1B[0m`,underline:(s)=>`\x1B[4m${s}\x1B[0m`,strikethrough:(s)=>`\x1B[9m${s}\x1B[0m`,reset:"\x1B[0m"},Ce=qe,{red:Ay,green:ad,yellow:Oy,blue:cd,magenta:_y,cyan:Dy,white:mo,gray:Fy,bgRed:ud,bgYellow:fd,bgGray:Ny,bold:ho,dim:Wy,italic:By,underline:jy,strikethrough:Uy,reset:zy}=qe,wi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},md={debug:"\uD83D\uDD0D",info:cd("\u2139"),success:ad("\u2713"),warning:fd(mo(ho(" WARN "))),error:ud(mo(ho(" ERROR ")))};class wt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(s,h={}){this.name=s,this.config={...Ln},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new _o,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??Ee.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let m={...h},g=h.timestamp!==void 0;if(g)delete m.timestamp;if(this.config={...this.config,...m,timestamp:g||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let R=this.generateKeyId(),I=this.generateKey();this.currentKeyId=R,this.keys.set(R,I),this.encryptionKeys.set(R,{key:I,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(s){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},m=this.fingersCrossedConfig.activationLevel??"error";return h[s]>=h[m]}initializeFingersCrossedConfig(s){if(!s.fingersCrossedEnabled&&s.fingersCrossed)return{...wi,...s.fingersCrossed};if(!s.fingersCrossedEnabled)return null;if(!s.fingersCrossed)return{...wi};return{...wi,...s.fingersCrossed}}normalizeOptions(s){let h={format:"json",level:"info",logDirectory:Ln.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},m={...h,...Object.fromEntries(Object.entries(s).filter(([,g])=>g!==void 0))};if(!m.level||!["debug","info","success","warning","error"].includes(m.level))m.level=h.level;return m}shouldWriteToFile(){return!Ue()&&this.config.writeToFile===!0}async writeToFile(s){let m=(async()=>{let R,I=0,S=3,L=1000;while(I<S)try{try{try{await nd(this.config.logDirectory,co.F_OK|co.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await sd(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let T=this.validateEncryptionConfig()?(await this.encrypt(s)).encrypted:at.from(s);try{if(!hn(this.currentLogFile))await xi(this.currentLogFile,"",{mode:420});if(R=ao(this.currentLogFile,"a",420),td(R,T,{flag:"a"}),lo(R),R!==void 0)bi(R),R=void 0;if((await Tt(this.currentLogFile)).size===0){if(await xi(this.currentLogFile,T,{flag:"w",mode:420}),(await Tt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let O=A;if(O.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(O.code)){if(I<S-1){let _=typeof O.message==="string"?O.message:"Unknown error";console.error(`Network error during write attempt ${I+1}/${S}:`,_);let D=L*2**I;await new Promise((F)=>setTimeout(F,D)),I++;continue}}if(O?.code&&["ENOSPC","EDQUOT"].includes(O.code))throw Error(`Disk quota exceeded or no space left on device: ${O.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",O),O}finally{if(R!==void 0)try{bi(R)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(T){if(I===S-1){let O=T,_=typeof O.message==="string"?O.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),T}I++;let A=L*2**(I-1);await new Promise((O)=>setTimeout(O,A))}})();this.pendingOperations.push(m);let g=this.pendingOperations.length-1;try{await m}catch(R){throw console.error("Debug: [writeToFile] Error in operation:",R),R}finally{this.pendingOperations.splice(g,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return At(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return At(this.config.logDirectory,`${this.name}.log`);let s=new Date().toISOString().split("T")[0];return At(this.config.logDirectory,`${this.name}-${s}.log`)}setupRotation(){if(Ue())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let s=this.config.rotation,h;switch(s.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let m=typeof h.interval==="number"?h.interval:60,g=Math.max(m,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((R)=>{console.error("Error rotating keys:",R)})},g)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,m=this.generateKeyId(),g=this.generateKey();this.currentKeyId=m,this.keys.set(m,g),this.encryptionKeys.set(m,{key:g,createdAt:new Date});let R=Array.from(this.encryptionKeys.entries()).sort(([,L],[,T])=>T.createdAt.getTime()-L.createdAt.getTime()),I=typeof h.maxKeys==="number"?h.maxKeys:1,S=Math.max(1,I);if(R.length>S)for(let[L]of R.slice(S))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return yi(16).toString("hex")}generateKey(){return yi(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let s=this.keys.get(this.currentKeyId);if(!s)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:s,id:this.currentKeyId}}encrypt(s){let{key:h}=this.getCurrentKey(),m=yi(16),g=Xh("aes-256-gcm",h,m),R=at.isBuffer(s)?s:at.from(s,"utf8"),I=g.update(R),S=g.final(),L=I.length+S.length,T=g.getAuthTag(),A=at.allocUnsafe(16+L+16);return m.copy(A,0),I.copy(A,16),S.copy(A,16+I.length),T.copy(A,16+L),{encrypted:A,iv:m}}async compressData(s){return new Promise((h,m)=>{let g=fo(),R=[];g.on("data",(I)=>R.push(I)),g.on("end",()=>h(at.from(at.concat(R)))),g.on("error",m),g.write(s),g.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let s={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let h=this.config.rotation.encrypt;return{...s,...h}}return s}async rotateLog(){if(Ue())return;if(!this.shouldWriteToFile())return;let s=await Tt(this.currentLogFile).catch(()=>null);if(!s)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&s.size>=h.maxSize){let m=this.currentLogFile,g=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let R=await dn(this.config.logDirectory),I=R.filter((T)=>T.startsWith(this.name)&&/\.log\.\d+$/.test(T)).sort((T,A)=>{let O=Number.parseInt(T.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-O}),S=I.length>0?Number.parseInt(I[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${m}.${S}`;if(await Tt(m).catch(()=>null))try{if(await uo(m,L),h.compress)try{let T=`${L}.gz`;await this.compressLogFile(L,T),await pn(L)}catch(T){console.error("Error compressing rotated file:",T)}if(I.length===0&&!R.some((T)=>T.endsWith(".log.1")))try{let T=`${m}.1`;await xi(T,"")}catch(T){console.error("Error creating backup file:",T)}}catch(T){console.error(`Error during rotation: ${T instanceof Error?T.message:String(T)}`)}}else{let R=new Date().toISOString().replace(/[:.]/g,"-"),I=m.replace(/\.log$/,`-${R}.log`);if(await Tt(m).catch(()=>null))await uo(m,I)}if(this.currentLogFile=g,h.maxFiles){let I=(await dn(this.config.logDirectory)).filter((S)=>S.startsWith(this.name)).sort((S,L)=>L.localeCompare(S));for(let S of I.slice(h.maxFiles))await pn(At(this.config.logDirectory,S))}}}async compressLogFile(s,h){let m=oo(s),g=ed(h),R=fo();await od(m,R,g)}async handleFingersCrossedBuffer(s,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(s)&&!this.isActivated){this.isActivated=!0;for(let m of this.logBuffer){let g=await this.formatter.format(m);if(this.shouldWriteToFile())await this.writeToFile(g);console.log(g)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog(s){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[s]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((s)=>{if(s instanceof Promise)return s.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),hn(this.currentLogFile))try{let s=ao(this.currentLogFile,"r+");lo(s),bi(s)}catch(s){console.error(`Error flushing file: ${s}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let s of this.pendingOperations)if(typeof s.cancel==="function")s.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(s){console.error("Error waiting for pending operations:",s)}if(!Ue()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await dn(this.config.logDirectory)).filter((m)=>(m.includes("temp")||m.includes(".tmp"))&&m.includes(this.name));for(let m of h)try{await pn(At(this.config.logDirectory,m))}catch(g){console.error(`Failed to delete temp file ${m}:`,g)}}catch(s){console.error("Error cleaning up temporary files:",s)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(s){if(!s)return"";return`${this.tagFormat.prefix}${s}${this.tagFormat.suffix}`}formatFileTimestamp(s){return`[${s.toISOString()}]`}formatConsoleTimestamp(s){return this.shouldStyleConsole()?Ce.gray(s.toLocaleTimeString()):s.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ue())return!1;let s=typeof Ee.env.NO_COLOR<"u",h=Ee.env.FORCE_COLOR==="0";if(s||h)return!1;return!!(typeof Ee.stderr<"u"&&Ee.stderr.isTTY||typeof Ee.stdout<"u"&&Ee.stdout.isTTY)}formatConsoleMessage(s){let{timestamp:h,icon:m="",tag:g="",message:R,level:I,showTimestamp:S=!0}=s,L=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(S)F.push(h);if(I==="warning")F.push("WARN");else if(I==="error")F.push("ERROR");else if(m)F.push(m.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(g)F.push(g.replace(/[[\]]/g,""));return F.push(R),F.join(" ")}let T=Ee.stdout.columns||120,A="";if(I==="warning"||I==="error")A=`${m} ${R}`;else if(I==="info"||I==="success")A=`${m} ${g} ${R}`;else A=`${m} ${g} ${Ce.cyan(R)}`;if(!S)return A.trim();let O=L(A).trim().length,_=L(h).length,D=Math.max(1,T-2-O-_);return`${A.trim()}${" ".repeat(D)}${h}`}formatMessage(s,h){if(h.length===1&&Array.isArray(h[0]))return s.replace(/\{(\d+)\}/g,(I,S)=>{let L=Number.parseInt(S,10);return L<h[0].length?String(h[0][L]):I});let m=/%([sdijfo%])/g,g=0,R=s.replace(m,(I,S)=>{if(S==="%")return"%";if(g>=h.length)return I;let L=h[g++];switch(S){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return I}});if(g<h.length)R+=` ${h.slice(g).map((I)=>typeof I==="object"?JSON.stringify(I,null,2):String(I)).join(" ")}`;return R}formatMarkdown(s){if(!s)return s;let h=s;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(m,g,R)=>{let I=Ce.underline(Ce.blue(g)),S=this.toAbsoluteFilePath(R);if(S&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(S)}`,T="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${L}\x1B\\${I}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${R}\x1B\\${I}\x1B]8;;\x1B\\`;return I}),h=h.replace(/`([^`]+)`/g,(m,g)=>Ce.bgGray(g)),h=h.replace(/\*\*([^*]+)\*\*/g,(m,g)=>Ce.bold(g)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(m,g)=>Ce.italic(g)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(m,g)=>Ce.italic(g)),h=h.replace(/~([^~]+)~/g,(m,g)=>Ce.strikethrough(g)),h}supportsHyperlinks(){if(Ue())return!1;let s=Ee.env;if(!s)return!1;if(s.TERM_PROGRAM==="iTerm.app"||s.TERM_PROGRAM==="vscode"||s.TERM_PROGRAM==="WezTerm")return!0;if(s.WT_SESSION)return!0;if(s.TERM==="xterm-kitty")return!0;let h=s.VTE_VERSION?Number.parseInt(s.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath(s){try{let h=s;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let m=Ee.env.HOME||"";if(m)h=h.replace(/^~(?=$|\/)/,m)}if(id(h)||h.startsWith("./")||h.startsWith("../"))h=rd(h);else return null;return hn(h)?h:null}catch{return null}}buildOutputTexts(s){let h=this.shouldStyleConsole()?this.formatMarkdown(s):s,m=s.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:m}}async log(s,h,...m){if(!this.shouldLog(s))return;let g=new Date,R=this.formatConsoleTimestamp(g),I=this.formatFileTimestamp(g),S,L;if(h instanceof Error)S=h.message,L=h.stack;else S=this.formatMessage(h,m);let{consoleText:T,fileText:A}=this.buildOutputTexts(S);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":md[s],D=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",F;switch(s){case"debug":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ce.gray(T),level:s}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ce.green(T),level:s}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.error(F),L){let N=L.split(`
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(R){R.onResolve({filter:/^virtual:bunfig-types$/},(I)=>({path:I.path,namespace:"bunfig-virtual"})),R.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:g(),loader:"ts"}))}}}var Lo,_t,Gt,To,Mh,Ch,eo,xn,Si,He,Te,Sh,to,Eh,no,Lh,Th,bi,Ah,so,io,xi,Oh,_h,Dh,Fh,wn,Ao,Nh,Ze,Wh,Bh,ro,Rn,Ei,je,Ie,jh,oo,Uh,lo,zh,qh,wi,Kh,ao,co,Vh,Ri,Hh,Zh,Gh,Jh,Yh,kn,Oo,Xh,Qh="0.15.6",Xe,En,Ht,Li,Ti,Ln,Ai,Oi,Zt,_i,Di,pt,_o,Do,nt,mt,Fo,No,ed=Mm(async()=>{Lo=import.meta.require,_t=new Fi,Gt=new Ni,To={createKey:th,isEquivalent:nh,estimateMemoryUsage:sh},Mh=vn(Mi.cwd(),"config"),Ch=vn(Mi.cwd(),"src/generated"),eo=Pn.env.CLARITY_LOG_DIR||Am(oh(),"logs"),xn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Si=await lh(),He={red:(s)=>`\x1B[31m${s}\x1B[0m`,green:(s)=>`\x1B[32m${s}\x1B[0m`,yellow:(s)=>`\x1B[33m${s}\x1B[0m`,blue:(s)=>`\x1B[34m${s}\x1B[0m`,magenta:(s)=>`\x1B[35m${s}\x1B[0m`,cyan:(s)=>`\x1B[36m${s}\x1B[0m`,white:(s)=>`\x1B[37m${s}\x1B[0m`,gray:(s)=>`\x1B[90m${s}\x1B[0m`,bgRed:(s)=>`\x1B[41m${s}\x1B[0m`,bgYellow:(s)=>`\x1B[43m${s}\x1B[0m`,bold:(s)=>`\x1B[1m${s}\x1B[0m`,dim:(s)=>`\x1B[2m${s}\x1B[0m`,italic:(s)=>`\x1B[3m${s}\x1B[0m`,underline:(s)=>`\x1B[4m${s}\x1B[0m`,reset:"\x1B[0m"},Te=He,Sh=He.red,to=He.green,Eh=He.yellow,no=He.blue,Lh=He.magenta,Th=He.cyan,bi=He.white,Ah=He.gray,so=He.bgRed,io=He.bgYellow,xi=He.bold,Oh=He.dim,_h=He.italic,Dh=He.underline,Fh=He.reset,wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ao={debug:"\uD83D\uDD0D",info:no("\u2139"),success:to("\u2713"),warning:io(bi(xi(" WARN "))),error:so(bi(xi(" ERROR ")))},Nh=new Mn("stacks"),Ze=new Mn("bunfig",{showTags:!0}),Wh=Je(Vt.cwd(),"config"),Bh=Je(Vt.cwd(),"src/generated"),ro=$n.env.CLARITY_LOG_DIR||Lm(fh(),"logs"),Rn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ro,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ei=await mh(),je={red:(s)=>`\x1B[31m${s}\x1B[0m`,green:(s)=>`\x1B[32m${s}\x1B[0m`,yellow:(s)=>`\x1B[33m${s}\x1B[0m`,blue:(s)=>`\x1B[34m${s}\x1B[0m`,magenta:(s)=>`\x1B[35m${s}\x1B[0m`,cyan:(s)=>`\x1B[36m${s}\x1B[0m`,white:(s)=>`\x1B[37m${s}\x1B[0m`,gray:(s)=>`\x1B[90m${s}\x1B[0m`,bgRed:(s)=>`\x1B[41m${s}\x1B[0m`,bgYellow:(s)=>`\x1B[43m${s}\x1B[0m`,bgGray:(s)=>`\x1B[100m${s}\x1B[0m`,bold:(s)=>`\x1B[1m${s}\x1B[0m`,dim:(s)=>`\x1B[2m${s}\x1B[0m`,italic:(s)=>`\x1B[3m${s}\x1B[0m`,underline:(s)=>`\x1B[4m${s}\x1B[0m`,strikethrough:(s)=>`\x1B[9m${s}\x1B[0m`,reset:"\x1B[0m"},Ie=je,jh=je.red,oo=je.green,Uh=je.yellow,lo=je.blue,zh=je.magenta,qh=je.cyan,wi=je.white,Kh=je.gray,ao=je.bgRed,co=je.bgYellow,Vh=je.bgGray,Ri=je.bold,Hh=je.dim,Zh=je.italic,Gh=je.underline,Jh=je.strikethrough,Yh=je.reset,kn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Oo={debug:"\uD83D\uDD0D",info:lo("\u2139"),success:oo("\u2713"),warning:co(wi(Ri(" WARN "))),error:ao(wi(Ri(" ERROR ")))},Xh=new Sn("stacks"),Xe=class extends Error{timestamp;context;constructor(h,m={}){super(h);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=m,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let h=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([m,g])=>`${m}: ${g}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${h}`}},En=class extends Xe{code="CONFIG_NOT_FOUND";constructor(h,m,g){let R=g?` or alias "${g}"`:"";super(`Configuration "${h}"${R} not found`,{configName:h,alias:g,searchPaths:m,searchPathCount:m.length})}},Ht=class extends Xe{code="CONFIG_LOAD_ERROR";constructor(h,m,g){super(`Failed to load configuration from "${h}": ${m.message}`,{configPath:h,configName:g,originalError:m.name,originalMessage:m.message});this.cause=m}},Li=class extends Xe{code="CONFIG_VALIDATION_ERROR";constructor(h,m,g){super(`Configuration validation failed for "${h}"`,{configPath:h,configName:g,validationErrors:m,errorCount:m.length})}},Ti=class extends Xe{code="CONFIG_MERGE_ERROR";constructor(h,m,g,R){super(`Failed to merge configuration from "${h}" with "${m}": ${g.message}`,{sourcePath:h,targetPath:m,configName:R,originalError:g.name,originalMessage:g.message});this.cause=g}},Ln=class extends Xe{code="ENV_VAR_ERROR";constructor(h,m,g,R){super(`Failed to parse environment variable "${h}" with value "${m}" as ${g}`,{envKey:h,envValue:m,expectedType:g,configName:R})}},Ai=class extends Xe{code="FILE_SYSTEM_ERROR";constructor(h,m,g){super(`File system ${h} failed for "${m}": ${g.message}`,{operation:h,path:m,originalError:g.name,originalMessage:g.message});this.cause=g}},Oi=class extends Xe{code="TYPE_GENERATION_ERROR";constructor(h,m,g){super(`Failed to generate types from "${h}" to "${m}": ${g.message}`,{configDir:h,outputPath:m,originalError:g.name,originalMessage:g.message});this.cause=g}},Zt=class extends Xe{code="SCHEMA_VALIDATION_ERROR";constructor(h,m,g){super(`Schema validation failed${g?` for config "${g}"`:""}`,{schemaPath:h,configName:g,validationErrors:m,errorCount:m.length})}},_i=class extends Xe{code="BROWSER_CONFIG_ERROR";constructor(h,m,g,R){super(`Failed to fetch configuration from "${h}": ${m} ${g}`,{endpoint:h,status:m,statusText:g,configName:R})}},Di=class extends Xe{code="PLUGIN_ERROR";constructor(h,m,g){super(`Plugin "${h}" failed during ${m}: ${g.message}`,{pluginName:h,operation:m,originalError:g.name,originalMessage:g.message});this.cause=g}},pt={configNotFound(s,h,m){return new En(s,h,m)},configLoad(s,h,m){return new Ht(s,h,m)},configValidation(s,h,m){return new Li(s,h,m)},configMerge(s,h,m,g){return new Ti(s,h,m,g)},envVar(s,h,m,g){return new Ln(s,h,m,g)},fileSystem(s,h,m){return new Ai(s,h,m)},typeGeneration(s,h,m){return new Oi(s,h,m)},schemaValidation(s,h,m){return new Zt(s,h,m)},browserConfig(s,h,m,g){return new _i(s,h,m,g)},plugin(s,h,m){return new Di(s,h,m)}},_o={replace:"replace",concat:"concat",smart:"smart"},Do=/^https?:\/\//,nt=new Sn("bunfig",{showTags:!0}),mt=new zi,Fo=Ye(xt.cwd(),"config"),No=Ye(xt.cwd(),"src/generated")});function sd(s,h={}){let m=Tn.cwd();while(m.includes("storage"))m=uo(m,"..");let g=uo(m,s||"");if(h?.relative)return nd(Tn.cwd(),g);return g}var id=Tn.env.CLARITY_LOG_DIR||td(sd(),"logs"),Wo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:id,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},An={...Wo},Cy=(async()=>{try{let{loadConfig:s}=await ed().then(()=>wo),h=await s({name:"clarity",alias:"logging",defaultConfig:Wo,cwd:Tn.cwd()});if(h)Object.assign(An,h)}catch{}return An})();function Ue(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function dd(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let s=ft.type;if(s==="renderer"||s==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class Bo{async format(s){let h=await dd(),m=await this.getMetadata(h);return JSON.stringify({timestamp:s.timestamp.toISOString(),level:s.level,name:s.name,message:s.message,metadata:m})}async getMetadata(s){if(s){let{hostname:h}=await import("os");return{pid:Ot.pid,hostname:h(),environment:Ot.env.NODE_ENV||"development",platform:Ot.platform,version:Ot.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ot.env.NODE_ENV||Ot.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var qe={red:(s)=>`\x1B[31m${s}\x1B[0m`,green:(s)=>`\x1B[32m${s}\x1B[0m`,yellow:(s)=>`\x1B[33m${s}\x1B[0m`,blue:(s)=>`\x1B[34m${s}\x1B[0m`,magenta:(s)=>`\x1B[35m${s}\x1B[0m`,cyan:(s)=>`\x1B[36m${s}\x1B[0m`,white:(s)=>`\x1B[37m${s}\x1B[0m`,gray:(s)=>`\x1B[90m${s}\x1B[0m`,bgRed:(s)=>`\x1B[41m${s}\x1B[0m`,bgYellow:(s)=>`\x1B[43m${s}\x1B[0m`,bgGray:(s)=>`\x1B[100m${s}\x1B[0m`,bold:(s)=>`\x1B[1m${s}\x1B[0m`,dim:(s)=>`\x1B[2m${s}\x1B[0m`,italic:(s)=>`\x1B[3m${s}\x1B[0m`,underline:(s)=>`\x1B[4m${s}\x1B[0m`,strikethrough:(s)=>`\x1B[9m${s}\x1B[0m`,reset:"\x1B[0m"},Ce=qe,{red:Wy,green:pd,yellow:By,blue:gd,magenta:jy,cyan:Uy,white:bo,gray:zy,bgRed:yd,bgYellow:bd,bgGray:qy,bold:xo,dim:Ky,italic:Vy,underline:Hy,strikethrough:Zy,reset:Gy}=qe,vi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xd={debug:"\uD83D\uDD0D",info:gd("\u2139"),success:pd("\u2713"),warning:bd(bo(xo(" WARN "))),error:yd(bo(xo(" ERROR ")))};class wt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(s,h={}){this.name=s,this.config={...An},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new Bo,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??Ee.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let m={...h},g=h.timestamp!==void 0;if(g)delete m.timestamp;if(this.config={...this.config,...m,timestamp:g||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let R=this.generateKeyId(),I=this.generateKey();this.currentKeyId=R,this.keys.set(R,I),this.encryptionKeys.set(R,{key:I,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(s){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},m=this.fingersCrossedConfig.activationLevel??"error";return h[s]>=h[m]}initializeFingersCrossedConfig(s){if(!s.fingersCrossedEnabled&&s.fingersCrossed)return{...vi,...s.fingersCrossed};if(!s.fingersCrossedEnabled)return null;if(!s.fingersCrossed)return{...vi};return{...vi,...s.fingersCrossed}}normalizeOptions(s){let h={format:"json",level:"info",logDirectory:An.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},m={...h,...Object.fromEntries(Object.entries(s).filter(([,g])=>g!==void 0))};if(!m.level||!["debug","info","success","warning","error"].includes(m.level))m.level=h.level;return m}shouldWriteToFile(){return!Ue()&&this.config.writeToFile===!0}async writeToFile(s){let m=(async()=>{let R,I=0,S=3,L=1000;while(I<S)try{try{try{await cd(this.config.logDirectory,po.F_OK|po.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await ud(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let T=this.validateEncryptionConfig()?(await this.encrypt(s)).encrypted:at.from(s);try{if(!pn(this.currentLogFile))await Pi(this.currentLogFile,"",{mode:420});if(R=ho(this.currentLogFile,"a",420),ad(R,T,{flag:"a"}),mo(R),R!==void 0)$i(R),R=void 0;if((await Tt(this.currentLogFile)).size===0){if(await Pi(this.currentLogFile,T,{flag:"w",mode:420}),(await Tt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let O=A;if(O.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(O.code)){if(I<S-1){let _=typeof O.message==="string"?O.message:"Unknown error";console.error(`Network error during write attempt ${I+1}/${S}:`,_);let D=L*2**I;await new Promise((F)=>setTimeout(F,D)),I++;continue}}if(O?.code&&["ENOSPC","EDQUOT"].includes(O.code))throw Error(`Disk quota exceeded or no space left on device: ${O.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",O),O}finally{if(R!==void 0)try{$i(R)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(T){if(I===S-1){let O=T,_=typeof O.message==="string"?O.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),T}I++;let A=L*2**(I-1);await new Promise((O)=>setTimeout(O,A))}})();this.pendingOperations.push(m);let g=this.pendingOperations.length-1;try{await m}catch(R){throw console.error("Debug: [writeToFile] Error in operation:",R),R}finally{this.pendingOperations.splice(g,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return At(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return At(this.config.logDirectory,`${this.name}.log`);let s=new Date().toISOString().split("T")[0];return At(this.config.logDirectory,`${this.name}-${s}.log`)}setupRotation(){if(Ue())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let s=this.config.rotation,h;switch(s.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let m=typeof h.interval==="number"?h.interval:60,g=Math.max(m,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((R)=>{console.error("Error rotating keys:",R)})},g)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,m=this.generateKeyId(),g=this.generateKey();this.currentKeyId=m,this.keys.set(m,g),this.encryptionKeys.set(m,{key:g,createdAt:new Date});let R=Array.from(this.encryptionKeys.entries()).sort(([,L],[,T])=>T.createdAt.getTime()-L.createdAt.getTime()),I=typeof h.maxKeys==="number"?h.maxKeys:1,S=Math.max(1,I);if(R.length>S)for(let[L]of R.slice(S))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return ki(16).toString("hex")}generateKey(){return ki(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let s=this.keys.get(this.currentKeyId);if(!s)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:s,id:this.currentKeyId}}encrypt(s){let{key:h}=this.getCurrentKey(),m=ki(16),g=rd("aes-256-gcm",h,m),R=at.isBuffer(s)?s:at.from(s,"utf8"),I=g.update(R),S=g.final(),L=I.length+S.length,T=g.getAuthTag(),A=at.allocUnsafe(16+L+16);return m.copy(A,0),I.copy(A,16),S.copy(A,16+I.length),T.copy(A,16+L),{encrypted:A,iv:m}}async compressData(s){return new Promise((h,m)=>{let g=yo(),R=[];g.on("data",(I)=>R.push(I)),g.on("end",()=>h(at.from(at.concat(R)))),g.on("error",m),g.write(s),g.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let s={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let h=this.config.rotation.encrypt;return{...s,...h}}return s}async rotateLog(){if(Ue())return;if(!this.shouldWriteToFile())return;let s=await Tt(this.currentLogFile).catch(()=>null);if(!s)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&s.size>=h.maxSize){let m=this.currentLogFile,g=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let R=await gn(this.config.logDirectory),I=R.filter((T)=>T.startsWith(this.name)&&/\.log\.\d+$/.test(T)).sort((T,A)=>{let O=Number.parseInt(T.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-O}),S=I.length>0?Number.parseInt(I[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${m}.${S}`;if(await Tt(m).catch(()=>null))try{if(await go(m,L),h.compress)try{let T=`${L}.gz`;await this.compressLogFile(L,T),await yn(L)}catch(T){console.error("Error compressing rotated file:",T)}if(I.length===0&&!R.some((T)=>T.endsWith(".log.1")))try{let T=`${m}.1`;await Pi(T,"")}catch(T){console.error("Error creating backup file:",T)}}catch(T){console.error(`Error during rotation: ${T instanceof Error?T.message:String(T)}`)}}else{let R=new Date().toISOString().replace(/[:.]/g,"-"),I=m.replace(/\.log$/,`-${R}.log`);if(await Tt(m).catch(()=>null))await go(m,I)}if(this.currentLogFile=g,h.maxFiles){let I=(await gn(this.config.logDirectory)).filter((S)=>S.startsWith(this.name)).sort((S,L)=>L.localeCompare(S));for(let S of I.slice(h.maxFiles))await yn(At(this.config.logDirectory,S))}}}async compressLogFile(s,h){let m=fo(s),g=ld(h),R=yo();await hd(m,R,g)}async handleFingersCrossedBuffer(s,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(s)&&!this.isActivated){this.isActivated=!0;for(let m of this.logBuffer){let g=await this.formatter.format(m);if(this.shouldWriteToFile())await this.writeToFile(g);console.log(g)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog(s){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[s]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((s)=>{if(s instanceof Promise)return s.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),pn(this.currentLogFile))try{let s=ho(this.currentLogFile,"r+");mo(s),$i(s)}catch(s){console.error(`Error flushing file: ${s}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let s of this.pendingOperations)if(typeof s.cancel==="function")s.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(s){console.error("Error waiting for pending operations:",s)}if(!Ue()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await gn(this.config.logDirectory)).filter((m)=>(m.includes("temp")||m.includes(".tmp"))&&m.includes(this.name));for(let m of h)try{await yn(At(this.config.logDirectory,m))}catch(g){console.error(`Failed to delete temp file ${m}:`,g)}}catch(s){console.error("Error cleaning up temporary files:",s)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(s){if(!s)return"";return`${this.tagFormat.prefix}${s}${this.tagFormat.suffix}`}formatFileTimestamp(s){return`[${s.toISOString()}]`}formatConsoleTimestamp(s){return this.shouldStyleConsole()?Ce.gray(s.toLocaleTimeString()):s.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ue())return!1;let s=typeof Ee.env.NO_COLOR<"u",h=Ee.env.FORCE_COLOR==="0";if(s||h)return!1;return!!(typeof Ee.stderr<"u"&&Ee.stderr.isTTY||typeof Ee.stdout<"u"&&Ee.stdout.isTTY)}formatConsoleMessage(s){let{timestamp:h,icon:m="",tag:g="",message:R,level:I,showTimestamp:S=!0}=s,L=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(S)F.push(h);if(I==="warning")F.push("WARN");else if(I==="error")F.push("ERROR");else if(m)F.push(m.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(g)F.push(g.replace(/[[\]]/g,""));return F.push(R),F.join(" ")}let T=Ee.stdout.columns||120,A="";if(I==="warning"||I==="error")A=`${m} ${R}`;else if(I==="info"||I==="success")A=`${m} ${g} ${R}`;else A=`${m} ${g} ${Ce.cyan(R)}`;if(!S)return A.trim();let O=L(A).trim().length,_=L(h).length,D=Math.max(1,T-2-O-_);return`${A.trim()}${" ".repeat(D)}${h}`}formatMessage(s,h){if(h.length===1&&Array.isArray(h[0]))return s.replace(/\{(\d+)\}/g,(I,S)=>{let L=Number.parseInt(S,10);return L<h[0].length?String(h[0][L]):I});let m=/%([sdijfo%])/g,g=0,R=s.replace(m,(I,S)=>{if(S==="%")return"%";if(g>=h.length)return I;let L=h[g++];switch(S){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return I}});if(g<h.length)R+=` ${h.slice(g).map((I)=>typeof I==="object"?JSON.stringify(I,null,2):String(I)).join(" ")}`;return R}formatMarkdown(s){if(!s)return s;let h=s;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(m,g,R)=>{let I=Ce.underline(Ce.blue(g)),S=this.toAbsoluteFilePath(R);if(S&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(S)}`,T="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${L}\x1B\\${I}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${R}\x1B\\${I}\x1B]8;;\x1B\\`;return I}),h=h.replace(/`([^`]+)`/g,(m,g)=>Ce.bgGray(g)),h=h.replace(/\*\*([^*]+)\*\*/g,(m,g)=>Ce.bold(g)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(m,g)=>Ce.italic(g)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(m,g)=>Ce.italic(g)),h=h.replace(/~([^~]+)~/g,(m,g)=>Ce.strikethrough(g)),h}supportsHyperlinks(){if(Ue())return!1;let s=Ee.env;if(!s)return!1;if(s.TERM_PROGRAM==="iTerm.app"||s.TERM_PROGRAM==="vscode"||s.TERM_PROGRAM==="WezTerm")return!0;if(s.WT_SESSION)return!0;if(s.TERM==="xterm-kitty")return!0;let h=s.VTE_VERSION?Number.parseInt(s.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath(s){try{let h=s;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let m=Ee.env.HOME||"";if(m)h=h.replace(/^~(?=$|\/)/,m)}if(fd(h)||h.startsWith("./")||h.startsWith("../"))h=md(h);else return null;return pn(h)?h:null}catch{return null}}buildOutputTexts(s){let h=this.shouldStyleConsole()?this.formatMarkdown(s):s,m=s.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:m}}async log(s,h,...m){if(!this.shouldLog(s))return;let g=new Date,R=this.formatConsoleTimestamp(g),I=this.formatFileTimestamp(g),S,L;if(h instanceof Error)S=h.message,L=h.stack;else S=this.formatMessage(h,m);let{consoleText:T,fileText:A}=this.buildOutputTexts(S);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":xd[s],D=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",F;switch(s){case"debug":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ce.gray(T),level:s}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:Ce.green(T),level:s}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:R,icon:_,tag:D,message:T,level:s}),console.error(F),L){let N=L.split(`
|
|
41
41
|
`);for(let W of N)if(W.trim()&&!W.includes(S))console.error(this.formatConsoleMessage({timestamp:R,message:Ce.gray(` ${W}`),level:s,showTimestamp:!1}))}break}}else if(!Ue()){if(console.error(`${I} ${this.environment}.${s.toUpperCase()}: ${S}`),L)console.error(L)}let O=`${I} ${this.environment}.${s.toUpperCase()}: ${A}
|
|
42
42
|
`;if(L)O+=`${L}
|
|
43
43
|
`;if(O=O.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(O)}progress(s,h=""){let m={update:(L,T)=>{},finish:(L)=>{},interrupt:(L,T)=>{}};if(!this.enabled)return m;let g=30;if(this.activeProgressBar={total:Math.max(1,s||1),current:0,message:h||"",barLength:g,lastRenderedLine:""},this.shouldStyleConsole()&&!Ue()&&Ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,T)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),T!==void 0)this.activeProgressBar.message=T;if(this.shouldStyleConsole()&&!Ue()&&Ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,T="info")=>{if(!Ue()&&Ee.stdout.isTTY)Ee.stdout.write(`
|
|
44
44
|
`);if(this[T==="warning"?"warn":T](L),this.activeProgressBar&&this.shouldStyleConsole()&&!Ue()&&Ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(s){let h=performance.now();if(this.shouldStyleConsole()){let m=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",g=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:g,icon:this.options.showIcons===!1?"":Ce.blue("\u25D0"),tag:m,message:`${Ce.cyan(s)}...`}))}return async(m)=>{if(!this.enabled)return;let g=performance.now(),R=Math.round(g-h),I=`${s} completed in ${R}ms`,S=new Date,L=this.formatConsoleTimestamp(S),A=`${this.formatFileTimestamp(S)} ${this.environment}.INFO: ${I}`;if(m)A+=` ${JSON.stringify(m)}`;if(A+=`
|
|
45
|
-
`,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let O=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":Ce.green("\u2713"),tag:O,message:`${I}${m?` ${JSON.stringify(m)}`:""}`}))}else if(!Ue())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(s,...h){await this.log("debug",s,...h)}async info(s,...h){await this.log("info",s,...h)}async success(s,...h){await this.log("success",s,...h)}async warn(s,...h){await this.log("warning",s,...h)}async error(s,...h){await this.log("error",s,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let s=this.config.rotation,{encrypt:h}=s;return!!h}async only(s){if(!this.enabled)return;return await s()}isEnabled(){return this.enabled}setEnabled(s){this.enabled=s}extend(s){let h=`${this.name}:${s}`,m=new wt(h,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(m),m}createReadStream(){if(Ue())throw Error("createReadStream is not supported in browser environments");if(!
|
|
45
|
+
`,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let O=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":Ce.green("\u2713"),tag:O,message:`${I}${m?` ${JSON.stringify(m)}`:""}`}))}else if(!Ue())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(s,...h){await this.log("debug",s,...h)}async info(s,...h){await this.log("info",s,...h)}async success(s,...h){await this.log("success",s,...h)}async warn(s,...h){await this.log("warning",s,...h)}async error(s,...h){await this.log("error",s,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let s=this.config.rotation,{encrypt:h}=s;return!!h}async only(s){if(!this.enabled)return;return await s()}isEnabled(){return this.enabled}setEnabled(s){this.enabled=s}extend(s){let h=`${this.name}:${s}`,m=new wt(h,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(m),m}createReadStream(){if(Ue())throw Error("createReadStream is not supported in browser environments");if(!pn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fo(this.currentLogFile,{encoding:"utf8"})}async decrypt(s){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let m=this.keys.get(this.currentKeyId);try{let g=at.isBuffer(s)?s:at.from(s,"base64"),R=g.subarray(0,16),I=g.subarray(g.length-16),S=g.subarray(16,g.length-16),L=od("aes-256-gcm",m,R);L.setAuthTag(I);let T=L.update(S),A=L.final(),O=T.length+A.length,_=at.allocUnsafe(O);return T.copy(_,0),A.copy(_,T.length),_.toString("utf8")}catch(g){throw Error(`Decryption failed: ${g instanceof Error?g.message:String(g)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ue()}isServerMode(){return!Ue()}setTestEncryptionKey(s,h){this.currentKeyId=s,this.keys.set(s,h)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(s){if(!this.enabled)return;let h=new Date,m=this.formatConsoleTimestamp(h),g=this.formatFileTimestamp(h),{consoleText:R,fileText:I}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let L=R.split(`
|
|
46
46
|
`),T=Math.max(...L.map((D)=>D.length))+2,A=`\u250C${"\u2500".repeat(T)}\u2510`,O=`\u2514${"\u2500".repeat(T)}\u2518`,_=L.map((D)=>this.formatConsoleMessage({timestamp:m,message:Ce.cyan(D),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:m,message:Ce.cyan(A),showTimestamp:!1})),_.forEach((D)=>console.error(D)),console.error(this.formatConsoleMessage({timestamp:m,message:Ce.cyan(O),showTimestamp:!1}))}else if(!Ue())console.error(`${g} ${this.environment}.INFO: [BOX] ${I}`);let S=`${g} ${this.environment}.INFO: [BOX] ${I}
|
|
47
47
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(S)}async prompt(s){if(Ue())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${Ce.cyan("?")} ${s} (y/n) `);let m=(g)=>{let R=g.toString().trim().toLowerCase();Ee.stdin.removeListener("data",m);try{if(typeof Ee.stdin.setRawMode==="function")Ee.stdin.setRawMode(!1)}catch{}Ee.stdin.pause(),console.error(""),h(R==="y"||R==="yes")};try{if(typeof Ee.stdin.setRawMode==="function")Ee.stdin.setRawMode(!0)}catch{}Ee.stdin.resume(),Ee.stdin.once("data",m)})}setFancy(s){this.fancy=s}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(s,...h){if(!this.enabled)return;let m=s;if(h&&h.length>0){let T=/%([sdijfo%])/g,A=0;if(m=s.replace(T,(O,_)=>{if(_==="%")return"%";if(A>=h.length)return O;let D=h[A++];switch(_){case"s":return String(D);case"d":case"i":return Number(D).toString();case"j":case"o":return JSON.stringify(D,null,2);default:return O}}),A<h.length)m+=` ${h.slice(A).map((O)=>typeof O==="object"?JSON.stringify(O,null,2):String(O)).join(" ")}`}let{consoleText:g,fileText:R}=this.buildOutputTexts(m);if(this.shouldStyleConsole()){let T=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${Ce.blue("\u25D0")} `;console.error(`${A}${T} ${Ce.cyan(g)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${R}
|
|
48
48
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(s,h=!1){if(!this.enabled||!this.shouldStyleConsole()||!Ee.stdout.isTTY)return;let m=Math.min(100,Math.max(0,Math.round(s.current/s.total*100))),g=Math.round(s.barLength*m/100),R=s.barLength-g,I=Ce.green("\u2501".repeat(g)),S=Ce.gray("\u2501".repeat(R)),L=`[${I}${S}]`,T=`${m}%`.padStart(4),A=s.message?` ${s.message}`:"",O=this.options.showIcons===!1?"":h||m===100?Ce.green("\u2713"):Ce.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${Ce.gray(this.formatTag(this.name))}`:"",D=`\r${O}${_} ${L} ${T}${A}`,F=Ee.stdout.columns||80,N=" ".repeat(Math.max(0,F-D.replace(this.ANSI_PATTERN,"").length));if(s.lastRenderedLine=`${D}${N}`,Ee.stdout.write(s.lastRenderedLine),h)Ee.stdout.write(`
|
|
49
|
-
`)}finishProgressBar(s,h){if(!this.enabled||!this.fancy||Ue()||!Ee.stdout.isTTY){this.activeProgressBar=null;return}if(s.current<s.total)s.current=s.total;if(h)s.message=h;this.renderProgressBar(s,!0),this.activeProgressBar=null}async clear(s={}){if(Ue()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await
|
|
50
|
-
`)}};var
|
|
51
|
-
`)}};var
|
|
52
|
-
`):s}};var
|
|
53
|
-
`):s}};var Do=["undefined","object","boolean","number","string","function","symbol","bigint"],ss={meta:{docs:"Enforce comparing typeof expressions against valid strings",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/typeof\s+\w+\s*(?:===|!==|==|!=)\s*(['"`])(\w+)\1/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let A=L[2];if(!Do.includes(A))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/valid-typeof",message:`Invalid typeof comparison value '${A}'`,severity:"error"})}let T=/(['"`])(\w+)\1\s*(?:===|!==|==|!=)\s*typeof\s+\w+/g;for(L=T.exec(I);L!==null;L=T.exec(I)){let A=L[2];if(!Do.includes(A))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/valid-typeof",message:`Invalid typeof comparison value '${A}'`,severity:"error"})}}return m}};var is={meta:{docs:"Enforce a maximum cyclomatic complexity allowed in a program",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=10,I=!1,S=0,L="",T=0,A=0;for(let O=0;O<g.length;O++){let _=g[O],D=_.match(/\bfunction\s+(\w+)\s*\(|(\w+)\s*=\s*(?:\([^)]*\)|(\w+))\s*=>/);if(D)I=!0,S=O+1,L=D[1]||D[2]||D[3]||"anonymous",T=1,A=0;if(I){for(let N of _){if(N==="{")A++;if(N==="}"){if(A--,A===0){if(T>10)m.push({filePath:h.filePath,line:S,column:1,ruleId:"eslint/complexity",message:`Function '${L}' has complexity ${T}, exceeds maximum of 10`,severity:"error"});I=!1}}}let F=[/\bif\s*\(/,/\belse\s+if\s*\(/,/\bfor\s*\(/,/\bwhile\s*\(/,/\bcase\s+/,/\bcatch\s*\(/,/\b&&\b/,/\b\|\|\b/,/\?\s*(?:\S.*(?:[\n\r\u2028\u2029]\s*)?)?:/];for(let N of F){let W=_.match(new RegExp(N,"g"));if(W)T+=W.length}}}return m}};var rs={meta:{docs:"Require default case in switch statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=0,S=!1,L=0;for(let T=0;T<g.length;T++){let A=g[T];if(A.match(/\bswitch\s*\(/))R=!0,I=T+1,S=!1,L=0;if(R){for(let O of A){if(O==="{")L++;if(O==="}"){if(L--,L===0){if(!S)m.push({filePath:h.filePath,line:I,column:1,ruleId:"eslint/default-case",message:"Expected a default case",severity:"error"});R=!1}}}if(A.match(/\bdefault\s*:/))S=!0}}return m}};var os={meta:{docs:"Require === and !== instead of == and !=",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/([^=!])(\s*)(==)(\s*)([^=])/g,L=/([^!])(\s*)(!=)(\s*)([^=])/g,T;for(T=S.exec(I);T!==null;T=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+2),ruleId:"eslint/eqeqeq",message:"Expected '===' and instead saw '=='",severity:"error"});for(T=L.exec(I);T!==null;T=L.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+2),ruleId:"eslint/eqeqeq",message:"Expected '!==' and instead saw '!='",severity:"error"})}return m},fix:(s)=>{let h=s;return h=h.replace(/([^!])(\s*)(!=)(\s*)([^=])/g,"$1$2!==$4$5"),h=h.replace(/([^=!])(\s*)(==)(\s*)([^=])/g,"$1$2===$4$5"),h}};var ls={meta:{docs:"Enforce a maximum depth that blocks can be nested",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=4,I=0,S=0,L=0;for(let T=0;T<g.length;T++){let A=g[T];if(A.match(/\b(if|for|while|switch|try|catch|else)\b.*\{/)){if(I++,I>S)S=I,L=T+1}else if(A.match(/\{/)&&!A.match(/^.*\}/)){if(g[T-1]?.match(/\b(if|for|while|switch|try|catch|else)\b/)){if(I++,I>S)S=I,L=T+1}}if(A.match(/^\s*\}/))I--;if(I>4)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"eslint/max-depth",message:`Blocks are nested too deeply (${I}), maximum allowed is 4`,severity:"error"})}return m}};var as={meta:{docs:"Enforce a maximum number of lines of code in a function",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=50,I=!1,S=0,L="",T=0;for(let A=0;A<g.length;A++){let O=g[A],_=O.match(/\bfunction\s+(\w+)\s*\(|(\w+)\s*=\s*(?:\([^)]*\)|(\w+))\s*=>/);if(_)I=!0,S=A+1,L=_[1]||_[2]||_[3]||"anonymous",T=0;if(I)for(let D of O){if(D==="{")T++;if(D==="}"){if(T--,T===0){let F=A+1-S+1;if(F>50)m.push({filePath:h.filePath,line:S,column:1,ruleId:"eslint/max-lines-per-function",message:`Function '${L}' has ${F} lines, exceeds maximum of 50`,severity:"error"});I=!1}}}}return m}};var cs={meta:{docs:"Disallow alert, confirm, and prompt",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b(alert|confirm|prompt)\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-alert",message:`Unexpected ${L[1]}`,severity:"warning"})}}return m}};var us={meta:{docs:"Disallow await inside of loops",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=0,S=0;for(let L=0;L<g.length;L++){let T=g[L];if(T.match(/\b(for|while|do)\s*\(/))R=!0,I=0,S=L;if(R){for(let A of T){if(A==="{")I++;if(A==="}"){if(I--,I===0)R=!1}}if(T.match(/\bawait\s+/))m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"eslint/no-await-in-loop",message:"Unexpected await inside a loop. Consider using Promise.all() instead",severity:"error"})}}return m}};var fs={meta:{docs:"Disallow use of arguments.caller or arguments.callee",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\barguments\s*\.\s*(caller|callee)\b/g,L;for(L=S.exec(I);L!==null;L=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"eslint/no-caller",message:`Avoid arguments.${L[1]}`,severity:"error"})}return m}};var ms={meta:{docs:"Disallow lexical declarations in case clauses",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=!1;for(let S=0;S<g.length;S++){let L=g[S];if(L.match(/\bcase\s+(?:\S.*)?:|default\s*:/))R=!0,I=!0;else I=!1;if(R&&!I&&(L.match(/\bbreak\b/)||L.match(/\bcase\s+(?:\S.*)?:/)))R=!1;if(R&&!I){if(L.match(/\b(let|const|function|class)\s+/))m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"eslint/no-case-declarations",message:"Unexpected lexical declaration in case block",severity:"error"})}}return m}};var hs={meta:{docs:"Disallow else blocks after return statements in if statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(!/^\s*else\b/.test(I))continue;let S=!1;for(let L=R-1;L>=0&&L>=R-10;L--){let T=g[L].trim();if(T.startsWith("return"))S=!0;if(T==="}"&&S)break;if(T.includes("{"))break}if(S)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("else")+1),ruleId:"eslint/no-else-return",message:"Unnecessary else after return",severity:"warning"})}return m}};var ds={meta:{docs:"Disallow empty block statements",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\{\s*\}/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=I.substring(0,L.index).trim(),A=/(?:if|else|for|while|do|try|catch|finally|function|\})\s*$/.test(T),O=/[=:]$/.test(T)||/return\s*$/.test(T);if(A&&!O)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-empty",message:"Empty block statement",severity:"error"})}}for(let R=0;R<g.length-1;R++){let I=g[R],S=g[R+1];if(/\{\s*$/.test(I.trim()))for(let L=R+1;L<g.length;L++){let T=g[L].trim();if(T==="")continue;if(T==="}"||T.startsWith("}")){let A=I.substring(0,I.lastIndexOf("{")).trim(),O=/(?:if|else|for|while|do|try|catch|finally|function|\})\s*$/.test(A),_=/[=:]$/.test(A)||/return\s*$/.test(A);if(O&&!_)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.lastIndexOf("{")+1),ruleId:"eslint/no-empty",message:"Empty block statement",severity:"error"})}break}}return m}};var ps={meta:{docs:"Disallow empty functions",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[/function\s+\w+\s*\([^)]*\)\s*\{\s*\}/g,/function\s*\([^)]*\)\s*\{\s*\}/g,/\([^)]*\)\s*=>\s*\{\s*\}/g,/\w+\s*\([^)]*\)\s*\{\s*\}/g];for(let L of S){let T;for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-empty-function",message:"Unexpected empty function",severity:"warning"})}}}return m}};var gs={meta:{docs:"Disallow use of eval()",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\beval\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-eval",message:"eval can be harmful",severity:"error"})}}return m}};var hd=["Object","Array","String","Number","Boolean","Date","RegExp","Function","Math","JSON","Promise","Map","Set","WeakMap","WeakSet","Symbol","Proxy","Reflect","Error","TypeError","RangeError"],ys={meta:{docs:"Disallow extending native types",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];for(let S of hd){let L=new RegExp(`\\b${S}\\.prototype\\.\\w+\\s*=`,"g"),T;for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-extend-native",message:`${S} prototype is read only, properties should not be added`,severity:"error"})}}}return m}};var bs={meta:{docs:"Disallow unnecessary boolean casts",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[/\bif\s*\(\s*Boolean\s*\(/g,/\bwhile\s*\(\s*Boolean\s*\(/g,/!\s*Boolean\s*\(/g,/\?\s*Boolean\s*\(/g,/&&\s*Boolean\s*\(/g,/\|\|\s*Boolean\s*\(/g,/!!\s*\w+/g];for(let L of S){let T;for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-extra-boolean-cast",message:"Redundant Boolean call or double negation",severity:"error"})}}}return m},fix:(s)=>{let h=s;return h=h.replace(/\b(if|while)\s*\(\s*Boolean\s*\(([^)]+)\)\s*\)/g,"$1 ($2)"),h=h.replace(/!\s*Boolean\s*\(([^)]+)\)/g,"!$1"),h=h.replace(/!!\s*(\w+)/g,"$1"),h}};var dd=["Array","Boolean","Date","Error","Function","JSON","Math","Number","Object","RegExp","String","Symbol","undefined","NaN","Infinity","isNaN","isFinite","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","eval","Promise","Proxy","Reflect","Set","Map","WeakSet","WeakMap","ArrayBuffer","DataView","console","window","document","globalThis","global","process"],xs={meta:{docs:"Disallow assignment to native objects or read-only global variables",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];for(let S of dd){let L=new RegExp(`\\b${S}\\s*=\\s*[^=]`,"g"),T;for(T=L.exec(I);T!==null;T=L.exec(I))if(!I.slice(T.index).match(new RegExp(`^${S}\\s*===?`)))m.push({filePath:h.filePath,line:R+1,column:T.index+1,ruleId:"eslint/no-global-assign",message:`Read-only global '${S}' should not be modified`,severity:"error"})}}return m}};var ws={meta:{docs:"Disallow implied eval() via setTimeout/setInterval with strings",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b(setTimeout|setInterval)\s*\(\s*(['"`])/g,L;while((L=S.exec(I))!==null){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-implied-eval",message:"Implied eval. Consider passing a function instead of a string",severity:"error"})}}return m}};var Rs={meta:{docs:"Disallow the use of the __iterator__ property",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/__iterator__/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-iterator",message:"Reserved name '__iterator__'",severity:"error"})}}return m}};var Yt={meta:{docs:"Disallow if statements as the only statement in else blocks",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(/^\s*else\s*(?:\{\s*)?$/.test(I)){let L=R,T=I.includes("{");if(!T){if(R+1<g.length&&g[R+1].trim()==="{")L=R+1,T=!0}if(T)for(let A=L+1;A<g.length;A++){let O=g[A].trim();if(O===""||O.startsWith("//")||O.startsWith("/*"))continue;if(O==="}")break;if(O.startsWith("if ")||O.startsWith("if(")){let _=!0,D=0,F=!1;for(let N=A;N<g.length;N++){let W=g[N];if(D+=(W.match(/\{/g)||[]).length,D-=(W.match(/\}/g)||[]).length,N===A){F=!0;continue}if(D===0){for(let B=N+1;B<g.length;B++){let j=g[B].trim();if(j===""||j.startsWith("//"))continue;if(j==="}"||j.startsWith("}"))break;else _=!1;break}break}}if(F&&_)m.push({filePath:h.filePath,line:A+1,column:Math.max(1,g[A].indexOf("if")+1),ruleId:"eslint/no-lonely-if",message:"Unexpected if as the only statement in an else block",severity:"warning"})}break}}}return m},fix:(s,h)=>{if(Yt.check(s,h).length===0)return s;return s}};var ks={meta:{docs:"Disallow new operators outside of assignments or comparisons",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(/^\s*new\s+\w+\s*\(/.test(I)){if(!/[=:]/.test(I.substring(0,I.indexOf("new"))))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("new")+1),ruleId:"eslint/no-new",message:"Do not use 'new' for side effects",severity:"warning"})}}return m}};var $s={meta:{docs:"Disallow new Function() declarations",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\bnew\s+Function\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-new-func",message:"The Function constructor is eval",severity:"error"})}}return m}};var Ps={meta:{docs:"Disallow new operators with String, Number, and Boolean",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\bnew\s+(String|Number|Boolean)\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-new-wrappers",message:`Do not use ${L[1]} as a constructor`,severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=!1,g=h.map((R)=>{if(R.trim().startsWith("//")||R.trim().startsWith("/*"))return R;return R.replace(/\bnew\s+(String|Number|Boolean)\s*\(/g,(S,L)=>(m=!0,`${L}(`))});return m?g.join(`
|
|
54
|
-
`):s}};var
|
|
55
|
-
`):s}};var
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
`)
|
|
60
|
-
`)break;else if(F==="/"&&!_){O+=1;break}O+=1}m=O;continue}if(A==="/"&&s[m+1]==="/"){let O=s.indexOf(`
|
|
61
|
-
`,m);T(m+2,O<0?s.length:O),m=O<0?s.length:O;continue}if(A==="/"&&s[m+1]==="*"){let O=s.indexOf("*/",m+2);T(m+2,O<0?s.length:O),m=O<0?s.length:O+2;continue}m+=1}return h.join("")}var gt={meta:{docs:"Report variables and parameters that are declared/assigned but never used"},check:(s,h)=>{if(h.filePath.endsWith("/no-unused-vars.ts"))return[];if(h.filePath.endsWith(".d.ts"))return[];let m=[],g=h.options||{},R=typeof g.varsIgnorePattern==="string"?g.varsIgnorePattern:"^_",I=typeof g.argsIgnorePattern==="string"?g.argsIgnorePattern:"^_",S=new RegExp(R,"u"),L=new RegExp(I,"u"),T=Wi(s),A=T.split(/\r?\n/),O=T,_=Array(A.length).fill(!1);(()=>{let H=[],Y=!1,se=!1,G=!1,le=!1,te=!1,ie="",X=()=>{if(ie==="")return!0;if("=([{,;!&|?:+-*/%^~<>".includes(ie))return!0;return!1};for(let ne=0;ne<A.length;ne++){_[ne]=H.length>0&&H[H.length-1]===-1;let oe=A[ne];for(let ee=0;ee<oe.length;ee++){let q=oe[ee];if(le){if(q==="*"&&ee+1<oe.length&&oe[ee+1]==="/")le=!1,ee++;continue}if(te){te=!1;continue}let Q=H.length>0&&H[H.length-1]===-1,Z=H.length>0&&H[H.length-1]>=0;if(q==="\\"&&(Y||se||G||Q)){te=!0;continue}if(Y){if(q==="'")Y=!1;continue}if(se){if(q==='"')se=!1;continue}if(G){if(q==="["){let re=1,we=ee+1;while(we<oe.length){let pe=oe[we];if(pe==="\\"){we+=2;continue}if(pe==="]"){if(re--,re===0)break}we++}ee=we;continue}if(q==="/"){G=!1;while(ee+1<oe.length&&/[gimsuvy]/.test(oe[ee+1]))ee++}continue}if(Q){if(q==="`")H.pop();else if(q==="$"&&ee+1<oe.length&&oe[ee+1]==="{")H.push(0),ee++;continue}if(q==="/"&&ee+1<oe.length&&oe[ee+1]==="/")break;if(q==="/"&&ee+1<oe.length&&oe[ee+1]==="*"){le=!0,ee++;continue}if(Z){if(q==="`")H.push(-1),ie="";else if(q==="'")Y=!0,ie="'";else if(q==='"')se=!0,ie='"';else if(q==="{")H[H.length-1]++,ie="{";else if(q==="}"){let re=H[H.length-1];if(re>0)H[H.length-1]=re-1;else H.pop();ie="}"}else if(q==="/"&&X())G=!0;else if(!/\s/.test(q))ie=q;continue}if(q==="`")H.push(-1),ie="";else if(q==="'")Y=!0,ie="'";else if(q==='"')se=!0,ie='"';else if(q==="/"&&X())G=!0;else if(!/\s/.test(q))ie=q}}})();let F=new RegExp("^\\s*(?:const|let|var)\\s+(.+?);?\\s*$");for(let H=0;H<A.length;H++){if(_[H])continue;let Y=A[H],se=Y.match(F);if(!se)continue;let G=se[1],le=[],te="",ie=0,X=0,ne=null,oe=!1;for(let ee=0;ee<G.length;ee++){let q=G[ee];if(oe){oe=!1,te+=q;continue}if(q==="\\"&&ne){oe=!0,te+=q;continue}if(!ne){if(q==="/"&&G[ee+1]==="/")break;if(q==="/"&&G[ee+1]==="*"){ee+=2;while(ee<G.length&&!(G[ee]==="*"&&G[ee+1]==="/"))ee++;ee++;continue}if(q==="'")ne="single";else if(q==='"')ne="double";else if(q==="`")ne="template";else if(q==="<")X++;else if(q===">")X--;else if(q==="("||q==="["||q==="{")ie++;else if(q===")"||q==="]"||q==="}")ie--;else if(q===","&&ie===0&&X===0){le.push(te),te="";continue}}else if(ne==="single"&&q==="'"||ne==="double"&&q==='"'||ne==="template"&&q==="`")ne=null;te+=q}if(te)le.push(te);for(let ee of le){let q=ee.trim();if(!q)continue;let Q=q.match(/^([$A-Z_][\w$]*)/i),Z=[];if(Q)Z.push(Q[1]);else if(q.startsWith("{")||q.startsWith("[")){let re=q[0],we=re==="{"?"}":"]",pe=0,ue=-1,ae=null,xe=!1;for(let Me=0;Me<q.length;Me++){let de=q[Me];if(xe){xe=!1;continue}if(de==="\\"&&ae){xe=!0;continue}if(!ae){if(de==="'"||de==='"'||de==="`")ae=de==="'"?"single":de==='"'?"double":"template";else if(de===re)pe++;else if(de===we){if(pe--,pe===0){ue=Me;break}}}else if(ae==="single"&&de==="'"||ae==="double"&&de==='"'||ae==="template"&&de==="`")ae=null}if(ue>0){let Me=q.slice(1,ue),de=[],Pe="",Fe=0,fe=null,ye=!1;for(let ge=0;ge<Me.length;ge++){let me=Me[ge];if(ye){ye=!1,Pe+=me;continue}if(me==="\\"&&fe){ye=!0,Pe+=me;continue}if(!fe){if(me==="'"||me==='"'||me==="`"){fe=me==="'"?"single":me==='"'?"double":"template",Pe+=me;continue}if(me==="("||me==="{"||me==="[")Fe++;if(me===")"||me==="}"||me==="]")Fe--;if(me===","&&Fe===0){de.push(Pe.trim()),Pe="";continue}}else if(fe==="single"&&me==="'"||fe==="double"&&me==='"'||fe==="template"&&me==="`")fe=null;Pe+=me}if(Pe.trim())de.push(Pe.trim());for(let ge of de){if(ge.startsWith("...")){let ze=ge.slice(3).match(/^([$A-Z_][\w$]*)/i);if(ze)Z.push(ze[1]);continue}let me=ge.indexOf(":");if(me!==-1){let ze=ge.slice(me+1).trim(),We=0;for(let ot=0;ot<ze.length;ot++){let Ge=ze[ot];if(Ge==="("||Ge==="{"||Ge==="[")We++;else if(Ge===")"||Ge==="}"||Ge==="]")We--;else if(Ge==="="&&We===0){ze=ze.slice(0,ot).trim();break}}let zt=ze.match(/^([$A-Z_][\w$]*)/i);if(zt)Z.push(zt[1])}else{let ze=ge,We=0;for(let ot=0;ot<ze.length;ot++){let Ge=ze[ot];if(Ge==="("||Ge==="{"||Ge==="[")We++;else if(Ge===")"||Ge==="}"||Ge==="]")We--;else if(Ge==="="&&We===0){ze=ze.slice(0,ot).trim();break}}let zt=ze.match(/^([$A-Z_][\w$]*)/i);if(zt)Z.push(zt[1])}}}}for(let re of Z){if(S.test(re))continue;let we=`${A.slice(0,H).join(`
|
|
49
|
+
`)}finishProgressBar(s,h){if(!this.enabled||!this.fancy||Ue()||!Ee.stdout.isTTY){this.activeProgressBar=null;return}if(s.current<s.total)s.current=s.total;if(h)s.message=h;this.renderProgressBar(s,!0),this.activeProgressBar=null}async clear(s={}){if(Ue()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await gn(this.config.logDirectory),m=[];for(let g of h){if(!(s.name?new RegExp(s.name.replace("*",".*")).test(g):g.startsWith(this.name))||!g.endsWith(".log"))continue;let I=At(this.config.logDirectory,g);if(s.before)try{if((await Tt(I)).mtime>=s.before)continue}catch(S){console.error(`Failed to get stats for file ${I}:`,S);continue}m.push(I)}if(m.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${m.length} log file(s)...`);for(let g of m)try{await yn(g),console.warn(`Deleted log file: ${g}`)}catch(R){console.error(`Failed to delete log file ${g}:`,R)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}var Jy=new wt("stacks");import{readFileSync as im,writeFileSync as pg}from"fs";import{isAbsolute as gg,relative as nm,resolve as yg}from"path";var Dn={meta:{docs:"Enforce return statements in callbacks of array methods",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=new RegExp(`\\.(${["map","filter","find","findIndex","findLast","findLastIndex","every","some","reduce","reduceRight","sort","flatMap"].join("|")})\\s*\\(`,"g");for(let S=0;S<g.length;S++){let L=g[S],T;for(T=I.exec(L);T!==null;T=I.exec(L)){let A=T[1],O=T.index+T[0].length,_=L.slice(O),D=_.match(/^\s*(?:\(([^)]*)\)|([a-z_$][\w$]*))\s*=>/i),F=_.match(/^\s*function\s*(?:[a-zA-Z_$][\w$]*\s*)?\(/);if(D){let N=_.slice(D[0].length).trim();if(N.startsWith("{")){let W=!1,B=0,j=N,z=S;while(z<g.length){let K=z===S?j:g[z];for(let V=0;V<K.length;V++){let G=K[V];if(G==="{")B++;if(G==="}"){if(B--,B===0){if(!W)m.push({filePath:h.filePath,line:S+1,column:T.index+1,ruleId:"eslint/array-callback-return",message:`Array method '${A}' callback should return a value`,severity:"error"});break}}}if(K.match(new RegExp("\\breturn\\s+[^;]")))W=!0;if(B===0)break;z++,j=g[z]||""}}}else if(F){let N=!1,W=0,B=S,j=!1;while(B<g.length){let z=g[B];for(let K=0;K<z.length;K++){let V=z[K];if(V==="{")W++,j=!0;else if(V==="}"){if(W--,W===0&&j){if(!N)m.push({filePath:h.filePath,line:S+1,column:T.index+1,ruleId:"eslint/array-callback-return",message:`Array method '${A}' callback should return a value`,severity:"error"});break}}}if(j&&z.match(new RegExp("\\breturn\\s+[^;]")))N=!0;if(W===0&&j)break;B++}}}}return m}};var Fn={meta:{docs:"Require super() calls in constructors of derived classes",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=!1,S=0,L=0,T=!1;for(let A=0;A<g.length;A++){let O=g[A];if(O.match(/\bclass\s+\w+\s+extends\s+\w+/))R=!0;if(R&&O.match(/\bconstructor\s*\(/))I=!0,S=A+1,L=0,T=!1;if(I){for(let _ of O){if(_==="{")L++;if(_==="}")L--}if(O.match(/\bsuper\s*\(/))T=!0;if(L===0&&O.includes("}")){if(!T)m.push({filePath:h.filePath,line:S,column:1,ruleId:"eslint/constructor-super",message:"Constructors of derived classes must call super()",severity:"error"});I=!1,R=!1}}}return m}};var Nn={meta:{docs:'Enforce "for" loop update clause moving counter in the right direction',recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=new RegExp("\\bfor\\s*\\(\\s*(?:(?:let|var|const)\\s*)?(\\w+)\\s*=[^;]+;\\s*(\\w+)\\s*([<>]=?)[^;]+;\\s*(\\w+)(\\+\\+|--|[\\s+-]=)"),L=I.match(S);if(L){let T=L[1],A=L[2],O=L[3],_=L[4],D=L[5];if(T===A&&A===_){let F=D.includes("+"),N=O.includes("<");if(N&&!F||!N&&F)m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"eslint/for-direction",message:"The update clause in this loop moves the variable in the wrong direction",severity:"error"})}}}return m}};var Wn={meta:{docs:"Enforce return statements in getters",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let S=g[R].match(/\bget\s+(\w+)\s*\(/);if(S){let L=S[1],T=!1,A=0,O=R;while(O<g.length){let _=g[O];for(let F of _){if(F==="{")A++;if(F==="}"){if(A--,A===0){if(!T)m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"eslint/getter-return",message:`Getter '${L}' must return a value`,severity:"error"});break}}}let D=new RegExp("\\breturn\\s+[^;]");if(_.match(D))T=!0;if(A===0)break;O++}}}return m}};var Bn={meta:{docs:"Disallow async functions as Promise executor",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/new\s+Promise\s*\(\s*async\s*(?:\(|function)/g,L;for(L=S.exec(I);L!==null;L=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"eslint/no-async-promise-executor",message:"Promise executor functions should not be async",severity:"error"})}return m}};var jn={meta:{docs:"Disallow comparing against -0",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/([!=]==?)\s*-0\b|\b-0\s*([!=]==?)/g,L;for(L=S.exec(I);L!==null;L=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"eslint/no-compare-neg-zero",message:"Do not use the '-0' literal in comparisons",severity:"error"})}return m}};var Un={meta:{docs:"Disallow assignment operators in conditional expressions",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b(if|while)\s*\([^)]*\b(\w+)\s*=\s*(?!=)[^)]*\)/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[0];if(/===|==/.test(T))continue;if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-cond-assign",message:"Expected a conditional expression and instead saw an assignment",severity:"error"})}}return m}};var zn={meta:{docs:"Disallow reassigning const variables",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=new Map;for(let I=0;I<g.length;I++){let S=g[I],L=S.match(/\bconst\s+(\w+)/);if(L)R.set(L[1],I);let T=/\b(\w+)\s*=(?!=)/g,A;for(A=T.exec(S);A!==null;A=T.exec(S)){let O=A[1],_=S.substring(0,A.index);if(!/\b(?:const|let|var)\s*$/.test(_)&&R.has(O))m.push({filePath:h.filePath,line:I+1,column:Math.max(1,A.index+1),ruleId:"eslint/no-const-assign",message:`'${O}' is constant`,severity:"error"})}}return m}};var qn={meta:{docs:"Disallow constant expressions in conditions",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[{pattern:/\b(if|while)\s*\(\s*(true|false)\s*\)/g,type:"boolean"},{pattern:/\b(if|while)\s*\(\s*(\d+)\s*\)/g,type:"number"},{pattern:/\b(if|while)\s*\(\s*(['"`][^'"`]*['"`])\s*\)/g,type:"string"}];for(let{pattern:L,type:T}of S){let A;while((A=L.exec(I))!==null){let O=A[1];if(I.substring(0,A.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,A.index+O.length+2),ruleId:"eslint/no-constant-condition",message:"Unexpected constant condition",severity:"error"})}}}return m}};var Kn={meta:{docs:"Disallow duplicate class members",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=new Set,S=0;for(let L=0;L<g.length;L++){let T=g[L];if(T.match(/\bclass\s+\w+/))R=!0,I=new Set,S=0;if(R){for(let O of T){if(O==="{")S++;if(O==="}"){if(S--,S===0)R=!1}}let A=[...T.matchAll(/^\s*(?:(?:public|private|protected|static|readonly|async)\s*)?(?:get|set)?\s*(\w+)\s*\(/g),...T.matchAll(/^\s*(?:(?:public|private|protected|static|readonly)\s*)?(\w+)\s*[:=]/g)];for(let O of A){let _=O[1];if(I.has(_))m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"eslint/no-dupe-class-members",message:`Duplicate class member '${_}'`,severity:"error"});else I.add(_)}}}return m}};var Jt={meta:{docs:"Disallow duplicate keys in object literals",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=/\{\s*$/,I=/^\s*(?:(['"`])(.+?)\1|(\w+))\s*:/;for(let S=0;S<g.length;S++){let L=g[S];if(!R.test(L)&&!L.includes("{"))continue;let T=new Map,A=(L.match(/\{/g)||[]).length-(L.match(/\}/g)||[]).length,O=S;for(let _=S+1;_<g.length&&A>0;_++){let D=g[_];A+=(D.match(/\{/g)||[]).length,A-=(D.match(/\}/g)||[]).length;let F=D.match(I);if(F){let N=F[2]||F[3];if(N)if(T.get(N)!==void 0)m.push({filePath:h.filePath,line:_+1,column:Math.max(1,D.search(/\S/)+1),ruleId:"eslint/no-dupe-keys",message:`Duplicate key '${N}'`,severity:"error"});else T.set(N,_)}if(A===0)break}}return m},fix:(s,h)=>{let m=Jt.check(s,h);if(m.length===0)return s;let g=s.split(/\r?\n/),R=new Set(m.map((S)=>S.line-1));return g.filter((S,L)=>!R.has(L)).join(`
|
|
50
|
+
`)}};var Vn={meta:{docs:"Disallow duplicate case labels in switch statements",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=new Set,S=-1;for(let L=0;L<g.length;L++){let T=g[L],A=T.trim();if(/\bswitch\s*\(/.test(A)){R=!0,I=new Set,S=L;continue}if(R&&A==="}"&&L>S){let O=g[S].match(/^\s*/)?.[0].length||0;if((T.match(/^\s*/)?.[0].length||0)<=O+2)R=!1,I=new Set}if(R){let O=A.match(/^case\s+(.+?)\s*:/);if(O){let _=O[1].trim();if(I.has(_))m.push({filePath:h.filePath,line:L+1,column:Math.max(1,T.indexOf("case")+1),ruleId:"eslint/no-duplicate-case",message:`Duplicate case label '${_}'`,severity:"error"});else I.add(_)}}}return m}};var Hn={meta:{docs:"Disallow empty destructuring patterns",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\{\s*\}\s*=/g,L=/\[\s*\]\s*=/g,T;for(T=S.exec(I);T!==null;T=S.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-empty-pattern",message:"Unexpected empty object pattern",severity:"error"})}for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-empty-pattern",message:"Unexpected empty array pattern",severity:"error"})}}return m}};var Zn={meta:{docs:"Disallow fallthrough of case statements",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=-1,S=!1;for(let L=0;L<g.length;L++){let A=g[L].trim();if(/\bswitch\s*\(/.test(A)){R=!0;continue}if(R){if(/^case\s+/.test(A)||/^default\s*:/.test(A)){if(I>=0&&S){if(!(/\/\/.*falls?\s*through|\/\*.*falls?\s*through/i.test(g[I])||L>0&&/\/\/.*falls?\s*through|\/\*.*falls?\s*through/i.test(g[L-1])))m.push({filePath:h.filePath,line:I+1,column:Math.max(1,g[I].indexOf("case")+1),ruleId:"eslint/no-fallthrough",message:"Expected a 'break' statement before 'case'",severity:"error"})}I=L,S=!0}if(/\b(?:break|return|throw|continue)\b/.test(A))S=!1;if(A==="}")R=!1,I=-1,S=!1}}return m}};var Gn={meta:{docs:"Disallow number literals that lose precision",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b(\d{17,}(?:\.\d+)?|\d+\.\d{17,})\b/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[1];if(Number(T).toString()!==T)m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"eslint/no-loss-of-precision",message:"This number literal will lose precision at runtime",severity:"error"})}}return m}};var Jn={meta:{docs:"Disallow returning values from Promise executor functions",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++)if(g[R].match(/new\s+Promise\s*\(/)){let L=0,T=!1,A=R;while(A<g.length){let O=g[A];for(let D of O){if(D==="{")L++,T=!0;if(D==="}"){if(L--,L===0&&T)break}}let _=new RegExp("\\breturn\\s+[^;]");if(T&&O.match(_))m.push({filePath:h.filePath,line:A+1,column:1,ruleId:"eslint/no-promise-executor-return",message:"Return values from promise executor functions cannot be read",severity:"error"});if(L===0&&T)break;A++}}return m}};var Yn={meta:{docs:"Disallow variable redeclaration",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=new Map;for(let I=0;I<g.length;I++){let S=g[I],L=/\b(var|let|const)\s+(\w+)/g,T;for(T=L.exec(S);T!==null;T=L.exec(S)){let O=T[2];if(R.get(O)!==void 0)m.push({filePath:h.filePath,line:I+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-redeclare",message:`'${O}' is already defined`,severity:"error"});else R.set(O,I)}let A=/\bfunction\s+(\w+)/g;for(T=A.exec(S);T!==null;T=A.exec(S)){let O=T[1];if(R.get(O)!==void 0)m.push({filePath:h.filePath,line:I+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-redeclare",message:`'${O}' is already defined`,severity:"error"});else R.set(O,I)}}return m}};var Yt={meta:{docs:"Disallow assignments where both sides are identical",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=new RegExp("\\b(\\w+)\\s*=\\s*(\\w+)\\s*(?:;\\s*)?(?:\\/\\/.*)?$"),L=I.match(S);if(L&&L[1]===L[2]){m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf(L[1])+1),ruleId:"eslint/no-self-assign",message:`'${L[1]}' is assigned to itself`,severity:"error"});continue}let T=I.match(/([\w.]+)\s*=\s*([\w.]+)/);if(T&&T[1]===T[2]){m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf(T[1])+1),ruleId:"eslint/no-self-assign",message:`'${T[1]}' is assigned to itself`,severity:"error"});continue}let A=I.match(/(\w+\[[^\]]+\])\s*=\s*(\w+\[[^\]]+\])/);if(A){let O=A[1].replace(/\s/g,""),_=A[2].replace(/\s/g,"");if(O===_)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf(A[1])+1),ruleId:"eslint/no-self-assign",message:`'${A[1]}' is assigned to itself`,severity:"error"})}}return m},fix:(s,h)=>{let m=Yt.check(s,h);if(m.length===0)return s;let g=s.split(/\r?\n/),R=new Set(m.map((S)=>S.line-1));return g.map((S,L)=>{if(R.has(L)){let T=S.trim();if(new RegExp("^\\w+(?:\\.\\w+|\\[[^\\]]+\\])?\\s*=\\s*\\w+(?:\\.\\w+|\\[[^\\]]+\\])?;?\\s*$").test(T))return""}return S}).filter((S,L,T)=>{if(S===""&&R.has(L)){let A=L>0&&T[L-1].trim()!=="",O=L<T.length-1&&T[L+1]&&T[L+1].trim()!=="";if(!A||!O)return!1}return!0}).join(`
|
|
51
|
+
`)}};var Xn={meta:{docs:"Disallow comparisons where both sides are identical",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/([\w.\[\]]+)\s*(===|!==|==|!=|<|>|<=|>=)\s*([\w.\[\]]+)/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[1].replace(/\s/g,""),A=L[2],O=L[3].replace(/\s/g,"");if(T===O)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-self-compare",message:`Comparing '${L[1]}' to itself is potentially pointless`,severity:"error"})}}return m}};var Qn={meta:{docs:"Disallow sparse arrays (arrays with empty slots)",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\[([^\]]*)\]/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[1];if(/,\s*,/.test(T))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-sparse-arrays",message:"Unexpected sparse array",severity:"error"})}}return m},fix:(s,h)=>{let m=s.split(/\r?\n/),g=!1,R=m.map((I)=>{let S=I;return S=S.replace(/\[([^\]]*)\]/g,(L,T)=>{if(/,\s*,/.test(T))return g=!0,`[${T.replace(/,(\s*),/g,", undefined,")}]`;return L}),S});return g?R.join(`
|
|
52
|
+
`):s}};var es={meta:{docs:"Disallow undeclared variables",recommended:!0,wip:!0},check:(s,h)=>[]};var ts={meta:{docs:"Disallow unreachable code after return, throw, continue, or break",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(/^\s*(?:return|throw|break|continue)\b/.test(I))for(let L=R+1;L<g.length;L++){let T=g[L],A=T.trim();if(A===""||A.startsWith("//")||A.startsWith("/*"))continue;if(A==="}"||A.startsWith("}"))break;if(/^(?:case\b|default\s*:)/.test(A))break;m.push({filePath:h.filePath,line:L+1,column:Math.max(1,T.search(/\S/)+1),ruleId:"eslint/no-unreachable",message:"Unreachable code",severity:"error"});break}}return m}};var ns={meta:{docs:"Disallow negation of the left operand of relational operators",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/!\s*\w+\s+in\s+/g,L=/!\s*\w+\s+instanceof\s+/g,T;for(T=S.exec(I);T!==null;T=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:T.index+1,ruleId:"eslint/no-unsafe-negation",message:"Unexpected negation of 'in' operand",severity:"error"});for(T=L.exec(I);T!==null;T=L.exec(I))m.push({filePath:h.filePath,line:R+1,column:T.index+1,ruleId:"eslint/no-unsafe-negation",message:"Unexpected negation of 'instanceof' operand",severity:"error"})}return m},fix:(s)=>{let h=s;return h=h.replace(/!\s*(\w+)\s+in\s+/g,"!($1 in "),h=h.replace(/!\s*(\w+)\s+instanceof\s+/g,"!($1 instanceof "),h}};var ss={meta:{docs:"Disallow unnecessary catch clauses",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.match(/catch\s*\(\s*(\w+)\s*\)/);if(!S)continue;let L=S[1];for(let T=R+1;T<Math.min(R+5,g.length);T++){let A=g[T].trim();if(A===`throw ${L}`||A===`throw ${L};`){let O=!1;for(let _=R+1;_<T;_++){let D=g[_].trim();if(D!==""&&D!=="{"&&!D.startsWith("//")){O=!0;break}}if(!O)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("catch")+1),ruleId:"eslint/no-useless-catch",message:"Unnecessary catch clause",severity:"error"});break}if(A==="}")break}}return m}};var is={meta:{docs:"Require isNaN() when checking for NaN",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b([\w.\[\]]+)\s*(===|!==|==|!=)\s*NaN\b|\bNaN\s*(===|!==|==|!=)\s*([\w.\[\]]+)/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[1]||L[4];m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/use-isnan",message:"Use isNaN() to compare with NaN",severity:"error"})}}return m},fix:(s,h)=>{let m=s.split(/\r?\n/),g=!1,R=m.map((I)=>{let S=I;return S=S.replace(/\b([\w.\[\]]+)\s*===\s*NaN\b/g,(L,T)=>(g=!0,`isNaN(${T})`)),S=S.replace(/\bNaN\s*===\s*([\w.\[\]]+)\b/g,(L,T)=>(g=!0,`isNaN(${T})`)),S=S.replace(/\b([\w.\[\]]+)\s*!==\s*NaN\b/g,(L,T)=>(g=!0,`!isNaN(${T})`)),S=S.replace(/\bNaN\s*!==\s*([\w.\[\]]+)\b/g,(L,T)=>(g=!0,`!isNaN(${T})`)),S=S.replace(/\b([\w.\[\]]+)\s*==\s*NaN\b/g,(L,T)=>(g=!0,`isNaN(${T})`)),S=S.replace(/\bNaN\s*==\s*([\w.\[\]]+)\b/g,(L,T)=>(g=!0,`isNaN(${T})`)),S=S.replace(/\b([\w.\[\]]+)\s*!=\s*NaN\b/g,(L,T)=>(g=!0,`!isNaN(${T})`)),S=S.replace(/\bNaN\s*!=\s*([\w.\[\]]+)\b/g,(L,T)=>(g=!0,`!isNaN(${T})`)),S});return g?R.join(`
|
|
53
|
+
`):s}};var jo=["undefined","object","boolean","number","string","function","symbol","bigint"],rs={meta:{docs:"Enforce comparing typeof expressions against valid strings",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/typeof\s+\w+\s*(?:===|!==|==|!=)\s*(['"`])(\w+)\1/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let A=L[2];if(!jo.includes(A))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/valid-typeof",message:`Invalid typeof comparison value '${A}'`,severity:"error"})}let T=/(['"`])(\w+)\1\s*(?:===|!==|==|!=)\s*typeof\s+\w+/g;for(L=T.exec(I);L!==null;L=T.exec(I)){let A=L[2];if(!jo.includes(A))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/valid-typeof",message:`Invalid typeof comparison value '${A}'`,severity:"error"})}}return m}};var os={meta:{docs:"Enforce a maximum cyclomatic complexity allowed in a program",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=10,I=!1,S=0,L="",T=0,A=0;for(let O=0;O<g.length;O++){let _=g[O],D=_.match(/\bfunction\s+(\w+)\s*\(|(\w+)\s*=\s*(?:\([^)]*\)|(\w+))\s*=>/);if(D)I=!0,S=O+1,L=D[1]||D[2]||D[3]||"anonymous",T=1,A=0;if(I){for(let N of _){if(N==="{")A++;if(N==="}"){if(A--,A===0){if(T>10)m.push({filePath:h.filePath,line:S,column:1,ruleId:"eslint/complexity",message:`Function '${L}' has complexity ${T}, exceeds maximum of 10`,severity:"error"});I=!1}}}let F=[/\bif\s*\(/,/\belse\s+if\s*\(/,/\bfor\s*\(/,/\bwhile\s*\(/,/\bcase\s+/,/\bcatch\s*\(/,/\b&&\b/,/\b\|\|\b/,/\?\s*(?:\S.*(?:[\n\r\u2028\u2029]\s*)?)?:/];for(let N of F){let W=_.match(new RegExp(N,"g"));if(W)T+=W.length}}}return m}};var ls={meta:{docs:"Require default case in switch statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=0,S=!1,L=0;for(let T=0;T<g.length;T++){let A=g[T];if(A.match(/\bswitch\s*\(/))R=!0,I=T+1,S=!1,L=0;if(R){for(let O of A){if(O==="{")L++;if(O==="}"){if(L--,L===0){if(!S)m.push({filePath:h.filePath,line:I,column:1,ruleId:"eslint/default-case",message:"Expected a default case",severity:"error"});R=!1}}}if(A.match(/\bdefault\s*:/))S=!0}}return m}};var as={meta:{docs:"Require === and !== instead of == and !=",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/([^=!])(\s*)(==)(\s*)([^=])/g,L=/([^!])(\s*)(!=)(\s*)([^=])/g,T;for(T=S.exec(I);T!==null;T=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+2),ruleId:"eslint/eqeqeq",message:"Expected '===' and instead saw '=='",severity:"error"});for(T=L.exec(I);T!==null;T=L.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+2),ruleId:"eslint/eqeqeq",message:"Expected '!==' and instead saw '!='",severity:"error"})}return m},fix:(s)=>{let h=s;return h=h.replace(/([^!])(\s*)(!=)(\s*)([^=])/g,"$1$2!==$4$5"),h=h.replace(/([^=!])(\s*)(==)(\s*)([^=])/g,"$1$2===$4$5"),h}};var cs={meta:{docs:"Enforce a maximum depth that blocks can be nested",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=4,I=0,S=0,L=0;for(let T=0;T<g.length;T++){let A=g[T];if(A.match(/\b(if|for|while|switch|try|catch|else)\b.*\{/)){if(I++,I>S)S=I,L=T+1}else if(A.match(/\{/)&&!A.match(/^.*\}/)){if(g[T-1]?.match(/\b(if|for|while|switch|try|catch|else)\b/)){if(I++,I>S)S=I,L=T+1}}if(A.match(/^\s*\}/))I--;if(I>4)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"eslint/max-depth",message:`Blocks are nested too deeply (${I}), maximum allowed is 4`,severity:"error"})}return m}};var us={meta:{docs:"Enforce a maximum number of lines of code in a function",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=50,I=!1,S=0,L="",T=0;for(let A=0;A<g.length;A++){let O=g[A],_=O.match(/\bfunction\s+(\w+)\s*\(|(\w+)\s*=\s*(?:\([^)]*\)|(\w+))\s*=>/);if(_)I=!0,S=A+1,L=_[1]||_[2]||_[3]||"anonymous",T=0;if(I)for(let D of O){if(D==="{")T++;if(D==="}"){if(T--,T===0){let F=A+1-S+1;if(F>50)m.push({filePath:h.filePath,line:S,column:1,ruleId:"eslint/max-lines-per-function",message:`Function '${L}' has ${F} lines, exceeds maximum of 50`,severity:"error"});I=!1}}}}return m}};var fs={meta:{docs:"Disallow alert, confirm, and prompt",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b(alert|confirm|prompt)\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-alert",message:`Unexpected ${L[1]}`,severity:"warning"})}}return m}};var ms={meta:{docs:"Disallow await inside of loops",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=0,S=0;for(let L=0;L<g.length;L++){let T=g[L];if(T.match(/\b(for|while|do)\s*\(/))R=!0,I=0,S=L;if(R){for(let A of T){if(A==="{")I++;if(A==="}"){if(I--,I===0)R=!1}}if(T.match(/\bawait\s+/))m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"eslint/no-await-in-loop",message:"Unexpected await inside a loop. Consider using Promise.all() instead",severity:"error"})}}return m}};var hs={meta:{docs:"Disallow use of arguments.caller or arguments.callee",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\barguments\s*\.\s*(caller|callee)\b/g,L;for(L=S.exec(I);L!==null;L=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"eslint/no-caller",message:`Avoid arguments.${L[1]}`,severity:"error"})}return m}};var ds={meta:{docs:"Disallow lexical declarations in case clauses",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=!1;for(let S=0;S<g.length;S++){let L=g[S];if(L.match(/\bcase\s+(?:\S.*)?:|default\s*:/))R=!0,I=!0;else I=!1;if(R&&!I&&(L.match(/\bbreak\b/)||L.match(/\bcase\s+(?:\S.*)?:/)))R=!1;if(R&&!I){if(L.match(/\b(let|const|function|class)\s+/))m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"eslint/no-case-declarations",message:"Unexpected lexical declaration in case block",severity:"error"})}}return m}};var ps={meta:{docs:"Disallow else blocks after return statements in if statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(!/^\s*else\b/.test(I))continue;let S=!1;for(let L=R-1;L>=0&&L>=R-10;L--){let T=g[L].trim();if(T.startsWith("return"))S=!0;if(T==="}"&&S)break;if(T.includes("{"))break}if(S)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("else")+1),ruleId:"eslint/no-else-return",message:"Unnecessary else after return",severity:"warning"})}return m}};var gs={meta:{docs:"Disallow empty block statements",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\{\s*\}/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=I.substring(0,L.index).trim(),A=/(?:if|else|for|while|do|try|catch|finally|function|\})\s*$/.test(T),O=/[=:]$/.test(T)||/return\s*$/.test(T);if(A&&!O)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-empty",message:"Empty block statement",severity:"error"})}}for(let R=0;R<g.length-1;R++){let I=g[R],S=g[R+1];if(/\{\s*$/.test(I.trim()))for(let L=R+1;L<g.length;L++){let T=g[L].trim();if(T==="")continue;if(T==="}"||T.startsWith("}")){let A=I.substring(0,I.lastIndexOf("{")).trim(),O=/(?:if|else|for|while|do|try|catch|finally|function|\})\s*$/.test(A),_=/[=:]$/.test(A)||/return\s*$/.test(A);if(O&&!_)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.lastIndexOf("{")+1),ruleId:"eslint/no-empty",message:"Empty block statement",severity:"error"})}break}}return m}};var ys={meta:{docs:"Disallow empty functions",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[/function\s+\w+\s*\([^)]*\)\s*\{\s*\}/g,/function\s*\([^)]*\)\s*\{\s*\}/g,/\([^)]*\)\s*=>\s*\{\s*\}/g,/\w+\s*\([^)]*\)\s*\{\s*\}/g];for(let L of S){let T;for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-empty-function",message:"Unexpected empty function",severity:"warning"})}}}return m}};var bs={meta:{docs:"Disallow use of eval()",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\beval\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-eval",message:"eval can be harmful",severity:"error"})}}return m}};var wd=["Object","Array","String","Number","Boolean","Date","RegExp","Function","Math","JSON","Promise","Map","Set","WeakMap","WeakSet","Symbol","Proxy","Reflect","Error","TypeError","RangeError"],xs={meta:{docs:"Disallow extending native types",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];for(let S of wd){let L=new RegExp(`\\b${S}\\.prototype\\.\\w+\\s*=`,"g"),T;for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-extend-native",message:`${S} prototype is read only, properties should not be added`,severity:"error"})}}}return m}};var ws={meta:{docs:"Disallow unnecessary boolean casts",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[/\bif\s*\(\s*Boolean\s*\(/g,/\bwhile\s*\(\s*Boolean\s*\(/g,/!\s*Boolean\s*\(/g,/\?\s*Boolean\s*\(/g,/&&\s*Boolean\s*\(/g,/\|\|\s*Boolean\s*\(/g,/!!\s*\w+/g];for(let L of S){let T;for(T=L.exec(I);T!==null;T=L.exec(I)){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-extra-boolean-cast",message:"Redundant Boolean call or double negation",severity:"error"})}}}return m},fix:(s)=>{let h=s;return h=h.replace(/\b(if|while)\s*\(\s*Boolean\s*\(([^)]+)\)\s*\)/g,"$1 ($2)"),h=h.replace(/!\s*Boolean\s*\(([^)]+)\)/g,"!$1"),h=h.replace(/!!\s*(\w+)/g,"$1"),h}};var Rd=["Array","Boolean","Date","Error","Function","JSON","Math","Number","Object","RegExp","String","Symbol","undefined","NaN","Infinity","isNaN","isFinite","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","eval","Promise","Proxy","Reflect","Set","Map","WeakSet","WeakMap","ArrayBuffer","DataView","console","window","document","globalThis","global","process"],Rs={meta:{docs:"Disallow assignment to native objects or read-only global variables",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];for(let S of Rd){let L=new RegExp(`\\b${S}\\s*=\\s*[^=]`,"g"),T;for(T=L.exec(I);T!==null;T=L.exec(I))if(!I.slice(T.index).match(new RegExp(`^${S}\\s*===?`)))m.push({filePath:h.filePath,line:R+1,column:T.index+1,ruleId:"eslint/no-global-assign",message:`Read-only global '${S}' should not be modified`,severity:"error"})}}return m}};var ks={meta:{docs:"Disallow implied eval() via setTimeout/setInterval with strings",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b(setTimeout|setInterval)\s*\(\s*(['"`])/g,L;while((L=S.exec(I))!==null){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-implied-eval",message:"Implied eval. Consider passing a function instead of a string",severity:"error"})}}return m}};var $s={meta:{docs:"Disallow the use of the __iterator__ property",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/__iterator__/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-iterator",message:"Reserved name '__iterator__'",severity:"error"})}}return m}};var Xt={meta:{docs:"Disallow if statements as the only statement in else blocks",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(/^\s*else\s*(?:\{\s*)?$/.test(I)){let L=R,T=I.includes("{");if(!T){if(R+1<g.length&&g[R+1].trim()==="{")L=R+1,T=!0}if(T)for(let A=L+1;A<g.length;A++){let O=g[A].trim();if(O===""||O.startsWith("//")||O.startsWith("/*"))continue;if(O==="}")break;if(O.startsWith("if ")||O.startsWith("if(")){let _=!0,D=0,F=!1;for(let N=A;N<g.length;N++){let W=g[N];if(D+=(W.match(/\{/g)||[]).length,D-=(W.match(/\}/g)||[]).length,N===A){F=!0;continue}if(D===0){for(let B=N+1;B<g.length;B++){let j=g[B].trim();if(j===""||j.startsWith("//"))continue;if(j==="}"||j.startsWith("}"))break;else _=!1;break}break}}if(F&&_)m.push({filePath:h.filePath,line:A+1,column:Math.max(1,g[A].indexOf("if")+1),ruleId:"eslint/no-lonely-if",message:"Unexpected if as the only statement in an else block",severity:"warning"})}break}}}return m},fix:(s,h)=>{if(Xt.check(s,h).length===0)return s;return s}};var Ps={meta:{docs:"Disallow new operators outside of assignments or comparisons",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(/^\s*new\s+\w+\s*\(/.test(I)){if(!/[=:]/.test(I.substring(0,I.indexOf("new"))))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("new")+1),ruleId:"eslint/no-new",message:"Do not use 'new' for side effects",severity:"warning"})}}return m}};var vs={meta:{docs:"Disallow new Function() declarations",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\bnew\s+Function\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-new-func",message:"The Function constructor is eval",severity:"error"})}}return m}};var Is={meta:{docs:"Disallow new operators with String, Number, and Boolean",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\bnew\s+(String|Number|Boolean)\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-new-wrappers",message:`Do not use ${L[1]} as a constructor`,severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=!1,g=h.map((R)=>{if(R.trim().startsWith("//")||R.trim().startsWith("/*"))return R;return R.replace(/\bnew\s+(String|Number|Boolean)\s*\(/g,(S,L)=>(m=!0,`${L}(`))});return m?g.join(`
|
|
54
|
+
`):s}};var Ms={meta:{docs:"Disallow octal literals",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\b0[0-7]+\b/g,L;for(L=S.exec(I);L!==null;L=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"eslint/no-octal",message:"Octal literals should not be used",severity:"error"})}return m}};var Cs={meta:{docs:"Disallow reassignment of function parameters",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=new Map;for(let I=0;I<g.length;I++){let S=g[I],L=[...S.matchAll(/function\s+(?:(\w+)\s*)?\(([^)]*)\)/g),...S.matchAll(/(?:const|let|var)?\s*(\w+)\s*=\s*\(([^)]*)\)\s*=>/g),...S.matchAll(/(?:const|let|var)?\s*(\w+)\s*=\s*(\w+)\s*=>/g)];for(let T of L){let A=T[2]?T[2].split(",").map((_)=>_.trim().split(/[=:]/)[0].trim()):[],O=`line-${I}`;if(A.length>0)R.set(O,new Set(A.filter((_)=>_&&/^\w+$/.test(_))))}for(let[T,A]of R.entries())for(let O of A){let _=new RegExp(`\\b${O}\\s*=\\s*[^=]`,"g"),D;for(D=_.exec(S);D!==null;D=_.exec(S))if(!S.slice(D.index).match(/^\w+\s*===?/))m.push({filePath:h.filePath,line:I+1,column:D.index+1,ruleId:"eslint/no-param-reassign",message:`Assignment to function parameter '${O}'`,severity:"error"})}}return m}};var Ss={meta:{docs:"Disallow use of __proto__",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/__proto__/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-proto",message:"The '__proto__' property is deprecated",severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=!1,g=h.map((R)=>{if(R.trim().startsWith("//")||R.trim().startsWith("/*"))return R;return R.replace(/(\w+)\.__proto__/g,(S,L)=>(m=!0,`Object.getPrototypeOf(${L})`))});return m?g.join(`
|
|
55
|
+
`):s}};var Es={meta:{docs:"Disallow assignment operators in return statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\breturn\s[^;]*\b\w+\s*=\s*(?!=)/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[0];if(/===|==/.test(T))continue;if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-return-assign",message:"Return statement should not contain assignment",severity:"error"})}}return m}};var Ls={meta:{docs:"Disallow comma operators",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\)\s*,\s*\w+\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+L[0].indexOf(",")+1),ruleId:"eslint/no-sequences",message:"Unexpected use of comma operator",severity:"warning"})}}return m}};var Ts={meta:{docs:"Disallow variable declarations from shadowing variables declared in the outer scope",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=[new Set];for(let S=0;S<g.length;S++){let L=g[S];if(L.match(/\bfunction\s+\w+\s*\(|=>\s*\{|\{\s*$/))I.push(new Set);let T=[...L.matchAll(/\b(const|let|var)\s+(\w+)/g),...L.matchAll(/function\s+(\w+)\s*\(/g)];for(let A of T){let O=A[2]||A[1];for(let _=0;_<I.length-1;_++)if(I[_].has(O)){m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"eslint/no-shadow",message:`'${O}' is already declared in the upper scope`,severity:"error"});break}I[I.length-1].add(O)}if(L.match(/^\s*\}\s*$/)){if(I.length>1)I.pop()}}return m}};var As={meta:{docs:"Disallow throwing literals as exceptions",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[{pattern:/\bthrow\s+(['"`][^'"`]*['"`])/g,type:"string"},{pattern:/\bthrow\s+(\d+)/g,type:"number"},{pattern:/\bthrow\s+(true|false|null|undefined)/g,type:"literal"}];for(let{pattern:L,type:T}of S){let A;while((A=L.exec(I))!==null){if(I.substring(0,A.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,A.index+1),ruleId:"eslint/no-throw-literal",message:`Expected an error object to be thrown, got ${T} literal`,severity:"error"})}}}return m}};var kd=new Set(["return","typeof","instanceof","in","of","new","delete","void","case","do","else","yield","await","throw"]),qi=/[\w$\u00A0-\uFFFF]/;function Dt(s){return s===`
|
|
56
|
+
`||s==="\r"||s==="\u2028"||s==="\u2029"}function $d(s,h){let m=h+1,g=!1;while(m<s.length){let R=s[m];if(Dt(R))return-1;if(R==="\\"){if(Dt(s[m+1]))return-1;m+=2;continue}if(g){if(R==="]")g=!1}else if(R==="[")g=!0;else if(R==="/"){m+=1;while(m<s.length&&qi.test(s[m]))m+=1;return m}m+=1}return-1}function Qt(s){let h=[],m=[],g=s.length,R=[],I=-1,S="operator",L=0;if(s.startsWith("#!")){let O=2;while(O<g&&!Dt(s[O]))O+=1;h.push({kind:"comment",start:2,end:O}),L=O}let T=(O)=>{if(R.length===0)I=O;R.push(-1)},A=()=>{let O=L;while(L<g){let _=s[L];if(_==="\\"){L+=2;continue}if(_==="`"){if(h.push({kind:"template",start:O,end:L}),R.pop(),R.length===0)m.push([I,L]);L+=1,S="value";return}if(_==="$"&&s[L+1]==="{"){h.push({kind:"template",start:O,end:L}),R.push(0),L+=2,S="operator";return}L+=1}L=Math.min(L,g),h.push({kind:"template",start:O,end:L}),R.length=0,m.push([I,g])};while(L<g){if(R.length>0&&R[R.length-1]===-1){A();continue}let O=s[L],_=s[L+1];if(O==="/"&&_==="/"){let D=L+2;while(D<g&&!Dt(s[D]))D+=1;h.push({kind:"comment",start:L+2,end:D}),L=D;continue}if(O==="/"&&_==="*"){let D=s.indexOf("*/",L+2),F=D<0?g:D;h.push({kind:"comment",start:L+2,end:F}),L=D<0?g:D+2;continue}if(O==="'"||O==='"'){let D=L+1,F=D;while(F<g){let N=s[F];if(N==="\\"){F+=s[F+1]==="\r"&&s[F+2]===`
|
|
57
|
+
`?3:2;continue}if(N===O||Dt(N))break;F+=1}F=Math.min(F,g),h.push({kind:"string",start:D,end:F}),L=s[F]===O?F+1:F,S="value";continue}if(O==="`"){T(L),L+=1;continue}if(O==="/"){let D=S==="operator"?$d(s,L):-1;if(D>0){let F=D;while(F>L&&s[F-1]!=="/")F-=1;h.push({kind:"regex",start:L+1,end:F-1}),L=D,S="value";continue}L+=1,S="operator";continue}if(R.length>0){if(O==="{"){R[R.length-1]+=1,L+=1,S="operator";continue}if(O==="}"){let D=R[R.length-1];if(D>0)R[R.length-1]=D-1,S="operator";else R.pop();L+=1;continue}}if(qi.test(O)){let D=L+1;while(D<g&&qi.test(s[D]))D+=1;let F=s.slice(L,D);S=kd.has(F)?"operator":"value",L=D;continue}if(O===")"||O==="]")S="value";else if(!/\s/.test(O))S="operator";L+=1}return{regions:h,templates:m}}function Os(s,h={comments:!0},m=Qt(s)){let g=new Set;if(h.comments)g.add("comment");if(h.strings)g.add("string");if(h.templates)g.add("template");if(h.regex)g.add("regex");if(g.size===0)return s;let R=s.split("");for(let I of m.regions){if(!g.has(I.kind))continue;for(let S=I.start;S<I.end&&S<R.length;S+=1)if(!Dt(R[S]))R[S]=" "}return R.join("")}function Uo(s){return Os(s,{comments:!0})}function _s(s){return Os(s,{comments:!0,strings:!0,templates:!0,regex:!0})}function Ds(s,h=Qt(s)){let m=[0];for(let S=0;S<s.length;S+=1)if(s[S]===`
|
|
58
|
+
`)m.push(S+1);let g=Array.from({length:m.length},()=>!1),R=h.regions.filter((S)=>S.kind==="template"),I=0;for(let S=0;S<m.length;S+=1){let L=m[S];while(I<R.length&&R[I].end<L)I+=1;let T=R[I];g[S]=T!==void 0&&T.start<=L&&L<=T.end&&L>0}return g}var Fs={meta:{docs:"Disallow the use of variables before they are defined",recommended:!1},check:(s,h)=>{let m=[],g=_s(s).split(/\r?\n/),R=new Map;for(let I=0;I<g.length;I++){let S=g[I],L=[...S.matchAll(/\b(const|let|var)\s+(\w+)/g),...S.matchAll(/\bfunction\s+(\w+)\s*\(/g),...S.matchAll(/\bclass\s+(\w+)/g)];for(let T of L){let A=T[2]||T[1];if(!R.has(A))R.set(A,I+1)}}for(let I=0;I<g.length;I++){let S=g[I];if(S.match(/\b(const|let|var|function|class)\s+\w+/))continue;let L=S.matchAll(/\b(\w+)\b/g);for(let T of L){let A=T[1],O=R.get(A);if(O&&O>I+1)m.push({filePath:h.filePath,line:I+1,column:T.index+1,ruleId:"eslint/no-use-before-define",message:`'${A}' was used before it was defined`,severity:"error"})}}return m}};var Ns={meta:{docs:"Disallow unnecessary .call() and .apply()",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\.\s*call\s*\(\s*(undefined|null)\s*,/g,L=/\.\s*apply\s*\(\s*(undefined|null)\s*,/g,T;for(T=S.exec(I);T!==null;T=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:T.index+1,ruleId:"eslint/no-useless-call",message:"Unnecessary '.call()'",severity:"error"});for(T=L.exec(I);T!==null;T=L.exec(I))m.push({filePath:h.filePath,line:R+1,column:T.index+1,ruleId:"eslint/no-useless-call",message:"Unnecessary '.apply()'",severity:"error"})}return m}};var Ws={meta:{docs:"Disallow unnecessary concatenation of literals or template literals",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=[/(['"`])([^'"`]*)\1\s*\+\s*\1([^'"`]*)\1/g];for(let L of S){let T;while((T=L.exec(I))!==null){if(I.substring(0,T.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,T.index+1),ruleId:"eslint/no-useless-concat",message:"Unexpected string concatenation of literals",severity:"warning"})}}}return m},fix:(s)=>{let h=s;return h=h.replace(/(['"`])([^'"`]*)\1\s*\+\s*\1([^'"`]*)\1/g,"$1$2$3$1"),h}};var zo=["/","(",")","[","]","{","}","<",">",":","@","#","$","%","&","=","+","-","*","?","!",";",",","|","~","`","^"],Bs={meta:{docs:"Disallow unnecessary escape characters",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];for(let S of zo){let L=`\\${S}`,T=new RegExp(`(['"\`])[^'"\`]*${L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`,"g"),A;while((A=T.exec(I))!==null){let O=A.index,_=I.indexOf(L,O);if(_>O)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,_+1),ruleId:"eslint/no-useless-escape",message:`Unnecessary escape character: \\${S}`,severity:"warning"})}}}return m},fix:(s)=>{let h=s;for(let m of zo){let g=`\\${m}`;h=h.replace(new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),m)}return h}};var js={meta:{docs:"Disallow renaming import, export, and destructured assignments to the same name",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/import\s*\{[^}]*\b(\w+)\s+as\s+\1\b[^}]*\}/g,L;for(L=S.exec(I);L!==null;L=S.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-useless-rename",message:`Renaming import '${L[1]}' to '${L[1]}' is redundant`,severity:"error"});let T=/export\s*\{[^}]*\b(\w+)\s+as\s+\1\b[^}]*\}/g;for(L=T.exec(I);L!==null;L=T.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-useless-rename",message:`Renaming export '${L[1]}' to '${L[1]}' is redundant`,severity:"error"});let A=/\{[^}]*\b(\w+)\s*:\s*\1\b[^}]*\}\s*=/g;for(L=A.exec(I);L!==null;L=A.exec(I))m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-useless-rename",message:`Renaming destructured property '${L[1]}' to '${L[1]}' is redundant`,severity:"error"})}return m},fix:(s)=>{let h=s;return h=h.replace(/\b(\w+)\s+as\s+\1\b/g,"$1"),h=h.replace(/\{([^}]*)\b(\w+)\s*:\s*\2\b([^}]*)\}/g,"{$1$2$3}"),h}};var en={meta:{docs:"Disallow redundant return statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(S==="return"||S==="return;"){let L=!1;for(let T=R+1;T<g.length;T++){let A=g[T].trim();if(A===""||A.startsWith("//")||A.startsWith("/*"))continue;if(A==="}"||A.startsWith("}"))L=!0;break}if(L)m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("return")+1),ruleId:"eslint/no-useless-return",message:"Unnecessary return statement",severity:"warning"})}}return m},fix:(s,h)=>{let m=en.check(s,h);if(m.length===0)return s;let g=s.split(/\r?\n/),R=new Set(m.map((S)=>S.line-1));return g.filter((S,L)=>!R.has(L)).join(`
|
|
59
|
+
`)}};var Us={meta:{docs:"Require let or const instead of var",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\bvar\s+/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-var",message:"Unexpected var, use let or const instead",severity:"error"})}}return m},fix:(s,h)=>s.split(/\r?\n/).map((R)=>{if(R.trim().startsWith("//")||R.trim().startsWith("/*"))return R;return R.replace(/\bvar\s+/g,"let ")}).join(`
|
|
60
|
+
`)};var zs={meta:{docs:"Disallow with statements",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\bwith\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/no-with",message:"Unexpected use of 'with' statement",severity:"error"})}}return m}};var qs={meta:{docs:"Require using arrow functions for callbacks",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=/\.(map|filter|reduce|forEach|some|every|find|findIndex)\s*\(\s*function\s*\(/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){if(I.substring(0,L.index).includes("//"))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,L.index+1),ruleId:"eslint/prefer-arrow-callback",message:"Unexpected function expression, use arrow function instead",severity:"warning"})}}return m}};var Ks={meta:{docs:"Disallow async functions which have no await expression",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++)if(g[R].match(/\basync\s+(?:function\s+\w+|(?:\(|\w+)\s*(?:\(|=>))/)){let L=!1,T=0,A=!1,O=R;while(O<g.length){let _=g[O];for(let D of _){if(D==="{")T++,A=!0;if(D==="}"){if(T--,T===0&&A)break}}if(_.match(/\bawait\s+/))L=!0;if(T===0&&A){if(!L)m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"eslint/require-await",message:"Async function has no await expression",severity:"error"});break}O++}}return m}};var qo=/\.(?:ts|js|tsx|jsx|mts|mjs|cts|cjs)$/;function U(s){return{meta:s.meta,check:(h,m)=>{if(!qo.test(m.filePath))return[];return s.check(h,m)},fix:s.fix?(h,m)=>{if(!qo.test(m.filePath))return h;return s.fix(h,m)}:void 0}}var Ko=/\.(?:sh|bash|zsh|ksh|dash)$/,Vo=/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/;function De(s){return{meta:s.meta,check:(h,m)=>{if(!Ko.test(m.filePath)&&!Vo.test(h))return[];return s.check(h,m)},fix:s.fix?(h,m)=>{if(!Ko.test(m.filePath)&&!Vo.test(h))return h;return s.fix(h,m)}:void 0}}var Ho=/(?:^|[/\\])package\.json$/;function Ne(s){return{meta:s.meta,check:(h,m)=>{if(!Ho.test(m.filePath))return[];return s.check(h,m)},fix:s.fix?(h,m)=>{if(!Ho.test(m.filePath))return h;return s.fix(h,m)}:void 0}}var Zo={name:"eslint",rules:{"array-callback-return":U(Dn),"constructor-super":U(Fn),"for-direction":U(Nn),"getter-return":U(Wn),"no-async-promise-executor":U(Bn),"no-compare-neg-zero":U(jn),"no-cond-assign":U(Un),"no-constant-condition":U(qn),"no-const-assign":U(zn),"no-dupe-class-members":U(Kn),"no-dupe-keys":U(Jt),"no-duplicate-case":U(Vn),"no-empty-pattern":U(Hn),"no-fallthrough":U(Zn),"no-loss-of-precision":U(Gn),"no-promise-executor-return":U(Jn),"no-redeclare":U(Yn),"no-self-assign":U(Yt),"no-self-compare":U(Xn),"no-sparse-arrays":U(Qn),"no-undef":U(es),"no-unsafe-negation":U(ns),"no-unreachable":U(ts),"no-useless-catch":U(ss),"use-isnan":U(is),"valid-typeof":U(rs),"default-case":U(ls),eqeqeq:U(as),"no-alert":U(fs),"no-await-in-loop":U(ms),"no-caller":U(hs),"no-case-declarations":U(ds),"no-else-return":U(ps),"no-empty":U(gs),"no-empty-function":U(ys),"no-eval":U(bs),"no-extend-native":U(xs),"no-global-assign":U(Rs),"no-implied-eval":U(ks),"no-iterator":U($s),"no-new":U(Ps),"no-new-func":U(vs),"no-new-wrappers":U(Is),"no-octal":U(Ms),"no-param-reassign":U(Cs),"no-proto":U(Ss),"no-return-assign":U(Es),"no-shadow":U(Ts),"no-throw-literal":U(As),"no-use-before-define":U(Fs),"no-useless-call":U(Ns),"no-with":U(zs),"require-await":U(Ks),complexity:U(os),"max-depth":U(cs),"max-lines-per-function":U(us),"no-extra-boolean-cast":U(ws),"no-lonely-if":U(Xt),"no-sequences":U(Ls),"no-useless-concat":U(Ws),"no-useless-escape":U(Bs),"no-useless-rename":U(js),"no-useless-return":U(en),"no-var":U(Us),"prefer-arrow-callback":U(qs)}};var Go={meta:{docs:"Disallow return statements in constructors - constructors automatically return the instance"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.indexOf("//");if(!(S>=0?I.slice(0,S):I).match(/\bconstructor\s*\(/))continue;let A=0,O=!1,_=-1;for(let D=R;D<g.length;D++){let F=g[D],N=null,W=!1;for(let B=0;B<F.length;B++){let j=F[B];if(W){W=!1;continue}if(j==="\\"&&N){W=!0;continue}if(!N){if(j==="'")N="single";else if(j==='"')N="double";else if(j==="`")N="template";else if(j==="{")A++,O=!0;else if(j==="}"){if(A--,O&&A===0){_=D;break}}}else if(N==="single"&&j==="'"||N==="double"&&j==='"'||N==="template"&&j==="`")N=null}if(_!==-1)break}if(_===-1)continue;for(let D=R;D<=_;D++){let F=g[D];if(D===R)continue;if(/^\s*\/\//.test(F))continue;let N=F.indexOf("//"),W=N>=0?F.slice(0,N):F;if(W=W.replace(/(['"`])(?:(?!\1)[^\\]|\\.)*?\1/g,'""'),W.match(/\breturn\b/)){let j=W.indexOf("return"),z=j>0?W[j-1]:" ",K=j+6<W.length?W[j+6]:" ";if(/\w/.test(z)||/\w/.test(K))continue;let V=W.slice(j+6).trim();if(V.startsWith("this;")||V==="this")continue;if(V===";"||V==="")continue;let G=F.indexOf("return");m.push({filePath:h.filePath,line:D+1,column:G+1||1,ruleId:"no-constructor-return",message:"Unexpected return statement in constructor. Constructors should not return values.",severity:"error",help:"Remove the return statement or move the logic outside of the constructor"})}}}return m}};var Jo={meta:{docs:"Disallow irregular whitespace characters that may cause issues in code"},check:(s,h)=>{let m=[],g=/[\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/g,R=s.split(/\r?\n/);for(let I=0;I<R.length;I++){let S=R[I],L;g.lastIndex=0;while((L=g.exec(S))!==null){let A=L[0].charCodeAt(0),O="irregular whitespace",_={160:"NO-BREAK SPACE",5760:"OGHAM SPACE MARK",6158:"MONGOLIAN VOWEL SEPARATOR",8192:"EN QUAD",8193:"EM QUAD",8194:"EN SPACE",8195:"EM SPACE",8196:"THREE-PER-EM SPACE",8197:"FOUR-PER-EM SPACE",8198:"SIX-PER-EM SPACE",8199:"FIGURE SPACE",8200:"PUNCTUATION SPACE",8201:"THIN SPACE",8202:"HAIR SPACE",8232:"LINE SEPARATOR",8233:"PARAGRAPH SEPARATOR",8239:"NARROW NO-BREAK SPACE",8287:"MEDIUM MATHEMATICAL SPACE",12288:"IDEOGRAPHIC SPACE",65279:"ZERO WIDTH NO-BREAK SPACE"};if(_[A])O=_[A];m.push({filePath:h.filePath,line:I+1,column:L.index+1,ruleId:"no-irregular-whitespace",message:`Irregular whitespace detected: ${O} (U+${A.toString(16).toUpperCase().padStart(4,"0")})`,severity:"error",help:"Replace irregular whitespace with regular spaces or tabs"})}}return m},fix:(s)=>s.replace(/[\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/g," ")};var Yo={meta:{docs:"Disallow new operators outside of assignments or comparisons",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(S.startsWith("//")||S.startsWith("/*")||S.startsWith("*"))continue;if(/^\s*new\s+\w+/.test(I)){let T=/^\s*(?:const|let|var|this\.\w+)\s*=\s*new\s+/,A=/^\s*return\s+new\s+/,O=new RegExp("^\\s*new\\s+\\w[^;]*,"),_=/[=:,(]\s*new\s+/;if(!T.test(I)&&!A.test(I)&&!O.test(I)&&!_.test(S)){let D=I.search(/new\s+/)+1;m.push({filePath:h.filePath,line:R+1,column:D,ruleId:"no-new",message:"Do not use 'new' for side effects",severity:"error",help:"Either assign the result to a variable or remove the 'new' operator if the side effect is intentional."})}}}return m}};var Xo={meta:{docs:"Disallow multiple spaces in regular expressions",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(/^\s*\/\//.test(I))continue;let S=/\/(?![*/])((?:\\.|[^/\\])+)\/[gimsuvy]*/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let A=L[1];if(/ {2,}/.test(A)){let O=L.index+1;m.push({filePath:h.filePath,line:R+1,column:O,ruleId:"no-regex-spaces",message:"Multiple spaces in regular expression",severity:"error",help:"Use quantifiers like {2} instead of multiple spaces for clarity."})}}let T=/new\s+RegExp\s*\(\s*['"`]([^'"`]+)['"`]/g;for(L=T.exec(I);L!==null;L=T.exec(I)){let A=L[1];if(/ {2,}/.test(A)){let O=L.index+1;m.push({filePath:h.filePath,line:R+1,column:O,ruleId:"no-regex-spaces",message:"Multiple spaces in regular expression",severity:"error",help:"Use quantifiers like {2} instead of multiple spaces for clarity."})}}}return m}};var Qo=new Set(["|","&",":",",","<"]);function el(s){return Uo(s)}function Vs(s,h){if(s[h+1]==="/"||s[h+1]==="*")return!1;let m=s.slice(0,h).trimEnd();return!m||/[=([{,:;!&|?]$/.test(m)||m.endsWith("=>")||m.endsWith("return")}var gt={meta:{docs:"Report variables and parameters that are declared/assigned but never used"},check:(s,h)=>{if(h.filePath.endsWith("/no-unused-vars.ts"))return[];if(h.filePath.endsWith(".d.ts"))return[];let m=[],g=h.options||{},R=typeof g.varsIgnorePattern==="string"?g.varsIgnorePattern:"^_",I=typeof g.argsIgnorePattern==="string"?g.argsIgnorePattern:"^_",S=new RegExp(R,"u"),L=new RegExp(I,"u"),T=Qt(s),A=Os(s,{comments:!0},T),O=A.split(/\r?\n/),_=A,D=Ds(s,T),F=new RegExp("^\\s*(?:const|let|var)\\s+(.+?);?\\s*$");for(let J=0;J<O.length;J++){if(D[J])continue;let Y=O[J],se=Y.match(F);if(!se)continue;let Z=se[1],re=[],ee="",oe=0,X=0,te=null,le=!1;for(let ne=0;ne<Z.length;ne++){let q=Z[ne];if(le){le=!1,ee+=q;continue}if(q==="\\"&&te){le=!0,ee+=q;continue}if(!te){if(q==="/"&&Z[ne+1]==="/")break;if(q==="/"&&Z[ne+1]==="*"){ne+=2;while(ne<Z.length&&!(Z[ne]==="*"&&Z[ne+1]==="/"))ne++;ne++;continue}if(q==="'")te="single";else if(q==='"')te="double";else if(q==="`")te="template";else if(q==="<")X++;else if(q===">")X--;else if(q==="("||q==="["||q==="{")oe++;else if(q===")"||q==="]"||q==="}")oe--;else if(q===","&&oe===0&&X===0){re.push(ee),ee="";continue}}else if(te==="single"&&q==="'"||te==="double"&&q==='"'||te==="template"&&q==="`")te=null;ee+=q}if(ee)re.push(ee);for(let ne of re){let q=ne.trim();if(!q)continue;let Q=q.match(/^([$A-Z_][\w$]*)/i),H=[];if(Q)H.push(Q[1]);else if(q.startsWith("{")||q.startsWith("[")){let ie=q[0],ve=ie==="{"?"}":"]",ge=0,ue=-1,ae=null,xe=!1;for(let Me=0;Me<q.length;Me++){let de=q[Me];if(xe){xe=!1;continue}if(de==="\\"&&ae){xe=!0;continue}if(!ae){if(de==="'"||de==='"'||de==="`")ae=de==="'"?"single":de==='"'?"double":"template";else if(de===ie)ge++;else if(de===ve){if(ge--,ge===0){ue=Me;break}}}else if(ae==="single"&&de==="'"||ae==="double"&&de==='"'||ae==="template"&&de==="`")ae=null}if(ue>0){let Me=q.slice(1,ue),de=[],$e="",Fe=0,fe=null,ye=!1;for(let pe=0;pe<Me.length;pe++){let me=Me[pe];if(ye){ye=!1,$e+=me;continue}if(me==="\\"&&fe){ye=!0,$e+=me;continue}if(!fe){if(me==="'"||me==='"'||me==="`"){fe=me==="'"?"single":me==='"'?"double":"template",$e+=me;continue}if(me==="("||me==="{"||me==="[")Fe++;if(me===")"||me==="}"||me==="]")Fe--;if(me===","&&Fe===0){de.push($e.trim()),$e="";continue}}else if(fe==="single"&&me==="'"||fe==="double"&&me==='"'||fe==="template"&&me==="`")fe=null;$e+=me}if($e.trim())de.push($e.trim());for(let pe of de){if(pe.startsWith("...")){let ze=pe.slice(3).match(/^([$A-Z_][\w$]*)/i);if(ze)H.push(ze[1]);continue}let me=pe.indexOf(":");if(me!==-1){let ze=pe.slice(me+1).trim(),We=0;for(let ot=0;ot<ze.length;ot++){let Ge=ze[ot];if(Ge==="("||Ge==="{"||Ge==="[")We++;else if(Ge===")"||Ge==="}"||Ge==="]")We--;else if(Ge==="="&&We===0){ze=ze.slice(0,ot).trim();break}}let qt=ze.match(/^([$A-Z_][\w$]*)/i);if(qt)H.push(qt[1])}else{let ze=pe,We=0;for(let ot=0;ot<ze.length;ot++){let Ge=ze[ot];if(Ge==="("||Ge==="{"||Ge==="[")We++;else if(Ge===")"||Ge==="}"||Ge==="]")We--;else if(Ge==="="&&We===0){ze=ze.slice(0,ot).trim();break}}let qt=ze.match(/^([$A-Z_][\w$]*)/i);if(qt)H.push(qt[1])}}}}for(let ie of H){if(S.test(ie))continue;let ve=`${O.slice(0,J).join(`
|
|
62
61
|
`)}
|
|
63
|
-
${
|
|
64
|
-
`)}`;if(!new RegExp(`\\b${
|
|
65
|
-
`&&me!=="\r"&&me!=="{"&&me!=="}"&&
|
|
66
|
-
${
|
|
67
|
-
${
|
|
68
|
-
`)}`;else de=fe}else de=
|
|
69
|
-
`);for(let
|
|
70
|
-
`&&
|
|
71
|
-
${
|
|
72
|
-
`)}`;else xe=fe}else xe=
|
|
73
|
-
`)}else xe=j(
|
|
74
|
-
${
|
|
75
|
-
`)}`;else ae=fe}else ae=
|
|
76
|
-
`)}else ae=j(
|
|
77
|
-
`)
|
|
78
|
-
`)
|
|
79
|
-
`)
|
|
80
|
-
|
|
81
|
-
`)
|
|
82
|
-
`);for(let
|
|
83
|
-
`);for(let[I,S]
|
|
84
|
-
`);for(let[O
|
|
85
|
-
`);for(let[
|
|
86
|
-
`);for(let[
|
|
87
|
-
`)
|
|
88
|
-
`)}};var ml={meta:{docs:"
|
|
89
|
-
`)}};
|
|
90
|
-
`)
|
|
91
|
-
`)}};
|
|
92
|
-
`):s}};var
|
|
93
|
-
`)
|
|
94
|
-
`)};var
|
|
95
|
-
`):s}};var
|
|
96
|
-
`)}
|
|
97
|
-
`):s}};
|
|
98
|
-
`)}};var
|
|
99
|
-
`)}};var
|
|
100
|
-
`)
|
|
101
|
-
`)
|
|
102
|
-
`)}};var
|
|
103
|
-
`)}};var
|
|
104
|
-
`)}};var
|
|
105
|
-
`)}};var
|
|
106
|
-
`)}};var
|
|
107
|
-
`)}};var
|
|
108
|
-
`)}};var
|
|
109
|
-
`)}};var
|
|
110
|
-
`)}};var
|
|
111
|
-
`)}};var
|
|
112
|
-
`)
|
|
62
|
+
${O.slice(J+1).join(`
|
|
63
|
+
`)}`;if(!new RegExp(`\\b${ie}\\b`,"g").test(ve))m.push({filePath:h.filePath,line:J+1,column:Math.max(1,Y.indexOf(ie)+1),ruleId:"pickier/no-unused-vars",message:`'${ie}' is assigned a value but never used. Allowed unused vars must match pattern: ${R}`,severity:"error",help:`Either use this variable in your code, remove it, or prefix it with an underscore (_${ie}) to mark it as intentionally unused`})}}}let N=(J)=>{let se=((ee)=>{let oe="",X=null,te=!1,le=0;for(let ne=0;ne<ee.length;ne++){let q=ee[ne];if(te){te=!1;continue}if(q==="\\"&&X){te=!0;continue}if(!X){if(q==="'")X="single";else if(q==='"')X="double";else if(q==="`")X="template";else if(q==="("||q==="{"||q==="[")le++;else if(q===")"||q==="}"||q==="]")le--;else if(q==="="&&le===0)return oe}else if(X==="single"&&q==="'"||X==="double"&&q==='"'||X==="template"&&q==="`")X=null;oe+=q}return oe})(J);return((ee)=>{let oe="",X=0;while(X<ee.length){let te=ee[X];if(te===":"){X++;while(X<ee.length&&/\s/.test(ee[X]))X++;let le=0,ne=0,q=null,Q=!1;while(X<ee.length){let H=ee[X];if(Q){Q=!1,X++;continue}if(H==="\\"&&q){Q=!0,X++;continue}if(!q){if(H==="'")q="single";else if(H==='"')q="double";else if(H==="`")q="template";else if(H==="<")ne++;else if(H===">")ne--;else if(H==="("||H==="{"||H==="[")le++;else if(H===")"||H==="}"||H==="]")if(le>0)le--;else break;else if(H===","&&le===0&&ne===0)break}else if(q==="single"&&H==="'"||q==="double"&&H==='"'||q==="template"&&H==="`")q=null;X++}continue}oe+=te,X++}return oe})(se).split(/[^$\w]+/).filter((ee)=>ee&&ee!=="undefined")},W=(J,Y)=>{let se=/^\s*(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\b|class\b|const\b|let\b|var\b|interface\b|type\b)/;for(let Z=J;Z<O.length;Z++){let ee=(Z===J?O[Z].slice(Y+1):O[Z]).replace(/\/\/.*$/,"");if(Z!==J&&se.test(ee))return!0;if(ee.includes("{"))return!1;if(ee.includes(";"))return!0}return!0},B=(J,Y)=>{let se=!1,Z=0,re=0,ee=!1,oe=0,X=null,te=!1,le=!0,ne="",q=!1,Q=!1,H=[],ie=!1;for(let ve=J;ve<O.length;ve++){let ge=O[ve],ue=ge,ae=H.length>0&&H[H.length-1]===-1,xe=-1,Me=null,de=!1;if(!ae)for(let fe=0;fe<ge.length-1;fe++){let ye=ge[fe],pe=ge[fe+1];if(de){de=!1;continue}if(ye==="\\"&&Me){de=!0;continue}if(!Me){if(ye==="'")Me="single";else if(ye==='"')Me="double";else if(ye==="`")Me="template";else if(ye==="/"&&pe==="/"){xe=fe;break}}else if(Me==="single"&&ye==="'"||Me==="double"&&ye==='"'||Me==="template"&&ye==="`")Me=null}if(xe>=0)ue=ge.slice(0,xe);let $e=(fe)=>{let ye="",pe=0,me=null,ze=!1;while(pe<fe.length){let We=fe[pe];if(ze){ze=!1,ye+=We,pe++;continue}if(We==="\\"&&me){ze=!0,ye+=We,pe++;continue}if(!me){if(We==="'")me="single";else if(We==='"')me="double";else if(We==="`")me="template";else if(We==="/"){if(Vs(fe,pe)){pe++;while(pe<fe.length){if(fe[pe]==="\\"){pe+=2;continue}if(fe[pe]==="/"){pe++;while(pe<fe.length&&/[gimsuvy]/.test(fe[pe]))pe++;break}pe++}continue}}}else if(me==="single"&&We==="'"||me==="double"&&We==='"'||me==="template"&&We==="`")me=null;ye+=We,pe++}return ye};if(!ae)ue=$e(ue);let Fe=0;if(!se){let fe=-1,ye=le?typeof Y==="number"?Y:0:0;if(le=!1,ye>=ue.length){let pe=ue.indexOf("=>");ye=pe>=0?pe+2:0}for(let pe=ye;pe<ue.length;pe++){let me=ue[pe];if(te){te=!1;continue}if(me==="\\"&&X){te=!0;continue}if(!X){if(me!==" "&&me!=="\t"&&me!==`
|
|
64
|
+
`&&me!=="\r"&&me!=="{"&&me!=="}"&&re===0)ne=me;if(me==="'")X="single";else if(me==='"')X="double";else if(me==="`")X="template";else if(me==="<")oe++;else if(me===">")oe=Math.max(0,oe-1);else if(me==="{"){if(re===0){if(ee&&oe===0&&!Qo.has(ne)){fe=pe;break}}re++}else if(me==="}"){if(re>0){if(re--,re===0)ee=!0,ne="}"}}}else if(X==="single"&&me==="'"||X==="double"&&me==='"'||X==="template"&&me==="`")X=null}if(fe===-1){if(oe>0)continue;if(re>0&&Qo.has(ne))continue;for(let pe=ye;pe<ue.length;pe++)if(ue[pe]==="{"&&!X){fe=pe;break}}if(fe===-1)continue;se=!0,Z=1,Fe=fe+1,J=ve}for(let fe=Fe;fe<ue.length;fe++){let ye=ue[fe];if(ie){ie=!1;continue}let pe=H.length>0&&H[H.length-1]===-1,me=H.length>0&&H[H.length-1]>=0;if(ye==="\\"&&(q||Q||pe)){ie=!0;continue}if(q){if(ye==="'")q=!1;continue}if(Q){if(ye==='"')Q=!1;continue}if(pe){if(ye==="`")H.pop();else if(ye==="$"&&fe+1<ue.length&&ue[fe+1]==="{")H[H.length-1]=0,fe++;continue}if(me){if(ye==="/"){if(Vs(ue,fe)){fe++;while(fe<ue.length){if(ue[fe]==="\\"){fe+=2;continue}if(ue[fe]==="/"){while(fe+1<ue.length&&/[gimsuvy]/.test(ue[fe+1]))fe++;break}fe++}continue}}if(ye==="`"){H.push(-1);continue}if(ye==="'"){q=!0;continue}if(ye==='"'){Q=!0;continue}if(ye==="{"){H[H.length-1]++;continue}if(ye==="}")if(H[H.length-1]>0)H[H.length-1]--;else H[H.length-1]=-1;continue}if(ye==="'")q=!0;else if(ye==='"')Q=!0;else if(ye==="`")H.push(-1);else if(ye==="{")Z++;else if(ye==="}"){if(Z--,Z===0)return{from:J,to:ve}}}}return null},j=(J,Y)=>{let se={parenDepth:0,braceDepth:0,bracketDepth:0,inTemplate:!1},Z=(le)=>{for(let ne=0;ne<le.length;ne++){let q=le[ne];if(q==="`")se.inTemplate=!se.inTemplate;else if(q==="(")se.parenDepth++;else if(q===")")se.parenDepth--;else if(q==="{")se.braceDepth++;else if(q==="}")se.braceDepth--;else if(q==="[")se.bracketDepth++;else if(q==="]")se.bracketDepth--}},re=()=>se.parenDepth>0||se.braceDepth>0||se.bracketDepth>0||se.inTemplate,ee=(le)=>/(?:\?|:|\.|,|&&|\|\||\?\?|\+|-|\*|\/|%|\*\*)$/.test(le.trimEnd()),oe=(le)=>/^(?:\?|:|\.|,|&&|\|\||\?\?|\+|-|\*|\/|%|\*\*)/.test(le.trimStart()),X=O[J].slice(Y+2);Z(X);let te=J+1;while(te<O.length){let le=te===J+1?X:O[te-1];if(!(!X.trim()||re()||ee(le)||oe(O[te])))break;X+=`
|
|
65
|
+
${O[te]}`,Z(O[te]),te++}return X},z=[],K=!1,V=!1,G=!1;for(let J=0;J<O.length;J++){let Y=O[J];if(/^\s*\/\//.test(Y))continue;if(D[J])continue;let se=Y,Z=null,re=!1,ee=!1;for(let q=0;q<Y.length-1;q++){let Q=Y[q],H=Y[q+1];if(ee){ee=!1;continue}if(Q==="\\"&&(Z||re)){ee=!0;continue}if(!Z&&!re){if(Q==="'")Z="single";else if(Q==='"')Z="double";else if(Q==="`")Z="template";else if(Q==="/"){if(Vs(Y,q))re=!0;else if(H==="/"){se=Y.slice(0,q);break}}}else if(Z){if(Z==="single"&&Q==="'"||Z==="double"&&Q==='"'||Z==="template"&&Q==="`")Z=null}else if(re&&Q==="/")re=!1}let te=((q)=>{let Q="",H=0;while(H<q.length){if(q[H]==="/"){if(Vs(q,H)){H++;while(H<q.length){if(q[H]==="\\"){H+=2;continue}if(q[H]==="/"){H++;while(H<q.length&&/[gimsuvy]/.test(q[H]))H++;break}H++}continue}}Q+=q[H],H++}return Q})(se).replace(/'(?:[^'\\]|\\.)*'/g,"''").replace(/"(?:[^"\\]|\\.)*"/g,'""');{let q="";for(let Q=0;Q<te.length;Q++){let H=te[Q];if(G){G=!1;let ge=z.length>0&&z[z.length-1]===-1;q+=ge?" ":H;continue}let ie=z.length>0&&z[z.length-1]===-1,ve=z.length>0&&z[z.length-1]>=0;if(H==="\\"&&(K||V||ie)){G=!0,q+=ie?" ":H;continue}if(K){if(H==="'")K=!1;q+=H;continue}if(V){if(H==='"')V=!1;q+=H;continue}if(ie){if(H==="`")z.pop();else if(H==="$"&&Q+1<te.length&&te[Q+1]==="{")z[z.length-1]=0,q+=" ",Q++;else q+=" ";continue}if(ve){if(H==="`")z.push(-1),q+=" ";else if(H==="'")K=!0,q+=H;else if(H==='"')V=!0,q+=H;else if(H==="{")z[z.length-1]++,q+=H;else if(H==="}")if(z[z.length-1]>0)z[z.length-1]--,q+=H;else z[z.length-1]=-1,q+=" ";else q+=H;continue}if(H==="`")z.push(-1),q+=" ";else if(H==="'")K=!0,q+=H;else if(H==='"')V=!0,q+=H;else q+=H}te=q}let le=te.match(/\bfunction\b/);if(le){if(Y.includes("function scanContent")||Y.includes("function findMatching"))continue;if(te.slice(le.index+8).trimStart().startsWith(":"))continue;let Q=te.slice(0,le.index).trimEnd();if(Q.endsWith(".")||Q.endsWith("?."))continue;let H=le.index,ie=Y.indexOf("(",H);if(ie===-1)continue;let ve=0,ge=-1,ue=J,ae="";for(let $e=J;$e<O.length;$e++){let Fe=$e===J?O[$e]:O[$e],fe=$e===J?ie:0;for(let ye=fe;ye<Fe.length;ye++)if(Fe[ye]==="(")ve++;else if(Fe[ye]===")"){if(ve--,ve===0){if(ge=ye,ue=$e,J===$e)ae=Y.slice(ie+1,ge);else{ae=Y.slice(ie+1);for(let pe=J+1;pe<$e;pe++)ae+=` ${O[pe]}`;ae+=` ${Fe.slice(0,ge)}`}break}}if(ge!==-1)break}if(ge===-1)continue;if(W(ue,ge))continue;let xe=N(ae),Me=B(ue,ge),de="";if(Me)if(Me.from===ue){let $e=O[Me.from],Fe=$e.lastIndexOf("{"),fe=Fe>=0?$e.slice(Fe+1):"";if(Me.to>Me.from)de=`${fe}
|
|
66
|
+
${O.slice(Me.from+1,Me.to+1).join(`
|
|
67
|
+
`)}`;else de=fe}else de=O.slice(Me.from,Me.to+1).join(`
|
|
68
|
+
`);for(let $e of xe){if(!$e||L.test($e)||$e==="undefined")continue;if(!new RegExp(`\\b${$e}\\b`,"g").test(de))m.push({filePath:h.filePath,line:J+1,column:Math.max(1,Y.indexOf($e)+1),ruleId:"pickier/no-unused-vars",message:`'${$e}' is defined but never used (function parameter). Allowed unused args must match pattern: ${I}`,severity:"error"})}continue}let ne=Y.indexOf("=>");if(ne!==-1&&te.includes("=>")){let q=-1;for(let Q=ne-1;Q>=0;Q--){let H=Y[Q];if(H===")"){q=Q;break}if(H!==" "&&H!=="\t"&&H!==`
|
|
69
|
+
`&&H!==":"&&H!==">"&&!/\w/.test(H))break}if(q!==-1){let Q=-1,H=1;for(let ie=q-1;ie>=0;ie--){let ve=Y[ie];if(ve===")")H++;else if(ve==="("){if(H--,H===0){Q=ie;break}}}if(Q!==-1){let ie=!1,ve=0,ge=0;for(let ae=Q-1;ae>=0;ae--){let xe=Y[ae];if(xe===">"){ve++;continue}if(xe==="<"){if(ve>0){ve--;continue}if(ge<=0){ie=!0;break}continue}if(xe===":"&&ve===0&&ge<=0){ie=!0;break}if(ve>0)continue;if(xe===",")continue;if(xe===")"){ge++;continue}if(xe==="("){ge--;continue}if(xe==="|"||xe==="&"){ie=!0;break}if(xe==="="||xe==="{"||xe==="["){if(ge>=0)break;continue}if(xe!==" "&&xe!=="\t"&&!/[\w.]/.test(xe)){if(ge>=0)break}}if(!ie){let ae=Y.slice(0,Q);if(/^\s*(?:export\s+)?(?:declare\s+)?type\s+\w[\w$]*\s*(?:<[^>]*>)?\s*=\s*$/.test(ae))ie=!0;else if(/\bas\s+$/.test(ae))ie=!0}if(ie)continue;let ue=Y.slice(Q+1,q);if(!(ue.trim()===""&&Y.slice(Math.max(0,Q-10),Q).includes("async"))){let ae=N(ue);if(ae.length>0){let xe="";if(Y.slice(ne+2).trimStart().startsWith("{")){let de=B(J,ne);if(de)if(de.from===J){let $e=O[de.from],Fe=$e.indexOf("{",ne),fe=Fe>=0?$e.slice(Fe+1):"";if(de.to>de.from)xe=`${fe}
|
|
70
|
+
${O.slice(de.from+1,de.to+1).join(`
|
|
71
|
+
`)}`;else xe=fe}else xe=O.slice(de.from,de.to+1).join(`
|
|
72
|
+
`)}else xe=j(J,ne);for(let de of ae){if(!de||L.test(de)||de==="undefined")continue;if(!new RegExp(`\\b${de}\\b`,"g").test(xe))m.push({filePath:h.filePath,line:J+1,column:Math.max(1,Y.indexOf(de)+1),ruleId:"pickier/no-unused-vars",message:`'${de}' is defined but never used (function parameter). Allowed unused args must match pattern: ${I}`,severity:"error"})}continue}}}}}{let q=/(?:^|[=,:({\s])\s*([$A-Z_][\w$]*)\s*=>/gi,Q;while((Q=q.exec(te))!==null){let H=Q[1];if(!H||L.test(H)||H==="undefined")continue;let ie=te.slice(0,Q.index+Q[0].indexOf(H)).trimEnd();if(/\)\s*:$/.test(ie)||/\)\s*:\s*$/.test(ie))continue;if(/\)\s*:\s*[$A-Z_][\w$]*\s+is$/i.test(ie))continue;if(/^(?:string|number|boolean|void|never|any|unknown|object|bigint|symbol|undefined|null)$/.test(H))continue;let ve=new RegExp(`\\b${H}\\s*=>`),ge=Y.match(ve);if(!ge)continue;let ue=Y.indexOf(ge[0])+ge[0].lastIndexOf("=>"),ae="";if(Y.slice(ue+2).trimStart().startsWith("{")){let de=B(J,ue);if(de)if(de.from===J){let $e=O[de.from],Fe=$e.indexOf("{",ue),fe=Fe>=0?$e.slice(Fe+1):"";if(de.to>de.from)ae=`${fe}
|
|
73
|
+
${O.slice(de.from+1,de.to+1).join(`
|
|
74
|
+
`)}`;else ae=fe}else ae=O.slice(de.from,de.to+1).join(`
|
|
75
|
+
`)}else ae=j(J,ue);if(!new RegExp(`\\b${H}\\b`,"g").test(ae))m.push({filePath:h.filePath,line:J+1,column:Math.max(1,Y.indexOf(H)+1),ruleId:"pickier/no-unused-vars",message:`'${H}' is defined but never used (function parameter). Allowed unused args must match pattern: ${I}`,severity:"error"})}}}return m},fix:(s,h)=>{let m=gt.check(s,h);if(m.length===0)return s;let g=m.filter((F)=>F.message.includes("(function parameter)"));if(g.length===0)return s;let R=s.split(/\r?\n/),I=new Set,S=/(?:eslint|pickier)-disable-next-line\b([^*\n]*)/;for(let F=0;F<R.length;F++){let N=R[F].match(S);if(!N)continue;let W=N[1].trim();if(W===""||/\bno-unused-vars\b/.test(W)||/\bpickier\/no-unused-vars\b/.test(W))I.add(F+2)}let L=new Map;for(let F of g){if(I.has(F.line))continue;let N=F.message.match(/^'([^']+)'/);if(!N)continue;let W=N[1];if(W.startsWith("_"))continue;let B=L.get(F.line);if(!B)B=new Set,L.set(F.line,B);B.add(W)}if(L.size===0)return s;let T=s.split(/\r?\n/),A=Qt(s),O=[0];for(let F=0;F<s.length;F++)if(s[F]===`
|
|
76
|
+
`)O.push(F+1);let _=(F)=>A.templates.some(([N,W])=>F>N&&F<W)||A.regions.some((N)=>N.kind!=="template"&&F>=N.start&&F<N.end),D=!1;for(let[F,N]of L){let W=F-1,B=T[W];if(B===void 0)continue;let j=O[W]??0,z=[];for(let V of N){let G=V.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),J=new RegExp(`(?<=[(,]\\s*)\\b${G}\\b(?=\\s*[,):=])`,"g"),Y;while((Y=J.exec(B))!==null){if(_(j+Y.index))continue;z.push({start:Y.index,end:Y.index+V.length,name:V})}}if(z.length===0)continue;z.sort((V,G)=>G.start-V.start);let K=B;for(let V of z)K=`${K.slice(0,V.start)}_${V.name}${K.slice(V.end)}`;if(K!==B)T[W]=K,D=!0}return D?T.join(`
|
|
77
|
+
`):s}};function yt(s){return Ds(s)}function Pd(s,h){let m=[],g=0,R=0,I=null,S=!1;for(let L=0;L<s.length;L++){let T=s[L];if(S){S=!1;continue}if(T==="\\"&&I){S=!0;continue}if(!I){if(T==="'")I="single";else if(T==='"')I="double";else if(T==="`")I="template";else if(T==="("||T==="{"||T==="[")g++;else if(T===")"||T==="}"||T==="]")g--;else if(T===h&&g===0)m.push(s.slice(R,L)),R=L+1}else if(I==="single"&&T==="'"||I==="double"&&T==='"'||I==="template"&&T==="`")I=null}return m.push(s.slice(R)),m}function vd(s){let h=0;for(let m=0;m<s.length;m++){let g=s[m];if(g==="{"||g==="("||g==="["||g==="<")h++;else if(g==="}"||g===")"||g==="]"||g===">")h--;else if(g==="="&&h===0&&s[m+1]!=="="&&s[m-1]!=="!"&&s[m-1]!=="<"&&s[m-1]!==">")return m}return-1}function Id(s,h){let m=new RegExp(`\\b${h}\\b`),g=0,R=null,I=!1;while(g<s.length){let S=s[g];if(I){I=!1,g++;continue}if(S==="\\"&&R){I=!0,g++;continue}if(R){if(R==="single"&&S==="'"||R==="double"&&S==='"'||R==="template"&&S==="`")R=null;g++;continue}if(S==="'"){R="single",g++;continue}if(S==='"'){R="double",g++;continue}if(S==="`"){R="template",g++;continue}if(S==="["||S==="{"){let L=S,T=S==="["?"]":"}",A=1,O=g+1;while(O<s.length&&A>0){let _=s[O];if(_==="\\"){O+=2;continue}if(_===L)A++;else if(_===T)A--;if(A===0)break;O++}if(A===0&&O<s.length){let _=O+1;while(_<s.length&&(s[_]===" "||s[_]==="\t"||s[_]==="\r"||s[_]===`
|
|
78
|
+
`))_++;if(s[_]==="="&&s[_+1]!=="="&&s[_+1]!==">"){let D=s.slice(g+1,O);if(m.test(D)){let F=new RegExp(`\\b${h}\\b\\s*:`),N=new RegExp(`:\\s*\\b${h}\\b`);if(L==="{"){if(!(F.test(D)&&!N.test(D)&&!new RegExp(`(?:^|[\\s,{])\\s*${h}\\s*(?:,|\\s*=|\\s*})`).test(D)))return!0}else return!0}}}g=O+1;continue}g++}return!1}function tl(s,h){let m=new RegExp("^\\s*(?:let|var)\\s+(.+?);?\\s*$"),g=s.match(m);if(!g)return null;let R=g[1],I=vd(R);if(I>=0){let T=R.indexOf(":");if(T>=0&&T<I)R=R.slice(0,T)+R.slice(I)}let S=Pd(R,","),L=[];for(let T of S){let A=T.trim();if(!A)continue;if(A.match(/^[{[]/))return null;let _=A.match(/^([$A-Z_][\w$]*)/i);if(!_)return null;let D=_[1];if(!/=/.test(A))return null;let N=h.indexOf(s),W=`${h.slice(0,Math.max(0,N))}
|
|
79
|
+
${h.slice(N+s.length)}`,j=`\\b${D}\\s*(?:${[">>>=","**=","<<=",">>=","??=","||=","&&=","+=","-=","*=","/=","%=","&=","^=","|=","="].map((se)=>se.replace(/[|\\^$*+?.(){}[\]]/g,(Z)=>`\\${Z}`)).join("|")})`,z=new RegExp(j).test(W),K=new RegExp(`(?:^|[^$w])(?:\\+\\+|--)\\s*${D}\\b|\\b${D}\\s*(?:\\+\\+|--)`).test(W),V=Id(W,D),G=A.indexOf("="),J=G>=0?A.slice(G+1):"",Y=new RegExp(j).test(J);L.push({name:D,fixable:!z&&!K&&!V&&!Y})}return L}var Hs={meta:{docs:"Suggest 'const' for variables that are never reassigned (heuristic)"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=yt(s);for(let I=0;I<g.length;I++){if(R[I])continue;let S=g[I],L=tl(S,s);if(!L)continue;for(let{name:T,fixable:A}of L){if(!A)continue;let O=S.search(new RegExp(`\\b${T.replace(/\$/g,"\\$")}\\b`)),_=O!==-1?O:S.indexOf(T);m.push({filePath:h.filePath,line:I+1,column:Math.max(1,_+1),ruleId:"prefer-const",message:`'${T}' is never reassigned. Use 'const' instead`,severity:"error",help:`Change 'let ${T}' to 'const ${T}' since the variable is never reassigned. This makes your code more predictable and prevents accidental mutations`})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=yt(s),g=new Set,R=/(?:eslint|pickier)-disable-next-line\b([^*\n]*)/;for(let S=0;S<h.length;S++){let L=h[S].match(R);if(!L)continue;let T=L[1].trim();if(T===""||/\bprefer-const\b/.test(T))g.add(S+2)}let I=!1;for(let S=0;S<h.length;S++){if(g.has(S+1))continue;if(m[S])continue;let L=h[S];if(!/^\s*let\b/.test(L))continue;let T=tl(L,s);if(!T||T.length===0)continue;if(!T.every((O)=>O.fixable))continue;let A=L.replace(/^(\s*)let(\s+)/,"$1const$2");if(A!==L)h[S]=A,I=!0}return I?h.join(`
|
|
80
|
+
`):s}};var nl={meta:{docs:"Prefer object spread ({...obj}) over Object.assign() for object composition"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(/^\s*\/\//.test(I))continue;let S=I.indexOf("//"),L=S>=0?I.slice(0,S):I,T=L.matchAll(/\bObject\.assign\s*\(/g);for(let A of T){let O=A.index,_=L.slice(0,O),D=(_.match(/'/g)||[]).length,F=(_.match(/"/g)||[]).length,N=(_.match(/`/g)||[]).length;if(D%2!==0||F%2!==0||N%2!==0)continue;let W=O+13,B=L.slice(W),j=-1,z=1,K=0,V=0,G=null,J=!1;for(let se=1;se<B.length;se++){let Z=B[se];if(J){J=!1;continue}if(Z==="\\"&&G){J=!0;continue}if(!G){if(Z==="'")G="single";else if(Z==='"')G="double";else if(Z==="`")G="template";else if(Z==="(")z++;else if(Z===")"){if(z--,z===0)break}else if(Z==="{")K++;else if(Z==="}")K--;else if(Z==="[")V++;else if(Z==="]")V--;else if(Z===","&&z===1&&K===0&&V===0){j=se;break}}else if(G==="single"&&Z==="'"||G==="double"&&Z==='"'||G==="template"&&Z==="`")G=null}if(j===-1)continue;let Y=B.slice(1,j).trim();if(Y==="{}")m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"prefer-object-spread",message:"Prefer object spread over Object.assign",severity:"error",help:"Use object spread syntax: {...obj} instead of Object.assign({}, obj)"});else if(Y==="{}"||/^\{.*\}$/.test(Y))m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"prefer-object-spread",message:"Prefer object spread over Object.assign for object literals",severity:"error",help:"Use object spread syntax: {...obj1, ...obj2}"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[];for(let g=0;g<h.length;g++){let R=h[g];R=R.replace(/\bObject\.assign\s*\(\s*\{\}\s*,\s*([^)]+)\)/g,(I,S)=>`{${S.split(",").map((T)=>T.trim()).map((T)=>`...${T}`).join(", ")}}`),m.push(R)}return m.join(`
|
|
81
|
+
`)}};function Md(s,h){let m=!1,g=!1,R=!1;for(let I=0;I<h;I++){let S=s[I];if(S==="\\"){I++;continue}if(S==="'"&&!g&&!R)m=!m;else if(S==='"'&&!m&&!R)g=!g;else if(S==="`"&&!m&&!g)R=!R}return m||g||R}var Zs={meta:{docs:"Prefer template literals over string concatenation",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(S.startsWith("//")||S.startsWith("/*")||S.startsWith("*")||S.startsWith("import"))continue;let L=/(['"`][^'"`]*['"`])\s*\+\s*([a-z_$][\w$]*)/i,T=/([a-z_$][\w$]*)\s*\+\s*(['"`][^'"`]*['"`])/i,A=S.match(L)||S.match(T);if(A){let O=I.indexOf("//"),_=I.indexOf(A[0]);if(O>=0&&_>O)continue;if(Md(I,_))continue;let D=!!S.match(T),F=!!S.match(L);if(D&&!F){if(S.slice(S.indexOf(A[0])+A[0].length).startsWith("."))continue}m.push({filePath:h.filePath,line:R+1,column:_+1,ruleId:"general/prefer-template",message:"Unexpected string concatenation. Use template literals instead",severity:"warning",help:"Use template literals (backticks) instead of string concatenation. Example: `hello ${name}!` instead of 'hello ' + name + '!'"})}}return m}};var sl={name:"general",rules:{"array-callback-return":U(Dn),"constructor-super":U(Fn),"for-direction":U(Nn),"getter-return":U(Wn),"no-async-promise-executor":U(Bn),"no-compare-neg-zero":U(jn),"no-cond-assign":U(Un),"no-const-assign":U(zn),"no-constant-condition":U(qn),"no-constructor-return":U(Go),"no-dupe-class-members":U(Kn),"no-dupe-keys":U(Jt),"no-duplicate-case":U(Vn),"no-empty-pattern":U(Hn),"no-fallthrough":U(Zn),"no-irregular-whitespace":U(Jo),"no-loss-of-precision":U(Gn),"no-new":U(Yo),"no-regex-spaces":U(Xo),"no-promise-executor-return":U(Jn),"no-redeclare":U(Yn),"no-self-assign":U(Yt),"no-self-compare":U(Xn),"no-sparse-arrays":U(Qn),"no-undef":U(es),"no-unsafe-negation":U(ns),"no-unreachable":U(ts),"no-unused-vars":U(gt),"no-useless-catch":U(ss),"prefer-const":U(Hs),"prefer-object-spread":U(nl),"prefer-template":U(Zs),"use-isnan":U(is),"valid-typeof":U(rs)}};var tn={npm:"registry.npmjs.org",yarn:"registry.yarnpkg.com",verdaccio:"registry.verdaccio.org"};function il(s){let h=s.split("/").pop()||"";if(h==="package-lock.json")return"npm";if(h==="yarn.lock")return"yarn";if(h==="bun.lockb"||h==="bun.lock")return"bun";return null}function st(s,h){let m=il(h);if(!m)return!1;if(m==="npm")try{let g=JSON.parse(s);return"lockfileVersion"in g||"dependencies"in g||"packages"in g}catch{return!1}if(m==="yarn")return s.startsWith("#")||s.includes("__metadata:")||s.includes('resolved "');if(m==="bun")try{let g=JSON.parse(s);return"lockfileVersion"in g||"packages"in g}catch{return!1}return!1}function Cd(s){let h=new Map,m=JSON.parse(s);if((m.lockfileVersion||1)>=2&&m.packages)for(let[R,I]of Object.entries(m.packages)){if(!R||R==="")continue;let S=R.replace(/^node_modules\//,"").replace(/\/node_modules\//g,"/"),L=S.split("/node_modules/").pop()||S;h.set(R,{name:L,version:I.version||"",resolved:I.resolved,integrity:I.integrity})}else if(m.dependencies)rl(m.dependencies,h,"");return{type:"npm",packages:h}}function rl(s,h,m){for(let[g,R]of Object.entries(s)){let I=m?`${m}/${g}`:g;if(h.set(I,{name:g,version:R.version||"",resolved:R.resolved,integrity:R.integrity}),R.dependencies)rl(R.dependencies,h,I)}}function Sd(s){let h=new Map,m=s.includes("__metadata:"),g=m?"yarn-berry":"yarn",R=s.split(`
|
|
82
|
+
`),I="",S={};for(let L of R){if(L.startsWith("#")||L.trim()==="")continue;if(!L.startsWith(" ")&&L.includes("@")&&L.endsWith(":")){if(I&&(S.resolved||S.integrity))h.set(I,S);if(I=L.slice(0,-1).trim(),I.startsWith('"')&&I.endsWith('"'))I=I.slice(1,-1);let T=I.match(/^(@?[^@]+)@/);S={name:T?T[1]:I.split("@")[0],version:""}}else if(L.startsWith(" ")||L.startsWith("\t")){let T=L.trim();if(T.startsWith("version")){let A=T.match(/version[:\s]+"?([^"]+)"?/);if(A)S.version=A[1]}else if(T.startsWith("resolved")){let A=T.match(/resolved[:\s]+"?([^"]+)"?/);if(A)S.resolved=A[1]}else if(T.startsWith("resolution:")&&m){let A=T.match(/resolution[:\s]+"?([^"]+)"?/);if(A)S.resolved=A[1]}else if(T.startsWith("integrity")||T.startsWith("checksum")){let A=T.match(/(integrity|checksum)[:\s]+"?([^"]+)"?/);if(A)S.integrity=A[2]}}}if(I&&(S.resolved||S.integrity))h.set(I,S);return{type:g,packages:h}}function Ed(s){let h=new Map,m=JSON.parse(s);if(m.packages)for(let[g,R]of Object.entries(m.packages)){if(!g||g==="")continue;if(Array.isArray(R)){let[I,S,L,T]=R,A=g,O="";if(typeof I==="string"&&I.includes("@")){let _=I.lastIndexOf("@");if(_>0)A=I.substring(0,_),O=I.substring(_+1)}h.set(g,{name:A,version:O,resolved:S||void 0,integrity:T||void 0})}else if(typeof R==="object")h.set(g,{name:R.name||g.split("@")[0],version:R.version||"",resolved:R.resolved,integrity:R.integrity||R.hash})}return{type:"bun",packages:h}}function it(s,h){let m=il(h);if(!m)return null;try{switch(m){case"npm":return Cd(s);case"yarn":return Sd(s);case"bun":return Ed(s);default:return null}}catch{return null}}function ol(s){try{return new URL(s).hostname}catch{return null}}function Gs(s){try{return new URL(s).protocol}catch{return null}}function ll(s){try{let m=new URL(s).pathname,g=m.indexOf("/-/");if(g===-1)return null;let R=m.substring(1,g);if(R.startsWith("@"))return R;return R}catch{return null}}function al(s){if(!s)return null;let h=s.match(/^(sha\d+)-/);return h?h[1]:null}function cl(s){return s.map((h)=>{let m=h.toLowerCase();return tn[m]||h})}var fl={meta:{docs:"Ensure all packages are from allowed registry hosts",recommended:!0},check(s,h){let m=[];if(!st(s,h.filePath))return m;let g=it(s,h.filePath);if(!g)return m;let R=h.options||{},I=R.allowedHosts||["npm","yarn"],S=R.emptyHostname!==!1,L=cl(I),T=s.split(`
|
|
83
|
+
`);for(let[A,O]of g.packages){if(!O.resolved){if(!S){let D=ul(T,A);m.push({filePath:h.filePath,line:D,column:1,ruleId:"lockfile/validate-host",message:`Package "${O.name}" has no resolved URL`,severity:"error",help:"All packages should have a resolved URL from an allowed registry."})}continue}let _=ol(O.resolved);if(!_)continue;if(!L.includes(_)){let D=ul(T,A),F=I.map((N)=>tn[N.toLowerCase()]||N).join(", ");m.push({filePath:h.filePath,line:D,column:1,ruleId:"lockfile/validate-host",message:`Invalid host for package "${O.name}": expected one of [${F}], got "${_}"`,severity:"error",help:`Package is resolving from an unauthorized registry. This could indicate a supply chain attack. Allowed hosts: ${F}`})}}return m}};function ul(s,h){for(let m=0;m<s.length;m++)if(s[m].includes(h)||s[m].includes(`"${h}"`))return m+1;return 1}var ml={meta:{docs:"Ensure all packages use HTTPS protocol",recommended:!0},check(s,h){let m=[];if(!st(s,h.filePath))return m;let g=it(s,h.filePath);if(!g)return m;let R=s.split(`
|
|
84
|
+
`);for(let[I,S]of g.packages){if(!S.resolved)continue;let L=Gs(S.resolved);if(!L)continue;if(L!=="https:"){let T=Ld(R,I);m.push({filePath:h.filePath,line:T,column:1,ruleId:"lockfile/validate-https",message:`Package "${S.name}" uses insecure protocol: "${L}" instead of "https:"`,severity:"error",help:"All packages should be downloaded over HTTPS to prevent man-in-the-middle attacks."})}}return m}};function Ld(s,h){for(let m=0;m<s.length;m++)if(s[m].includes(h)||s[m].includes(`"${h}"`))return m+1;return 1}var hl={meta:{docs:"Ensure all packages use strong integrity hashes (SHA512)",recommended:!0},check(s,h){let m=[];if(!st(s,h.filePath))return m;let g=it(s,h.filePath);if(!g)return m;let R=h.options||{},I=R.requiredAlgorithm||"sha512",S=new Set(R.exclude||[]),L={sha1:1,sha256:2,sha384:3,sha512:4},T=L[I]||4,A=s.split(`
|
|
85
|
+
`);for(let[O,_]of g.packages){if(S.has(_.name))continue;if(!_.integrity)continue;let D=al(_.integrity);if(!D)continue;if((L[D.toLowerCase()]||0)<T){let N=Td(A,O);m.push({filePath:h.filePath,line:N,column:1,ruleId:"lockfile/validate-integrity",message:`Package "${_.name}" uses weak hash algorithm: "${D}" (required: ${I})`,severity:"error",help:`Weak hash algorithms are susceptible to collision attacks. Upgrade to ${I} by regenerating your lockfile with a recent package manager.`})}}return m}};function Td(s,h){for(let m=0;m<s.length;m++)if(s[m].includes(h)||s[m].includes(`"${h}"`))return m+1;return 1}var dl={meta:{docs:"Ensure package names match their resolved URLs",recommended:!0},check(s,h){let m=[];if(!st(s,h.filePath))return m;let g=it(s,h.filePath);if(!g)return m;let I=(h.options||{}).aliases||{},S=Object.values(tn),L=s.split(`
|
|
86
|
+
`);for(let[T,A]of g.packages){if(!A.resolved)continue;let O=!1;try{let N=new URL(A.resolved);O=S.includes(N.hostname)}catch{continue}if(!O)continue;let _=ll(A.resolved);if(!_)continue;let D=A.name,F=I[D]||D;if(_!==F){let N=Ad(L,T);m.push({filePath:h.filePath,line:N,column:1,ruleId:"lockfile/validate-package-names",message:`Package name mismatch: "${D}" resolves to "${_}"`,severity:"error",help:`This could indicate a package substitution attack. The lockfile entry is for "${D}" but the resolved URL points to "${_}".`})}}return m}};function Ad(s,h){for(let m=0;m<s.length;m++)if(s[m].includes(h)||s[m].includes(`"${h}"`))return m+1;return 1}var pl={meta:{docs:"Ensure all packages use allowed URL schemes",recommended:!0},check(s,h){let m=[];if(!st(s,h.filePath))return m;let g=it(s,h.filePath);if(!g)return m;let S=((h.options||{}).allowedSchemes||["https:","git+https:","git+ssh:"]).map((T)=>T.endsWith(":")?T:`${T}:`),L=s.split(`
|
|
87
|
+
`);for(let[T,A]of g.packages){if(!A.resolved)continue;let O=Gs(A.resolved);if(!O)continue;if(!S.includes(O)){let _=Od(L,T);m.push({filePath:h.filePath,line:_,column:1,ruleId:"lockfile/validate-scheme",message:`Package "${A.name}" uses disallowed URL scheme: "${O}"`,severity:"error",help:`Only the following URL schemes are allowed: ${S.join(", ")}. Using "${O}" could be a security risk.`})}}return m}};function Od(s,h){for(let m=0;m<s.length;m++)if(s[m].includes(h)||s[m].includes(`"${h}"`))return m+1;return 1}var gl={name:"lockfile",rules:{"validate-host":fl,"validate-https":ml,"validate-integrity":hl,"validate-package-names":dl,"validate-scheme":pl}};var yl={meta:{docs:"Fenced code blocks should be surrounded by blank lines"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I];if(/^(?:`{3,}|~{3,})/.test(S.trim()))if(!R){let T=I>0?g[I-1]:"";if(I>0&&T.trim().length>0){if(!/^:::/.test(T.trim()))m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/blanks-around-fences",message:"Fenced code blocks should be surrounded by blank lines",severity:"error"})}R=!0}else{let T=I+1<g.length?g[I+1]:"";if(I+1<g.length&&T.trim().length>0){if(!/^:::/.test(T.trim()))m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/blanks-around-fences",message:"Fenced code blocks should be surrounded by blank lines",severity:"error"})}R=!1}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[],g=!1;for(let R=0;R<h.length;R++){let I=h[R],S=R>0?h[R-1]:"",L=/^(?:`{3,}|~{3,})/.test(I.trim());if(L)if(!g){if(R>0&&S.trim().length>0&&!/^:::/.test(S.trim())&&m.length>0)m.push("");g=!0}else g=!1;if(m.push(I),L&&!g&&R+1<h.length){let T=h[R+1];if(T.trim().length>0&&!/^:::/.test(T.trim()))m.push("")}}return m.join(`
|
|
88
|
+
`)}};var bl={meta:{docs:"Headings should be surrounded by blank lines"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=I>0?g[I-1]:"",T=I+1<g.length?g[I+1]:"";if(/^(?:`{3,}|~{3,})/.test(S.trim())){R=!R;continue}if(R)continue;let A=/^#{1,6}\s/.test(S),O=I+1<g.length&&/^(?:=+|-+)\s*$/.test(T)&&S.trim().length>0;if(A){if(I>0&&L.trim().length>0)m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/blanks-around-headings",message:"Headings should be surrounded by blank lines",severity:"error"});if(I+1<g.length&&T.trim().length>0&&!/^#{1,6}\s/.test(T))m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/blanks-around-headings",message:"Headings should be surrounded by blank lines",severity:"error"})}if(O){if(I>0&&L.trim().length>0)m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/blanks-around-headings",message:"Headings should be surrounded by blank lines",severity:"error"});let _=I+2<g.length?g[I+2]:"";if(I+2<g.length&&_.trim().length>0)m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/blanks-around-headings",message:"Headings should be surrounded by blank lines",severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[],g=!1;for(let R=0;R<h.length;R++){let I=h[R],S=R>0?h[R-1]:"",L=R+1<h.length?h[R+1]:"";if(/^(?:`{3,}|~{3,})/.test(I.trim())){g=!g,m.push(I);continue}if(g){m.push(I);continue}let T=/^#{1,6}\s/.test(I),A=R+1<h.length&&/^(?:=+|-+)\s*$/.test(L)&&I.trim().length>0;if(T||A){if(R>0&&S.trim().length>0&&m.length>0)m.push("")}if(m.push(I),T){if(R+1<h.length&&L.trim().length>0&&!/^#{1,6}\s/.test(L))m.push("")}if(R>0&&/^(?:=+|-+)\s*$/.test(I)&&h[R-1].trim().length>0){if((R+1<h.length?h[R+1]:"").trim().length>0)m.push("")}}return m.join(`
|
|
89
|
+
`)}};var xl={meta:{docs:"Lists should be surrounded by blank lines"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=!1;for(let S=0;S<g.length;S++){let L=g[S],T=S>0?g[S-1]:"";if(/^(?:`{3,}|~{3,})/.test(L.trim())){if(I=!I,R)R=!1;continue}if(I)continue;let A=/^(?:\s*)(?:[*\-+]|\d+\.)\s+/.test(L),O=R&&!A&&L.trim().length>0&&/^\s+/.test(L);if(A&&!R){if(R=!0,S>0&&T.trim().length>0)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"markdown/blanks-around-lists",message:"Lists should be surrounded by blank lines",severity:"error"})}else if(!A&&!O&&R&&L.trim().length>0){if(R=!1,/^(?:\s*)(?:[*\-+]|\d+\.)\s+/.test(T))m.push({filePath:h.filePath,line:S,column:1,ruleId:"markdown/blanks-around-lists",message:"Lists should be surrounded by blank lines",severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[],g=!1,R=!1,I=(S)=>/^(?:\s*)(?:[*\-+]|\d+\.)\s+/.test(S);for(let S=0;S<h.length;S++){let L=h[S],T=S>0?h[S-1]:"";if(/^(?:`{3,}|~{3,})/.test(L.trim())){R=!R,g=!1,m.push(L);continue}if(R){m.push(L);continue}let A=I(L),O=L.trim().length===0,_=g&&!A&&!O&&/^\s/.test(L);if(A&&!g){if(S>0&&T.trim().length>0&&m.length>0)m.push("");g=!0}else if(!A&&!_&&!O&&g){if(g=!1,m.length>0)m.push("")}else if(O){let D=S+1<h.length?h[S+1]:"",F=I(D),N=/^\s+\S/.test(D);if(!F&&!N&&g)g=!1}m.push(L)}return m.join(`
|
|
90
|
+
`)}};function ce(s){let h=new Set,m=null,g=0,R=!1,I=!1;for(let S=0;S<s.length;S++){let L=s[S],T=L.trim();if(m===null){let D=T.match(/^(`{3,}|~{3,})(.*)$/);if(D){let F=D[1],N=D[2],W=F[0];if(W==="`"&&N.includes("`"));else{m=W,g=F.length,h.add(S),R=!1,I=!1;continue}}}else{h.add(S);let D=T.match(/^(`{3,}|~{3,})\s*$/);if(D&&D[1][0]===m&&D[1].length>=g)m=null,g=0;continue}let A=L.length-L.trimStart().length,O=/^\t/.test(L);if((A>=4||O)&&T.length>0){if(I||R||S===0)h.add(S),I=!0;R=I;continue}if(T.length===0){if(I)h.add(S),R=!0;else R=!0;continue}I=!1,R=!1}return h}function wl(s,h,m){let g=0,R=0;while(g<s.length){if(s[g]!=="`"){g++;continue}let I=0;while(s[g+I]==="`")I++;let S=g+I,L=-1;while(S<s.length)if(s[S]==="`"){let T=0;while(s[S+T]==="`")T++;if(T===I){L=S;break}S+=T}else S++;if(L===-1){g+=I;continue}if(R<g)h(s.slice(R,g));m(s.slice(g,L+I)),g=L+I,R=g}if(R<s.length)h(s.slice(R))}function Ft(s,h){let m="";return wl(s,(g)=>{m+=h(g)},(g)=>{m+=g}),m}function bt(s){let h="";return wl(s,(m)=>{h+=m},(m)=>{h+=" ".repeat(m.length)}),h}function Rl(s){let h=ce(s),m=[],g=0;for(let R=0;R<s.length;R++){let I=s[R];if(h.has(R)||I.trim()===""){g=0,m.push(I);continue}if(g===0){let T=bt(I),A=_d(T);if(!A){m.push(T);continue}g=A.length,m.push(T.slice(0,A.index)+" ".repeat(T.length-A.index));continue}let S=new RegExp(`(?<!\`)\`{${g}}(?!\`)`).exec(I);if(!S){m.push(" ".repeat(I.length));continue}let L=S.index+S[0].length;g=0,m.push(" ".repeat(L)+bt(I.slice(L)))}return m}function _d(s){let h=/(?<!`)(`+)(?!`)(?=[^`]*$)/.exec(s);return h?{index:h.index,length:h[1].length}:null}function Rt(s){let h=new Set,m=ce(s);for(let g=0;g<s.length;g++){if(m.has(g))continue;let R=s[g];if(!Dd(R))continue;if(g>0&&!m.has(g-1)&&/\|/.test(s[g-1])&&s[g-1].trim().length>0)h.add(g-1);h.add(g);for(let I=g+1;I<s.length;I++){if(m.has(I))break;let S=s[I];if(S.trim().length===0||!/\|/.test(S))break;h.add(I)}}return h}function Dd(s){let h=s.trim();if(!h.includes("|"))return!1;if(!/^[|\s:-]+$/.test(h))return!1;if(!/-{3,}/.test(h))return!1;return!0}var kl={meta:{docs:"Tables should be surrounded by blank lines"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=!1,S=Rt(g);for(let L=0;L<g.length;L++){let T=g[L],A=L>0?g[L-1]:"";if(/^(?:`{3,}|~{3,})/.test(T.trim())){if(I=!I,R)R=!1;continue}if(I)continue;let O=S.has(L)&&/\|/.test(T)&&T.trim().length>0;if(O&&!R){if(R=!0,L>0&&A.trim().length>0)m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"markdown/blanks-around-tables",message:"Tables should be surrounded by blank lines",severity:"error"})}else if(!O&&R){if(R=!1,T.trim().length>0)m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"markdown/blanks-around-tables",message:"Tables should be surrounded by blank lines",severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=Rt(h),R=[],I=!1;for(let L=0;L<h.length;L++){let T=h[L];if(m.has(L)){R.push(T);continue}let A=g.has(L)&&/\|/.test(T)&&T.trim().length>0;if(A&&!I){let O=R.length-1;if(O>=0&&R[O].trim().length>0)R.push("");I=!0,R.push(T);continue}if(!A&&I){if(I=!1,T.trim().length>0)R.push("")}R.push(T)}let S=R.join(`
|
|
91
|
+
`);return S!==s?S:s}};var $l={meta:{docs:"Code block style should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).style||"consistent",S=null,L=!1;for(let T=0;T<g.length;T++){let A=g[T];if(/^(?:`{3,}|~{3,})/.test(A)){if(L=!L,I==="indented")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/code-block-style",message:"Expected indented code block style",severity:"error"});else if(I==="consistent"){if(S===null)S="fenced";else if(S==="indented")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/code-block-style",message:"Code block style should be consistent throughout document",severity:"error"})}continue}if(L)continue;if(/^(?: {4}|\t)/.test(A)&&A.trim().length>0){let F=(T>0?g[T-1]:"").trim().length===0||T===0;if(F&&I==="fenced")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/code-block-style",message:"Expected fenced code block style",severity:"error"});else if(F&&I==="consistent"){if(S===null)S="indented";else if(S==="fenced")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/code-block-style",message:"Code block style should be consistent throughout document",severity:"error"})}}}return m}};function Pl(s){let h=new Set,m=null,g=0;for(let R=0;R<s.length;R++){let I=s[R].trim();if(m===null){let S=I.match(/^(`{3,}|~{3,})(.*)$/);if(S){let L=S[1][0];if(L==="`"&&S[2].includes("`"))continue;m=L,g=S[1].length,h.add(R)}}else{let S=I.match(/^(`{3,}|~{3,})\s*$/);if(S&&S[1][0]===m&&S[1].length>=g)h.add(R),m=null,g=0}}return h}var vl={meta:{docs:"Code fence style should be consistent (backtick or tilde)"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=Pl(g),S=(h.options||{}).style||"consistent",L=null;for(let T of R){let A=g[T],_=/^`{3,}/.test(A.trim())?"backtick":"tilde";if(S==="backtick"||S==="tilde"){if(_!==S)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/code-fence-style",message:S==="tilde"?"Expected tilde (~~~) code fence":"Expected backtick (```) code fence",severity:"error"})}else if(S==="consistent"){if(L===null)L=_;else if(L!==_)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/code-fence-style",message:"Code fence style should be consistent throughout document",severity:"error"})}}return m},fix:(s,h)=>{let g=(h.options||{}).style||"consistent",R=s.split(/\r?\n/),I=Pl(R),S="backtick";if(g==="backtick"||g==="tilde")S=g;else for(let O of I){S=/^`{3,}/.test(R[O].trim())?"backtick":"tilde";break}let L=S==="backtick"?"`":"~",T=S==="backtick"?/^(\s*)(~{3,})(.*)$/:/^(\s*)(`{3,})(.*)$/;return R.map((O,_)=>{if(!I.has(_))return O;return O.replace(T,(D,F,N,W)=>`${F}${L.repeat(N.length)}${W}`)}).join(`
|
|
92
|
+
`)}};var Il={meta:{docs:"Commands in code blocks should not be prefixed with $ unless showing output"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=-1;for(let S=0;S<g.length;S++){let L=g[S];if(/^(?:`{3,}|~{3,})/.test(L)){if(!R)R=!0,I=S;else R=!1;continue}if(R&&/^\$\s+/.test(L.trim())){let T=!0,A=!1;for(let O=I+1;O<S;O++){let _=g[O].trim();if(_.length>0){if(A=!0,!_.startsWith("$")){T=!1;break}}}if(T&&A)m.push({filePath:h.filePath,line:S+1,column:L.indexOf("$")+1,ruleId:"markdown/commands-show-output",message:"Dollar signs used before commands without showing output",severity:"warning"})}}return m}};var Ml={meta:{docs:"Link text should be meaningful and descriptive"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=["click here","here","link","read more","more","this"],I=!1;for(let S=0;S<g.length;S++){let L=g[S];if(/^(?:`{3,}|~{3,})/.test(L.trim())){I=!I;continue}if(I)continue;let A=L.replace(/``[^`]+``/g,(O)=>" ".repeat(O.length)).replace(/`[^`]+`/g,(O)=>" ".repeat(O.length)).matchAll(/\[([^\]]+)\]\([^)]+\)/g);for(let O of A){let _=O[1].toLowerCase().trim();if(R.includes(_)){let D=O.index+1;m.push({filePath:h.filePath,line:S+1,column:D,ruleId:"markdown/descriptive-link-text",message:`Link text '${O[1]}' is not descriptive`,severity:"warning"})}}}return m}};var Ki="(?<!\\*)\\*(?!\\*)(?!\\s)([^*]*[^*\\s])\\*(?!\\*)",Fd=new RegExp(Ki),Vi="(?<![A-Za-z0-9_])_(?!_)([^_]+)_(?![A-Za-z0-9_])",Nd=new RegExp(Vi),Cl={meta:{docs:"Emphasis style should be consistent (asterisk or underscore)"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).style||"consistent",S=null,L=ce(g),T=Rl(g);for(let A=0;A<g.length;A++){let O=g[A];if(L.has(A))continue;let _=T[A]??bt(O),D=_.matchAll(new RegExp(Ki,"g"));for(let N of D)if(I==="underscore")m.push({filePath:h.filePath,line:A+1,column:N.index+1,ruleId:"markdown/emphasis-style",message:"Expected underscore (_) for emphasis",severity:"error"});else if(I==="consistent"){if(S===null)S="asterisk";else if(S==="underscore")m.push({filePath:h.filePath,line:A+1,column:N.index+1,ruleId:"markdown/emphasis-style",message:"Emphasis style should be consistent throughout document",severity:"error"})}let F=_.matchAll(new RegExp(Vi,"g"));for(let N of F)if(I==="asterisk")m.push({filePath:h.filePath,line:A+1,column:N.index+1,ruleId:"markdown/emphasis-style",message:"Expected asterisk (*) for emphasis",severity:"error"});else if(I==="consistent"){if(S===null)S="underscore";else if(S==="asterisk")m.push({filePath:h.filePath,line:A+1,column:N.index+1,ruleId:"markdown/emphasis-style",message:"Emphasis style should be consistent throughout document",severity:"error"})}}return m},fix:(s,h)=>{let g=(h.options||{}).style||"consistent",R=s.split(/\r?\n/),I=ce(R),S="asterisk";if(g==="asterisk")S="asterisk";else if(g==="underscore")S="underscore";else if(g==="consistent"){let T=null,A=null;for(let _=0;_<R.length;_++){if(I.has(_))continue;let D=bt(R[_]);if(T===null){let F=D.match(Fd);if(F)T={line:_,col:F.index}}if(A===null){let F=D.match(Nd);if(F)A={line:_,col:F.index}}if(T&&A)break}if(T&&(!A||((_,D)=>_.line!==D.line?_.line-D.line:_.col-D.col)(T,A)<0))S="asterisk";else if(A)S="underscore"}let L=!1;for(let T=0;T<R.length;T++){if(I.has(T))continue;let A=Ft(R[T],(O)=>S==="asterisk"?O.replace(new RegExp(Vi,"g"),"*$1*"):O.replace(new RegExp(Ki,"g"),"_$1_"));if(A!==R[T])R[T]=A,L=!0}return L?R.join(`
|
|
93
|
+
`):s}};var Sl={meta:{docs:"Fenced code blocks should have a language specified"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++)if(g[R].match(/^(?:`{3,}|~{3,})\s*$/)){let L=!0;for(let T=R-1;T>=0;T--)if(/^(?:`{3,}|~{3,})/.test(g[T])){L=!1;break}if(L)m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"markdown/fenced-code-language",message:"Fenced code blocks should have a language specified",severity:"error"})}return m}};var El={meta:{docs:"First line in a file should be a top-level heading"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=-1;for(let T=0;T<g.length;T++)if(g[T].trim().length>0){R=T;break}if(R===-1)return m;let I=g[R],S=/^#\s/.test(I),L=R+1<g.length&&/^=+\s*$/.test(g[R+1]);if(!S&&!L)m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"markdown/first-line-heading",message:"First line in a file should be a top-level heading",severity:"warning"});return m}};var Ll={meta:{docs:"Heading levels should only increment by one level at a time"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),I=0;for(let S=0;S<g.length;S++){if(R.has(S))continue;let T=g[S].match(/^(#{1,6})\s/);if(T){let A=T[1].length;if(I>0&&A>I+1)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"markdown/heading-increment",message:`Heading level should not skip from h${I} to h${A}`,severity:"error"});I=A}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=0,R=!1;for(let I=0;I<h.length;I++){if(m.has(I))continue;let L=h[I].match(/^(#{1,6})(\s.*)$/);if(!L)continue;let T=L[1].length,A=g===0?T:Math.min(T,g+1);if(A!==T)h[I]="#".repeat(A)+L[2],R=!0;g=A}return R?h.join(`
|
|
94
|
+
`):s}};var Tl={meta:{docs:"Headings must start at the beginning of the line"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I];if(/^(?:`{3,}|~{3,})/.test(S.trim())){R=!R;continue}if(R)continue;if(S.match(/^(\s+)(#{1,6}\s)/))m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/heading-start-left",message:"Headings must start at the beginning of the line",severity:"error"})}return m},fix:(s)=>s.split(/\r?\n/).map((g)=>g.replace(/^(\s+)(#{1,6}\s)/,"$2")).join(`
|
|
95
|
+
`)};var Al={meta:{docs:"Heading style should be consistent (atx, setext, or consistent)"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).style||"consistent",S=null,L=ce(g);for(let T=0;T<g.length;T++){if(L.has(T))continue;let A=g[T],O=T+1<g.length?g[T+1]:"",_=A.match(/^#{1,6}\s/),D=O.match(/^(?:=+|-+)\s*$/)&&A.trim().length>0&&!L.has(T+1);if(_){if(I==="setext")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/heading-style",message:"Expected setext style heading",severity:"error"});else if(I==="consistent"){if(S===null)S="atx";else if(S==="setext")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/heading-style",message:"Heading style should be consistent throughout document",severity:"error"})}}else if(D){if(I==="atx")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/heading-style",message:"Expected atx style heading",severity:"error"});else if(I==="consistent"){if(S===null)S="setext";else if(S==="atx")m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/heading-style",message:"Heading style should be consistent throughout document",severity:"error"})}}}return m},fix:(s,h)=>{let g=(h.options||{}).style||"consistent",R=s.split(/\r?\n/),I=ce(R),S=g==="consistent"?null:g;if(S===null)for(let A=0;A<R.length;A++){if(I.has(A))continue;let O=R[A],_=A+1<R.length?R[A+1]:"";if(/^#{1,6}\s/.test(O)){S="atx";break}if(/^(?:=+|-+)\s*$/.test(_)&&O.trim().length>0&&!I.has(A+1)){S="setext";break}}if(S===null)return s;let L=[],T=!1;for(let A=0;A<R.length;A++){let O=R[A];if(I.has(A)){L.push(O);continue}let _=A+1<R.length?R[A+1]:"";if(S==="atx"){let D=/^=+\s*$/.test(_),F=/^-+\s*$/.test(_),N=I.has(A+1);if((D||F)&&!N&&O.trim().length>0&&!/^#{1,6}\s/.test(O)){let W=D?"#":"##";L.push(`${W} ${O.trim()}`),A++,T=!0;continue}}if(S==="setext"){let D=O.match(/^(#{1,2})\s+(.+?)\s*#*\s*$/);if(D){let F=D[1].length,N=D[2],W=(F===1?"=":"-").repeat(Math.max(3,N.length));L.push(N),L.push(W),T=!0;continue}}L.push(O)}return T?L.join(`
|
|
96
|
+
`):s}};var Ol={meta:{docs:"Horizontal rule style should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).style||"consistent",S=null;for(let L=0;L<g.length;L++){let T=g[L].trim();if(T.match(/^([-*_])\1{2,}$/)){let O=T;if(I!=="consistent"&&T!==I)m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"markdown/hr-style",message:`Expected horizontal rule style '${I}'`,severity:"error"});else if(I==="consistent"){if(S===null)S=O;else if(S!==O)m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"markdown/hr-style",message:"Horizontal rule style should be consistent throughout document",severity:"error"})}}}return m}};var _l={meta:{docs:"Lines should not exceed a specified length"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=h.options||{},I=R.line_length||80,S=R.code_blocks!==!1,L=R.tables!==!1,T=R.headings!==!1,A=!1;for(let O=0;O<g.length;O++){let _=g[O];if(/^(?:`{3,}|~{3,})/.test(_)){A=!A;continue}if(A&&!S)continue;if(!L&&/\|/.test(_))continue;if(!T&&/^#{1,6}\s/.test(_))continue;if(_.length>I)m.push({filePath:h.filePath,line:O+1,column:I+1,ruleId:"markdown/line-length",message:`Line length exceeds ${I} characters (${_.length} characters)`,severity:"warning"})}return m}};function Wd(s){return s.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s/g,"-")}var Dl={meta:{docs:"Link fragments should reference valid headings"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),I=new Set;for(let S=0;S<g.length;S++){if(R.has(S))continue;let T=g[S].match(/^#{1,6}\s+(.+?)(?:\s*#+\s*)?$/);if(T){let A=T[1].trim();I.add(Wd(A))}}for(let S=0;S<g.length;S++){if(R.has(S))continue;let T=g[S].matchAll(/\[[^\]]+\]\(#([^)]+)\)/g);for(let A of T){let O=A[1];if(!I.has(O)){let _=A.index+1;m.push({filePath:h.filePath,line:S+1,column:_,ruleId:"markdown/link-fragments",message:`Link fragment '#${O}' does not match any heading`,severity:"error"})}}}return m}};var Fl={meta:{docs:"Link and image reference definitions should be used"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),I=new Map;for(let L=0;L<g.length;L++){if(R.has(L))continue;let A=g[L].match(/^\[([^\]]+)\]:\s*\S+/);if(A)I.set(A[1].toLowerCase(),L+1)}let S=new Set;for(let L=0;L<g.length;L++){if(R.has(L))continue;let T=g[L];if(T.match(/^\[(?:[^\]]+)\]:\s*\S+/))continue;let A=T.matchAll(/\[([^\]]+)\](?:\[([^\]]+)\])?(?!\()/g);for(let O of A){let _=(O[2]||O[1]).toLowerCase();S.add(_)}}for(let[L,T]of I)if(!S.has(L))m.push({filePath:h.filePath,line:T,column:1,ruleId:"markdown/link-image-reference-definitions",message:`Unused reference definition '[${L}]'`,severity:"warning"});return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=new Map;for(let S=0;S<h.length;S++){if(m.has(S))continue;let L=h[S].match(/^\s*\[([^\]]+)\]:\s*\S+/);if(L)g.set(S,L[1].toLowerCase())}if(g.size===0)return s;let R=new Set;for(let S=0;S<h.length;S++){if(m.has(S))continue;if(g.has(S))continue;let T=h[S].matchAll(/\[([^\]]+)\](?:\[([^\]]*)\])?(?!\()/g);for(let A of T){let O=(A[2]&&A[2].length>0?A[2]:A[1]).toLowerCase();R.add(O)}}let I=new Set;for(let[S,L]of g)if(!R.has(L))I.add(S);if(I.size===0)return s;return h.filter((S,L)=>!I.has(L)).join(`
|
|
97
|
+
`)}};var Nl={meta:{docs:"Link and image style should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),S=(h.options||{}).style||"consistent",L=S==="consistent"?null:S;if(L===null){let A=0,O=0,_=!1;for(let D=0;D<g.length;D++){if(R.has(D))continue;let F=g[D];if(F.includes("<!--"))_=!0;if(F.includes("-->")){_=!1;continue}if(_)continue;if(/^\s*\[(?:[^\]]+)\]:\s*\S+/.test(F))continue;let N=Hi(F);A+=(N.match(/\[[^\]]+\]\([^)]+\)/g)||[]).length,O+=(N.match(/\[[^\]]+\]\[(?:[^\]]*)\]/g)||[]).length}L=O>A?"reference":"inline"}let T=!1;for(let A=0;A<g.length;A++){if(R.has(A))continue;let O=g[A];if(O.includes("<!--"))T=!0;if(O.includes("-->")){T=!1;continue}if(T)continue;if(O.match(/^\[(?:[^\]]+)\]:\s*\S+/))continue;let _=Hi(O),D=_.matchAll(/\[[^\]]+\]\([^)]+\)/g);for(let N of D)if(L==="reference")m.push({filePath:h.filePath,line:A+1,column:N.index+1,ruleId:"markdown/link-image-style",message:S==="consistent"?"Link style should be consistent throughout document":"Expected reference style link",severity:S==="consistent"?"warning":"error"});let F=_.matchAll(/\[[^\]]+\]\[(?:[^\]]+)\]/g);for(let N of F)if(L==="inline")m.push({filePath:h.filePath,line:A+1,column:N.index+1,ruleId:"markdown/link-image-style",message:S==="consistent"?"Link style should be consistent throughout document":"Expected inline style link",severity:S==="consistent"?"warning":"error"})}return m},fix:(s,h)=>{let g=(h.options||{}).style||"consistent",R=s.split(/\r?\n/),I=ce(R),S=new Map;for(let A=0;A<R.length;A++){if(I.has(A))continue;let O=R[A].match(/^\s*\[([^\]]+)\]:\s*(\S+)(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?\s*$/);if(O){let _=O[1].toLowerCase(),D=O[2],F=O[3]??O[4]??O[5];if(!S.has(_))S.set(_,{url:D,title:F})}}if(S.size===0)return s;let L=g==="reference"?"reference":"inline";if(g==="consistent"){let A=0,O=0;for(let _=0;_<R.length;_++){if(I.has(_))continue;let D=R[_];if(/^\s*\[(?:[^\]]+)\]:\s*\S+/.test(D))continue;let F=Hi(D);A+=(F.match(/\[[^\]]+\]\([^)]+\)/g)||[]).length,O+=(F.match(/\[[^\]]+\]\[(?:[^\]]*)\]/g)||[]).length}L=O>A?"reference":"inline"}if(L!=="inline")return s;let T=!1;for(let A=0;A<R.length;A++){if(I.has(A))continue;let O=R[A];if(/^\s*\[(?:[^\]]+)\]:\s*\S+/.test(O))continue;let _=O;for(let D=0;D<8;D++){let F=_.replace(/(!?)\[((?:[^[\]]|\[[^\]]*\]\([^)]*\))+)\]\[([^\]]*)\]/g,(N,W,B,j)=>{let z=(j.trim()===""?B:j).toLowerCase(),K=S.get(z);if(!K)return N;let V=K.title?` "${K.title}"`:"";return`${W}[${B}](${K.url}${V})`});if(F===_)break;_=F}if(_!==O)R[A]=_,T=!0}return T?R.join(`
|
|
98
|
+
`):s}};function Hi(s){return s.replace(/(`+)([^`]+?)\1/g,(h)=>" ".repeat(h.length))}var Wl={meta:{docs:"List items at the same level should have consistent indentation"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=new Map,I=!1;for(let S=0;S<g.length;S++){let L=g[S],T=L.match(/^(\s*)(?:[*\-+]|\d+\.)\s+/);if(T){I=!0;let A=T[1].length,O=Math.floor(A/2);if(R.has(O)){let _=R.get(O);if(A!==_)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"markdown/list-indent",message:`Inconsistent indentation for list items at the same level. Expected ${_} spaces, found ${A}`,severity:"error"})}else R.set(O,A)}else if(L.trim().length===0){if(I){let A=g.slice(S+1).find((O)=>O.trim().length>0);if(A&&!/^(?:\s*)(?:[*\-+]|\d+\.)\s+/.test(A))I=!1,R.clear()}}}return m}};var Bl={meta:{docs:"Spaces after list markers should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=h.options||{},I=R.ul_single||1,S=R.ol_single||1;for(let L=0;L<g.length;L++){let T=g[L],A=T.match(/^(\s*)([*\-+])(\s+)/);if(A){let _=A[3].length;if(_!==I)m.push({filePath:h.filePath,line:L+1,column:A[1].length+2,ruleId:"markdown/list-marker-space",message:`Expected ${I} space${I!==1?"s":""} after list marker, found ${_}`,severity:"error"})}let O=T.match(/^(\s*)(\d+\.)(\s+)/);if(O){let _=O[3].length;if(_!==S)m.push({filePath:h.filePath,line:L+1,column:O[1].length+O[2].length+1,ruleId:"markdown/list-marker-space",message:`Expected ${S} space${S!==1?"s":""} after list marker, found ${_}`,severity:"error"})}}return m},fix:(s,h)=>{let m=h.options||{},g=m.ul_single||1,R=m.ol_single||1;return s.split(/\r?\n/).map((L)=>(L=L.replace(/^(\s*)([*\-+])\s+/,(T,A,O)=>`${A}${O}${" ".repeat(g)}`),L=L.replace(/^(\s*)(\d+\.)\s+/,(T,A,O)=>`${A}${O}${" ".repeat(R)}`),L)).join(`
|
|
99
|
+
`)}};var jl={meta:{docs:"Images should have alternate text"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I];if(/^(?:`{3,}|~{3,})/.test(S.trim())){R=!R;continue}if(R)continue;let T=S.replace(/``[^`]+``/g,(A)=>" ".repeat(A.length)).replace(/`[^`]+`/g,(A)=>" ".repeat(A.length)).matchAll(/!\[\s*\]\([^)]+\)/g);for(let A of T){let O=A.index+1;m.push({filePath:h.filePath,line:I+1,column:O,ruleId:"markdown/no-alt-text",message:"Images should have alternate text (alt text)",severity:"error"})}}return m}};var Ul={meta:{docs:"Bare URLs should be wrapped in angle brackets"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),I=!1;for(let S=0;S<g.length;S++){let L=g[S];if(R.has(S))continue;if(L.includes("<!--"))I=!0;if(L.includes("-->")){I=!1;continue}if(I)continue;if(/^\[(?:[^\]]+)\]:\s*\S+/.test(L))continue;let T=L.replace(/`[^`]+`/g,(_)=>" ".repeat(_.length)),A=/(?<![<(="'])https?:\/\/[^\s<>`)\]"']+(?![>\])"'])/g,O=T.matchAll(A);for(let _ of O)m.push({filePath:h.filePath,line:S+1,column:_.index+1,ruleId:"markdown/no-bare-urls",message:"Bare URL used. Wrap in angle brackets: <url>",severity:"error"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=!1;return h.map((I,S)=>{if(m.has(S))return I;if(I.includes("<!--"))g=!0;if(I.includes("-->"))return g=!1,I;if(g)return I;if(/^\[(?:[^\]]+)\]:\s*\S+/.test(I))return I;return I.replace(/(?<![<(="'])https?:\/\/[^\s<>`)\]"']+(?![>\])"'])/g,"<$&>")}).join(`
|
|
100
|
+
`)}};var zl={meta:{docs:"Blank lines inside blockquotes should use the blockquote symbol"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=!1;for(let S=0;S<g.length;S++){let L=g[S],T=S+1<g.length?g[S+1]:"";if(/^(?:`{3,}|~{3,})/.test(L.trim())){I=!I,R=!1;continue}if(I)continue;let A=/^\s*>/.test(L),O=L.trim().length===0,_=/^\s*>/.test(T);if(A)R=!0;else if(O&&R&&_)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"markdown/no-blanks-blockquote",message:"Blank line inside blockquote should use blockquote symbol (>)",severity:"error"});else if(!A&&!O)R=!1}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=!1,g=!1,R=!1;for(let I=0;I<h.length;I++){let S=h[I],L=I+1<h.length?h[I+1]:"";if(/^(?:`{3,}|~{3,})/.test(S.trim())){g=!g,m=!1;continue}if(g)continue;let T=/^\s*>/.test(S),A=S.trim().length===0,O=/^\s*>/.test(L);if(T)m=!0;else if(A&&m&&O){let _=L.match(/^(\s*)>/),D=_?`${_[1]}>`:">";h[I]=D,R=!0}else if(!T&&!A)m=!1}return R?h.join(`
|
|
101
|
+
`):s}};var ql={meta:{docs:"Multiple headings should not have the same content"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=Array.from({length:7},()=>new Map);for(let S=0;S<g.length;S++){let L=g[S];if(/^(?:`{3,}|~{3,})/.test(L.trim())){R=!R;continue}if(R)continue;if(/^\s*\[Compare changes\]\(/.test(L)){for(let D=3;D<=6;D++)I[D].clear();continue}let T=null,A=0,O=L.match(/^(#{1,6})\s+(.+?)(?:\s*#+\s*)?$/);if(O)A=O[1].length,T=O[2].trim();if(!T){let D=S+1<g.length?g[S+1]:"";if(/^(?:=+)\s*$/.test(D)&&L.trim().length>0)A=1,T=L.trim();else if(/^(?:-+)\s*$/.test(D)&&L.trim().length>0)A=2,T=L.trim()}if(!T||A===0)continue;for(let D=A+1;D<=6;D++)I[D].clear();let _=I[A];if(_.has(T))m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"markdown/no-duplicate-heading",message:`Duplicate heading "${T}" (first occurrence on line ${_.get(T)})`,severity:"error"});else _.set(T,S+1)}return m}};var Bd=/[.!?:;,]\s*$/;function Kl(s,h,m){let g=s.match(/^\*\*([^*]+)\*\*\s*$/)||s.match(/^__([^_]+)__\s*$/),R=s.match(/^\*([^*]+)\*\s*$/)||s.match(/^_([^_]+)_\s*$/),I=g||R;if(!I)return null;if(h.trim().length!==0||m.trim().length!==0)return null;let S=I[1];if(Bd.test(S))return null;if(S.trim().split(/\s+/).length>=7)return null;return S}var Vl={meta:{docs:"Emphasis should not be used for headings"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let S=g[I],L=I>0?g[I-1]:"",T=I+1<g.length?g[I+1]:"";if(Kl(S,L,T)===null)continue;m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"markdown/no-emphasis-as-heading",message:"Emphasis used instead of a heading",severity:"warning"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=2,R=!1;for(let I=0;I<h.length;I++){if(m.has(I))continue;let S=h[I],L=S.match(/^(#{1,6})\s/);if(L){g=L[1].length;continue}let T=I>0?h[I-1]:"",A=I+1<h.length?h[I+1]:"",O=Kl(S,T,A);if(O===null)continue;let _=Math.min(6,Math.max(2,g+1));h[I]=`${"#".repeat(_)} ${O.trim()}`,R=!0}return R?h.join(`
|
|
102
|
+
`):s}};var Hl={meta:{docs:"Links should not be empty"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I];if(/^(?:`{3,}|~{3,})/.test(S.trim())){R=!R;continue}if(R)continue;let L=S.replace(/`[^`]+`/g,(O)=>"x".repeat(O.length)),T=L.matchAll(/\[[^\]]+\]\(\s*\)/g);for(let O of T){let _=O.index+1;m.push({filePath:h.filePath,line:I+1,column:_,ruleId:"markdown/no-empty-links",message:"Empty link URL",severity:"error"})}let A=L.matchAll(/\[\s*\]\([^)]+\)/g);for(let O of A){let _=O.index+1;m.push({filePath:h.filePath,line:I+1,column:_,ruleId:"markdown/no-empty-links",message:"Empty link text",severity:"error"})}}return m}};var Zl={meta:{docs:"Spaces should be used instead of hard tabs"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I];if(/^(?:`{3,}|~{3,})/.test(S.trim())){R=!R;continue}if(R)continue;let L=S.indexOf("\t");if(L!==-1)m.push({filePath:h.filePath,line:I+1,column:L+1,ruleId:"markdown/no-hard-tabs",message:"Hard tabs should not be used",severity:"error"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=!1;return h.map((R)=>{if(/^(?:`{3,}|~{3,})/.test(R.trim()))return m=!m,R;if(m)return R;return R.replace(/\t/g," ")}).join(`
|
|
103
|
+
`)}};var Gl={meta:{docs:"Inline HTML should not be used"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).allowed_elements||[],S=!1;for(let L=0;L<g.length;L++){let T=g[L];if(/^(?:`{3,}|~{3,})/.test(T.trim())){S=!S;continue}if(S)continue;let A=T;A=A.replace(/``[^`]+``/g,(_)=>" ".repeat(_.length)),A=A.replace(/`[^`]+`/g,(_)=>" ".repeat(_.length));let O=A.matchAll(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi);for(let _ of O){let D=_[1].toLowerCase(),F=A.slice(_.index+1+D.length);if(F.startsWith("://")||D==="mailto"&&F.startsWith(":"))continue;if(!I.includes(D)){let N=_.index+1;m.push({filePath:h.filePath,line:L+1,column:N,ruleId:"markdown/no-inline-html",message:`Inline HTML element '<${D}>' should not be used`,severity:"warning"})}}}return m}};var Jl={meta:{docs:"ATX style headings must have a space after the hash"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let L=g[I].match(/^(#{1,6})([^\s#])/);if(L)m.push({filePath:h.filePath,line:I+1,column:L[1].length+1,ruleId:"markdown/no-missing-space-atx",message:"No space after hash on atx style heading",severity:"error"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h);return h.map((R,I)=>{if(m.has(I))return R;return R.replace(/^(#{1,6})([^\s#])/,"$1 $2")}).join(`
|
|
104
|
+
`)}};var Yl={meta:{docs:"Closed ATX style headings must have spaces inside the hashes"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let S=g[I],L=S.match(/^(#{1,6})\s+(.+?)(#{1,6})\s*$/);if(L){let A=L[1],O=L[2],_=L[3];if(!O.endsWith(" ")){let D=A.length+1+O.length;m.push({filePath:h.filePath,line:I+1,column:D,ruleId:"markdown/no-missing-space-closed-atx",message:"No space inside hashes on closed atx style heading",severity:"error"})}}let T=S.match(/^(#{1,6})(\S.+?#{1,6})\s*$/);if(T)m.push({filePath:h.filePath,line:I+1,column:T[1].length+1,ruleId:"markdown/no-missing-space-closed-atx",message:"No space inside hashes on closed atx style heading",severity:"error"})}return m}};var Xl={meta:{docs:"Multiple consecutive blank lines should not be used"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=h.options||{},I=R.maximum!==void 0?R.maximum:1,S=0;for(let L=0;L<g.length;L++)if(g[L].trim().length===0){if(S++,S>I)m.push({filePath:h.filePath,line:L+1,column:1,ruleId:"markdown/no-multiple-blanks",message:`Multiple consecutive blank lines (max ${I})`,severity:"error"})}else S=0;return m},fix:(s,h)=>{let m=h.options||{},g=m.maximum!==void 0?m.maximum:1,R=s.split(/\r?\n/),I=[],S=0;for(let L of R)if(L.trim().length===0){if(S++,S<=g)I.push(L)}else S=0,I.push(L);return I.join(`
|
|
105
|
+
`)}};var Ql={meta:{docs:"ATX style headings should have only one space after the hash"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let L=g[I].match(/^(#{1,6})\s{2,}/);if(L)m.push({filePath:h.filePath,line:I+1,column:L[1].length+1,ruleId:"markdown/no-multiple-space-atx",message:"Multiple spaces after hash on atx style heading",severity:"error"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h);return h.map((R,I)=>{if(m.has(I))return R;return R.replace(/^(#{1,6})\s{2,}/,"$1 ")}).join(`
|
|
106
|
+
`)}};var ea={meta:{docs:"Blockquote symbols should be followed by a single space"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let L=g[I].match(/^(\s*)(>+)\s{2,}/);if(L){let T=L[1].length+L[2].length+1;m.push({filePath:h.filePath,line:I+1,column:T,ruleId:"markdown/no-multiple-space-blockquote",message:"Multiple spaces after blockquote symbol",severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h);return h.map((R,I)=>{if(m.has(I))return R;return R.replace(/^(\s*>+)\s{2,}/,"$1 ")}).join(`
|
|
107
|
+
`)}};var ta={meta:{docs:"Closed ATX style headings should have only one space inside the hashes"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let S=g[I],L=S.match(/^(#{1,6})\s{2,}(?:\S.*?|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])#{1,6}\s*$/);if(L)m.push({filePath:h.filePath,line:I+1,column:L[1].length+1,ruleId:"markdown/no-multiple-space-closed-atx",message:"Multiple spaces inside hashes on closed atx style heading",severity:"error"});let T=S.match(/^#{1,6}\s+(?:\S.*?|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])\s{2,}(#{1,6})\s*$/);if(T){let A=S.lastIndexOf(T[1])-1;m.push({filePath:h.filePath,line:I+1,column:Math.max(1,A),ruleId:"markdown/no-multiple-space-closed-atx",message:"Multiple spaces inside hashes on closed atx style heading",severity:"error"})}}return m}};var na={meta:{docs:"Link syntax should not be reversed"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let L=g[I].matchAll(/\(([^)]+)\)\[(?:[^\]]+)\]/g);for(let T of L){let A=T.index+1;m.push({filePath:h.filePath,line:I+1,column:A,ruleId:"markdown/no-reversed-links",message:"Reversed link syntax: should be [text](url) not (text)[url]",severity:"error"})}}return m}};var sa={meta:{docs:"Code span elements should not have spaces inside the backticks"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){let S=g[I];if(R.has(I))continue;let L=/(`+)([\s\S]*?)\1/g;for(let T of S.matchAll(L)){let A=T[2];if(A.startsWith(" ")&&A.endsWith(" ")&&A.trim().length>0)m.push({filePath:h.filePath,line:I+1,column:T.index+1,ruleId:"markdown/no-space-in-code",message:"Spaces inside code span elements",severity:"error"})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=[];for(let R=0;R<h.length;R++){let I=h[R];if(m.has(R)){g.push(I);continue}g.push(I.replace(/(`+)([\s\S]*?)\1/g,(S,L,T)=>{if(T.startsWith(" ")&&T.endsWith(" ")&&T.trim().length>0)return`${L}${T.trim()}${L}`;return S}))}return g.join(`
|
|
108
|
+
`)}};var jd=[/(?<![A-Za-z0-9])\*\*\s+[^*]+?\*\*(?![A-Za-z0-9])/g,/(?<![A-Za-z0-9])\*\*[^*]+?\s+\*\*(?![A-Za-z0-9])/g,/(?<![A-Za-z0-9])__\s+[^_]+?__(?![A-Za-z0-9])/g,/(?<![A-Za-z0-9])__[^_]+?\s+__(?![A-Za-z0-9])/g],ia={meta:{docs:"Emphasis markers should not have spaces inside them"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){let S=g[I];if(R.has(I))continue;let L=S.replace(/`[^`]+`/g,(T)=>"\x01".repeat(T.length));for(let T of jd)for(let A of L.matchAll(T))m.push({filePath:h.filePath,line:I+1,column:A.index+1,ruleId:"markdown/no-space-in-emphasis",message:"Spaces inside emphasis markers",severity:"error"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=[];for(let R=0;R<h.length;R++){let I=h[R];if(m.has(R)){g.push(I);continue}let S=Ft(I,(L)=>{let T=L;return T=T.replace(/(?<![A-Za-z0-9])(\*\*)\s+([^*]+?)\*\*(?![A-Za-z0-9])/g,"$1$2**"),T=T.replace(/(?<![A-Za-z0-9])(\*\*)([^*]+?)\s+\*\*(?![A-Za-z0-9])/g,"$1$2**"),T=T.replace(/(?<![A-Za-z0-9])(__)\s+([^_]+?)__(?![A-Za-z0-9])/g,"$1$2__"),T=T.replace(/(?<![A-Za-z0-9])(__)([^_]+?)\s+__(?![A-Za-z0-9])/g,"$1$2__"),T});g.push(S)}return g.join(`
|
|
109
|
+
`)}};var ra={meta:{docs:"Link text should not have leading or trailing spaces"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g);for(let I=0;I<g.length;I++){if(R.has(I))continue;let L=g[I].matchAll(/\[([^\][]*)\]\([^)]*\)/g);for(let T of L){let A=T[1];if(/^\s/.test(A)||/\s$/.test(A)){let O=T.index+1;m.push({filePath:h.filePath,line:I+1,column:O,ruleId:"markdown/no-space-in-links",message:"Spaces inside link text",severity:"error"})}}}return m}};var oa={meta:{docs:"Headings should not end with punctuation"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).punctuation||".,;:!?",S=!1;for(let L=0;L<g.length;L++){let T=g[L];if(/^(?:`{3,}|~{3,})/.test(T.trim())){S=!S;continue}if(S)continue;let A=T.match(/^#{1,6}\s+(.+?)(?:\s*#+\s*)?$/);if(A){let _=A[1].trim(),D=_[_.length-1];if(D&&I.includes(D))m.push({filePath:h.filePath,line:L+1,column:T.indexOf(_)+_.length,ruleId:"markdown/no-trailing-punctuation",message:`Trailing punctuation in heading: '${D}'`,severity:"error"})}let O=L+1<g.length?g[L+1]:"";if(/^(?:=+|-+)\s*$/.test(O)&&T.trim().length>0){let _=T.trim(),D=_[_.length-1];if(D&&I.includes(D))m.push({filePath:h.filePath,line:L+1,column:T.indexOf(_)+_.length,ruleId:"markdown/no-trailing-punctuation",message:`Trailing punctuation in heading: '${D}'`,severity:"error"})}}return m},fix:(s,h)=>{let g=(h.options||{}).punctuation||".,;:!?",R=new RegExp(`[${g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}]+$`),I=s.split(/\r?\n/),S=!1;return I.map((T,A)=>{if(/^(?:`{3,}|~{3,})/.test(T.trim()))return S=!S,T;if(S)return T;let O=T.match(/^(#{1,6}\s+)(.+?)(\s*#+\s*)?$/);if(O){let D=O[1],F=O[2],N=O[3]||"",W=F.replace(R,"");return`${D}${W}${N}`}let _=A+1<I.length?I[A+1]:"";if(/^(?:=+|-+)\s*$/.test(_)&&T.trim().length>0)return T.replace(R,"");return T}).join(`
|
|
110
|
+
`)}};var la={meta:{docs:"Lines should not end with trailing spaces"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.match(/\s+$/);if(S){let L=h.options||{},T=L.br_spaces!==void 0?L.br_spaces:2;if(T===0||S[0].length!==T)m.push({filePath:h.filePath,line:R+1,column:I.length-S[0].length+1,ruleId:"markdown/no-trailing-spaces",message:`Trailing spaces found (${S[0].length} space${S[0].length!==1?"s":""})`,severity:"error"})}}return m},fix:(s,h)=>{let m=s.split(/\r?\n/),g=h.options||{},R=g.br_spaces!==void 0?g.br_spaces:2;return m.map((S)=>{let L=S.match(/\s+$/);if(L){if(R>0&&L[0].length===R)return S;return S.replace(/\s+$/,"")}return S}).join(`
|
|
111
|
+
`)}};var aa={meta:{docs:"Ordered list item prefix should follow specified style"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).style||"one_or_ordered",S=1;for(let L=0;L<g.length;L++){let T=g[L],A=T.match(/^(\s*)(\d+)\.\s+/);if(A){let O=Number.parseInt(A[2],10);if(I==="one"&&O!==1)m.push({filePath:h.filePath,line:L+1,column:A[1].length+1,ruleId:"markdown/ol-prefix",message:`Ordered list item prefix should be '1.', found '${O}.'`,severity:"error"});else if(I==="ordered"&&O!==S)m.push({filePath:h.filePath,line:L+1,column:A[1].length+1,ruleId:"markdown/ol-prefix",message:`Ordered list item prefix should be '${S}.', found '${O}.'`,severity:"error"});S++}else if(T.trim().length===0)S=1}return m},fix:(s,h)=>{let g=(h.options||{}).style||"one_or_ordered",R=s.split(/\r?\n/),I=[],S=1;for(let L of R){let T=L.match(/^(\s*)(\d+)(\.\s+)/);if(T){let A=T[1],O=T[3];if(g==="one")I.push(L.replace(/^(\s*)\d+(\.\s+)/,`${A}1${O}`));else if(g==="ordered")I.push(L.replace(/^(\s*)\d+(\.\s+)/,`${A}${S}${O}`)),S++;else I.push(L),S++}else if(I.push(L),L.trim().length===0)S=1}return I.join(`
|
|
112
|
+
`)}};var ca={meta:{docs:"Proper names should have correct capitalization"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=h.options||{},I=R.names||[],S=R.code_blocks!==!1;if(I.length===0)return m;let L=ce(g);for(let T=0;T<g.length;T++){if(L.has(T)&&!S)continue;let A=g[T];for(let O of I){let _=new RegExp(`\\b${O}\\b`,"gi"),D=A.matchAll(_);for(let F of D)if(F[0]!==O){let N=F.index+1;m.push({filePath:h.filePath,line:T+1,column:N,ruleId:"markdown/proper-names",message:`Incorrect capitalization of '${F[0]}', should be '${O}'`,severity:"error"})}}}return m}};var ua={meta:{docs:"Reference links and images should use defined labels"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=new Set;for(let L of g){let T=L.match(/^\s*\[([^\]]+)\]:\s*\S+/);if(T)R.add(T[1].toLowerCase())}let I=!1,S=!1;for(let L=0;L<g.length;L++){let T=g[L];if(/^(?:`{3,}|~{3,})/.test(T.trim())){I=!I;continue}if(I)continue;if(T.includes("<!--"))S=!0;if(T.includes("-->")){S=!1;continue}if(S)continue;if(/^\s*\[(?:[^\]]+)\]:\s*\S+/.test(T))continue;let A=T.replace(/`[^`]+`/g,(_)=>" ".repeat(_.length));A=A.replace(/!?\[[^\]]*\]\([^)]*\)/g,(_)=>" ".repeat(_.length));let O=A.matchAll(/!?\[([^\]]+)\]\[([^\]]*)\]/g);for(let _ of O){let D=(_[2].trim()||_[1]).toLowerCase();if(!R.has(D))m.push({filePath:h.filePath,line:L+1,column:_.index+1,ruleId:"markdown/reference-links-images",message:`Reference link '[${D}]' is not defined`,severity:"error"})}}return m}};var fa={meta:{docs:"Document should have required heading structure"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).headings||[];if(I.length===0)return m;let S=[];for(let T of g){let A=T.match(/^#{1,6}\s+(.+?)(?:\s*#+\s*)?$/);if(A)S.push(A[1].trim())}let L=0;for(let T=0;T<S.length&&L<I.length;T++)if(S[T]===I[L])L++;if(L<I.length)m.push({filePath:h.filePath,line:1,column:1,ruleId:"markdown/required-headings",message:`Missing required heading: '${I[L]}'`,severity:"error"});return m}};var ma={meta:{docs:"Document should have only one top-level heading (h1)"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),I=-1;for(let S=0;S<g.length;S++){if(R.has(S))continue;let L=g[S],T=S+1<g.length?g[S+1]:"",A=!1;if(/^#\s/.test(L))A=!0;if(/^=+\s*$/.test(T)&&L.trim().length>0&&!R.has(S+1))A=!0;if(A)if(I===-1)I=S+1;else m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"markdown/single-title",message:`Multiple top-level headings in the same document (first h1 on line ${I})`,severity:"error"})}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=ce(h),g=[],R=!1,I=!1;for(let S=0;S<h.length;S++){if(m.has(S)){g.push(h[S]);continue}let L=h[S],T=S+1<h.length?h[S+1]:"",A=/^#\s/.test(L),O=/^=+\s*$/.test(T)&&L.trim().length>0&&!m.has(S+1);if(A){if(!R)R=!0,g.push(L);else g.push(`#${L}`),I=!0;continue}if(O){if(!R){R=!0,g.push(L);continue}g.push(`## ${L.trim()}`),S++,I=!0;continue}g.push(L)}return I?g.join(`
|
|
113
|
+
`):s}};var ha={meta:{docs:"Files should end with a single newline character"},check:(s,h)=>{let m=[];if(!s.endsWith(`
|
|
113
114
|
`)&&!s.endsWith(`\r
|
|
114
115
|
`)){let g=s.split(/\r?\n/);m.push({filePath:h.filePath,line:g.length,column:g[g.length-1].length+1,ruleId:"markdown/single-trailing-newline",message:"File should end with a single newline character",severity:"error"})}if(s.endsWith(`
|
|
115
116
|
|
|
116
117
|
`)||s.endsWith(`\r
|
|
117
118
|
\r
|
|
118
119
|
`)){let g=s.split(/\r?\n/);m.push({filePath:h.filePath,line:g.length,column:1,ruleId:"markdown/single-trailing-newline",message:"File should end with a single newline character (not multiple)",severity:"error"})}return m},fix:(s)=>`${s.replace(/[\r\n]+$/,"")}
|
|
119
|
-
`};var
|
|
120
|
-
`):s}};var
|
|
121
|
-
`)}};function
|
|
122
|
-
`),frontmatter:g,frontmatterEndLine:m+1}}return{text:s,frontmatter:null,frontmatterEndLine:0}}function
|
|
120
|
+
`};var da={meta:{docs:"Strong style should be consistent (asterisk or underscore)"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),S=(h.options||{}).style||"consistent",L=null;for(let T=0;T<g.length;T++){if(R.has(T))continue;let A=bt(g[T]),O=A.matchAll(/\*\*([^*]+)\*\*/g);for(let D of O)if(S==="underscore")m.push({filePath:h.filePath,line:T+1,column:D.index+1,ruleId:"markdown/strong-style",message:"Expected underscore (__) for strong",severity:"error"});else if(S==="consistent"){if(L===null)L="asterisk";else if(L==="underscore")m.push({filePath:h.filePath,line:T+1,column:D.index+1,ruleId:"markdown/strong-style",message:"Strong style should be consistent throughout document",severity:"error"})}let _=A.matchAll(/__([^_]+)__/g);for(let D of _)if(S==="asterisk")m.push({filePath:h.filePath,line:T+1,column:D.index+1,ruleId:"markdown/strong-style",message:"Expected asterisk (**) for strong",severity:"error"});else if(S==="consistent"){if(L===null)L="underscore";else if(L==="asterisk")m.push({filePath:h.filePath,line:T+1,column:D.index+1,ruleId:"markdown/strong-style",message:"Strong style should be consistent throughout document",severity:"error"})}}return m},fix:(s,h)=>{let g=(h.options||{}).style||"consistent",R=s.split(/\r?\n/),I=ce(R),S="asterisk";if(g==="asterisk")S="asterisk";else if(g==="underscore")S="underscore";else if(g==="consistent"){let T=null,A=null;for(let _=0;_<R.length;_++){if(I.has(_))continue;let D=bt(R[_]);if(T===null){let F=D.match(/\*\*([^*]+)\*\*/);if(F)T={line:_,col:F.index}}if(A===null){let F=D.match(/__([^_]+)__/);if(F)A={line:_,col:F.index}}if(T&&A)break}if(T&&(!A||((_,D)=>_.line!==D.line?_.line-D.line:_.col-D.col)(T,A)<0))S="asterisk";else if(A)S="underscore"}let L=!1;for(let T=0;T<R.length;T++){if(I.has(T))continue;let A=R[T],O=Ft(A,(_)=>S==="asterisk"?_.replace(/__([^_]+)__/g,"**$1**"):_.replace(/\*\*([^*]+)\*\*/g,"__$1__"));if(O!==A)R[T]=O,L=!0}return L?R.join(`
|
|
121
|
+
`):s}};var pa={meta:{docs:"Table rows should have consistent column counts"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=-1,S=!1,L=Rt(g);for(let T=0;T<g.length;T++){let A=g[T];if(/^(?:`{3,}|~{3,})/.test(A.trim())){if(S=!S,R)R=!1,I=-1;continue}if(S)continue;let O=L.has(T)&&/\|/.test(A)&&A.trim().length>0;if(O){let _=Ud(A);if(!R)R=!0,I=_;else if(_!==I)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/table-column-count",message:`Table row has ${_} column(s), expected ${I}`,severity:"error"})}else if(A.trim().length===0||!O){if(R)R=!1,I=-1}}return m}};function Ud(s){let h=s.trim();if(h.startsWith("|"))h=h.slice(1);if(h.endsWith("|")&&!h.endsWith("\\|"))h=h.slice(0,-1);if(h==="")return 0;let m=1,g=!1,R=0,I=0;while(I<h.length){let S=h[I];if(S==="\\"&&h[I+1]==="|"){I+=2;continue}if(S==="`"){let L=0;while(h[I+L]==="`")L++;if(!g)g=!0,R=L;else if(L===R)g=!1,R=0;I+=L;continue}if(!g&&S==="|")m++;I++}return m}var ga={meta:{docs:"Table columns should have consistent alignment"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(/[-:]/.test(I)&&/\|/.test(I)){if(I.match(/^[|\s:.-]+$/)){let L=I.split("|").filter((T)=>T.trim().length>0);for(let T of L){let A=T.trim();if(!/^:?-+:?$/.test(A))m.push({filePath:h.filePath,line:R+1,column:I.indexOf(T)+1,ruleId:"markdown/table-column-style",message:"Invalid table column separator",severity:"error"})}}}}return m}};var ya={meta:{docs:"Table pipe style should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).style||"leading_and_trailing",S=!1,L=Rt(g);for(let T=0;T<g.length;T++){let A=g[T];if(/^(?:`{3,}|~{3,})/.test(A.trim())){S=!S;continue}if(S)continue;if(L.has(T)&&/\|/.test(A)&&A.trim().length>0){let O=A.trim().startsWith("|"),_=A.trim().endsWith("|");if(I==="leading_and_trailing"){if(!O||!_)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/table-pipe-style",message:"Table rows should have leading and trailing pipes",severity:"error"})}else if(I==="leading_only"){if(!O||_)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/table-pipe-style",message:"Table rows should have leading pipe only",severity:"error"})}else if(I==="trailing_only"){if(O||!_)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/table-pipe-style",message:"Table rows should have trailing pipe only",severity:"error"})}else if(I==="no_leading_or_trailing"){if(O||_)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/table-pipe-style",message:"Table rows should not have leading or trailing pipes",severity:"error"})}}}return m}};var ba={meta:{docs:"Unordered list indentation should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),I=(h.options||{}).indent||2,S=!1,L=[];for(let T=0;T<g.length;T++){let A=g[T];if(/^(?:`{3,}|~{3,})/.test(A.trim())){S=!S;continue}if(S)continue;if(A.trim()==="")continue;let O=A.match(/^(\s*)([*\-+])(\s+)/),_=A.match(/^(\s*)(\d+[.)])(\s+)/);if(!O&&!_){let z=A.match(/^(\s*)/)?.[1].length||0;while(L.length>0&&L[L.length-1].contentCol>z)L.pop();continue}let D=O||_,F=D[1].length,N=D[2],W=D[3],B=F+N.length+W.length,j=O?"ul":"ol";while(L.length>0&&F<L[L.length-1].contentCol)L.pop();if(j==="ul"){let z=L.length>0?L[L.length-1]:null;if(!z){if(F!==0&&F%I!==0)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/ul-indent",message:`Unordered list indentation should be ${I} spaces per level. Found ${F} spaces`,severity:"error"})}else if(z.type==="ul"){let K=z.contentCol,V=z.indent+I;if(F!==K&&F!==V)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"markdown/ul-indent",message:`Unordered list indentation should be ${I} spaces per level. Found ${F} spaces`,severity:"error"})}}L.push({indent:F,contentCol:B,type:j})}return m}};var xa={meta:{docs:"Unordered list style should be consistent"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=ce(g),S=(h.options||{}).style||"consistent",L=null;for(let T=0;T<g.length;T++){let A=g[T];if(R.has(T))continue;let O=A.match(/^(\s*)([*\-+])\s+/);if(O){let _=O[2];if(S==="asterisk"&&_!=="*")m.push({filePath:h.filePath,line:T+1,column:O[1].length+1,ruleId:"markdown/ul-style",message:`Expected asterisk (*) for unordered list, found '${_}'`,severity:"error"});else if(S==="dash"&&_!=="-")m.push({filePath:h.filePath,line:T+1,column:O[1].length+1,ruleId:"markdown/ul-style",message:`Expected dash (-) for unordered list, found '${_}'`,severity:"error"});else if(S==="plus"&&_!=="+")m.push({filePath:h.filePath,line:T+1,column:O[1].length+1,ruleId:"markdown/ul-style",message:`Expected plus (+) for unordered list, found '${_}'`,severity:"error"});else if(S==="consistent"){if(L===null)L=_;else if(L!==_)m.push({filePath:h.filePath,line:T+1,column:O[1].length+1,ruleId:"markdown/ul-style",message:`Unordered list style should be consistent throughout document. Expected '${L}', found '${_}'`,severity:"error"})}}}return m},fix:(s,h)=>{let g=(h.options||{}).style||"consistent",R=s.split(/\r?\n/),I=ce(R),S="*";if(g==="asterisk")S="*";else if(g==="dash")S="-";else if(g==="plus")S="+";else if(g==="consistent")for(let T=0;T<R.length;T++){if(I.has(T))continue;let A=R[T].match(/^(\s*)([*\-+])\s+/);if(A){S=A[2];break}}return R.map((T,A)=>{if(I.has(A))return T;return T.replace(/^(\s*)([*\-+])(\s+)/,`$1${S}$3`)}).join(`
|
|
122
|
+
`)}};function zd(s){let h=s.split(/\r?\n/);if(h[0]?.trim()!=="---")return{text:s,frontmatter:null,frontmatterEndLine:0};for(let m=1;m<h.length;m++)if(h[m].trim()==="---"){let g=h.slice(0,m+1);return{text:[...g.map(()=>""),...h.slice(m+1)].join(`
|
|
123
|
+
`),frontmatter:g,frontmatterEndLine:m+1}}return{text:s,frontmatter:null,frontmatterEndLine:0}}function qd(s){let h=s.split(/\r?\n/);if(h[0]?.trim()!=="---")return{header:null,body:s};for(let m=1;m<h.length;m++)if(h[m].trim()==="---")return{header:h.slice(0,m+1).join(`
|
|
123
124
|
`),body:h.slice(m+1).join(`
|
|
124
|
-
`)};return{header:null,body:s}}function
|
|
125
|
-
${I}`}:void 0}}var
|
|
125
|
+
`)};return{header:null,body:s}}function Kd(s){return{meta:s.meta,check:(h,m)=>m.filePath.endsWith(".md")?s.check(h,m):[],fix:s.fix?(h,m)=>m.filePath.endsWith(".md")?s.fix(h,m):h:void 0}}function he(s){return{meta:s.meta,check:(h,m)=>{if(!m.filePath.endsWith(".md"))return[];let{text:g,frontmatterEndLine:R}=zd(h),I=s.check(g,m);if(R>0)return I.filter((S)=>S.line>R+1);return I},fix:s.fix?(h,m)=>{if(!m.filePath.endsWith(".md"))return h;let{header:g,body:R}=qd(h);if(g===null)return s.fix(h,m);let I=s.fix(R,m);if(I===R)return h;return`${g}
|
|
126
|
+
${I}`}:void 0}}var wa={name:"markdown",rules:{"heading-increment":he(Ll),"heading-style":he(Al),"no-missing-space-atx":he(Jl),"no-multiple-space-atx":he(Ql),"no-missing-space-closed-atx":he(Yl),"no-multiple-space-closed-atx":he(ta),"blanks-around-headings":he(bl),"heading-start-left":he(Tl),"no-duplicate-heading":he(ql),"single-title":he(ma),"no-trailing-punctuation":he(oa),"ul-style":he(xa),"list-indent":he(Wl),"ul-indent":he(ba),"ol-prefix":he(aa),"list-marker-space":he(Bl),"blanks-around-lists":he(xl),"no-trailing-spaces":he(la),"no-hard-tabs":he(Zl),"no-multiple-blanks":he(Xl),"no-multiple-space-blockquote":he(ea),"no-blanks-blockquote":he(zl),"blanks-around-fences":he(yl),"single-trailing-newline":Kd(ha),"blanks-around-tables":he(kl),"no-reversed-links":he(na),"no-bare-urls":he(Ul),"no-space-in-links":he(ra),"no-empty-links":he(Hl),"link-fragments":he(Dl),"reference-links-images":he(ua),"link-image-reference-definitions":he(Fl),"link-image-style":he(Nl),"descriptive-link-text":he(Ml),"line-length":he(_l),"commands-show-output":he(Il),"fenced-code-language":he(Sl),"code-block-style":he($l),"code-fence-style":he(vl),"no-emphasis-as-heading":he(Vl),"no-space-in-emphasis":he(ia),"no-space-in-code":he(sa),"emphasis-style":he(Cl),"strong-style":he(da),"no-inline-html":he(Gl),"hr-style":he(Ol),"first-line-heading":he(El),"required-headings":he(fa),"proper-names":he(ca),"no-alt-text":he(jl),"table-pipe-style":he(ya),"table-column-count":he(pa),"table-column-style":he(ga)}};var Ra={meta:{docs:"Prefer using global Buffer instead of requiring it",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=/(?:import\b[^;\n]*\bfrom\s*|require\s*\(\s*)['"](?:node:)?buffer['"]/;for(let I=0;I<g.length;I++){let S=g[I],L=S.trim();if(L.startsWith("//")||L.startsWith("/*")||L.startsWith("*"))continue;let T=S.match(R);if(!T||T.index===void 0)continue;if(!/\bBuffer\b/.test(S))continue;m.push({filePath:h.filePath,line:I+1,column:T.index+1,ruleId:"node/prefer-global/buffer",message:"Unexpected import of 'Buffer'. Use the global 'Buffer' instead",severity:"error",help:"`Buffer` is a global in Node.js \u2014 remove the import and use it directly."})}return m}};var ka={meta:{docs:"Prefer using global process instead of requiring it",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=/(?:import\b[^;\n]*\bfrom\s*|require\s*\(\s*)['"](?:node:)?process['"]/;for(let I=0;I<g.length;I++){let S=g[I],L=S.trim();if(L.startsWith("//")||L.startsWith("/*")||L.startsWith("*"))continue;let T=S.match(R);if(!T||T.index===void 0)continue;m.push({filePath:h.filePath,line:I+1,column:T.index+1,ruleId:"node/prefer-global/process",message:"Unexpected import of 'process'. Use the global 'process' instead",severity:"error",help:"`process` is a global in Node.js \u2014 remove the import and use it directly."})}return m}};var $a={name:"node",rules:{"prefer-global/buffer":U(Ra),"prefer-global/process":U(ka)}};var Js={meta:{docs:"Enforce sorted imports (delegates to formatter check only)"},check:(s,h)=>{let m=s.split(/\r?\n/),g=0;while(g<m.length&&(/^\s*$/.test(m[g])||/^\s*\/.\/.*/.test(m[g])||/^\s*\/.\*/.test(m[g])))g++;let R=g,I=[];while(g<m.length&&/^\s*import\b/.test(m[g]))I.push(m[g].trim()),g++;if(I.length===0)return[];let S=I.join(`
|
|
126
127
|
`),L=m.slice(g).join(`
|
|
127
128
|
`),T=`${S}
|
|
128
|
-
${L}`;if(p(T)!==T)return[{filePath:h.filePath,line:R+1,column:1,ruleId:"sort-imports",message:"Imports are not sorted/grouped consistently",severity:"warning"}];return[]},fix:(s)=>p(s)};var
|
|
129
|
-
`),g=1,R=0;for(let I of h){let S=new RegExp(`"${Vd(I)}"\\s*:`);for(let L=R;L<m.length;L++)if(S.test(m[L])){g=L+1,R=L+1;break}}return g}function rt(s){return Bd(s)}function Qe(s,h){return jd(s,h)}function ve(s){let h="pkg";for(let m of s)if(/^\d+$/.test(m))h+=`[${m}]`;else if(!/^[a-z_$][a-z0-9_$]*$/i.test(m))h+=`["${m}"]`;else h+=`.${m}`;return h}function Re(s,h){if(s.publishConfig?.[h]!==void 0)return[s.publishConfig[h],["publishConfig",h]];return[s[h],[h]]}var zd=new RegExp(`(?:[\\s;]|^)(?:import[\\w,{}\\s*]*from|import\\s*['"*{]|export\\b\\s*(?:[*{]|default|type|function|const|var|let|async function)|import\\.meta\\b)`,"m"),qd=new RegExp("(?:[\\s;]|^)(?:module.exports\\b|exports\\.\\w|require\\s*\\(|global\\.\\w|Object\\.(?:defineProperty|defineProperties|assign)\\s*\\(\\s*exports\\b)","m");function kt(s){let h=Kd(s),m=zd.test(h),g=qd.test(h);if(m&&g)return"mixed";if(m)return"ESM";if(g)return"CJS";return"unknown"}function ba(s,h){if(s.endsWith(".mjs"))return"ESM";if(s.endsWith(".cjs"))return"CJS";return h==="module"?"ESM":"CJS"}function xa(s){if(s==="ESM")return".mjs";if(s==="CJS")return".cjs";return".js"}function wa(s){return s===".mjs"||s===".cjs"}function ht(s){return s.endsWith(".js")||s.endsWith(".mjs")||s.endsWith(".cjs")}function Ra(s){return/^#!\s*\//.test(s)}function Kd(s){return s.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*/g,"")}function Oe(s,h,m,g){zi(s,h,m,g)}function zi(s,h,m,g){if(typeof s==="string"){g(s,{path:h,isImports:m});return}if(Array.isArray(s)){g(s,{path:h,isImports:m});for(let R=0;R<s.length;R++)zi(s[R],h.concat(String(R)),m,g);return}if(s!==null&&typeof s==="object"){let R=Object.keys(s);g(s,{path:h,isImports:m},R);for(let I of R)zi(s[I],h.concat(I),m,g)}}function be(s,h,m,g,R,I,S){return{filePath:s,line:Ud(h,m),column:1,ruleId:g,message:R,severity:I,...S&&{help:S}}}function Vd(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var qi={meta:{docs:"Disallow deprecated jsnext:main and jsnext fields",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[];if(m["jsnext:main"]!=null)g.push(be(h.filePath,s,["jsnext:main"],"publint/deprecated-field-jsnext",'pkg["jsnext:main"] is deprecated. pkg.module should be used instead.',"warning",'The jsnext:main field is no longer recognized by modern bundlers. Use "module" instead.'));if(m.jsnext!=null)g.push(be(h.filePath,s,["jsnext"],"publint/deprecated-field-jsnext","pkg.jsnext is deprecated. pkg.module should be used instead.","warning",'The jsnext field is no longer recognized by modern bundlers. Use "module" instead.'));return g}};var Ki={meta:{docs:'Ensure "default" condition is last in exports objects',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("default"in S))return;if(T[T.length-1]!=="default")g.push(be(h.filePath,s,L.path.concat("default"),"publint/exports-default-should-be-last",`${ve(L.path.concat("default"))} should be the last condition in the object so it doesn't take precedence over the keys following it.`,"error",'Conditions are resolved in order. "default" acts as a fallback and should come last.'))}),g}};var Vi={meta:{docs:"Warn against using fallback arrays in exports",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L)=>{if(!Array.isArray(S))return;g.push(be(h.filePath,s,L.path,"publint/exports-fallback-array-use",`${ve(L.path)} uses fallback arrays which is not recommended. It works differently in some tools and may face inconsistent behaviors.`,"warning","Fallback arrays pick the first parseable value and have no practical use case in Node.js currently."))}),g}};var Hi={meta:{docs:"Ensure exports has a root entrypoint when main/module exist",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let[g]=Re(m,"main"),[R]=Re(m,"module"),[I,S]=Re(m,"exports");if(g==null&&R==null||I==null)return[];if(typeof I!=="object"||Array.isArray(I))return[];let L=Object.keys(I);if(L.length===0)return[];if(!L[0]?.startsWith("."))return[];if(L.includes("."))return[];let A=[];if(g)A.push("main");if(R)A.push("module");return[be(h.filePath,s,S,"publint/exports-missing-root-entrypoint",`${ve(S)} is missing the root entrypoint export, which is defined in pkg.${A[0]}. Environments that support "exports" will ignore pkg.${A[0]} as "exports" takes the highest priority.`,"warning",`Add ${ve(S.concat("."))} to ensure the root entrypoint is accessible.`)]}};var Zi={meta:{docs:'Ensure "module" condition precedes "require" in exports',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("module"in S)||!("require"in S))return;if(T.indexOf("module")>T.indexOf("require"))g.push(be(h.filePath,s,L.path.concat("module"),"publint/exports-module-should-precede-require",`${ve(L.path.concat("module"))} should come before the "require" condition so it can take precedence when used by a bundler.`,"error",'Bundlers prioritize conditions by order. "module" should precede "require" to ensure ESM is preferred.'))}),g}};var Gi={meta:{docs:'Ensure "types" condition is first in exports objects',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("types"in S))return;let A=T.indexOf("types");if(A===0)return;if(T.slice(0,A).filter((_)=>{if(_.startsWith("types"))return!1;if(typeof S[_]==="object"&&S[_]!==null&&ka(S[_],"types"))return!1;return!0}).length>0)g.push(be(h.filePath,s,L.path.concat("types"),"publint/exports-types-should-be-first",`${ve(L.path.concat("types"))} should be the first condition in the object so it can be resolved by TypeScript.`,"error",'TypeScript resolves conditions in order. The "types" condition must come first to ensure correct type resolution.'))}),g}};function ka(s,h){for(let m in s){if(m===h)return!0;if(typeof s[m]==="object"&&s[m]!==null&&ka(s[m],h))return!0}return!1}var Ji={meta:{docs:'Ensure exports values start with "./"',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L)=>{if(typeof S!=="string")return;if(S.startsWith("./"))return;let T=`./${S.replace(/^[/]+/,"")}`;g.push(be(h.filePath,s,L.path,"publint/exports-value-invalid",`${ve(L.path)} is "${S}" which is invalid as it does not start with "./". Use "${T}" instead.`,"error",'All exports values must be relative paths starting with "./".'))}),g}};var Hd=[{field:"main",expectTypes:["string"]},{field:"module",expectTypes:["string"]},{field:"types",expectTypes:["string"]},{field:"typings",expectTypes:["string"]},{field:"browser",expectTypes:["string","object"]},{field:"bin",expectTypes:["string","object"]},{field:"exports",expectTypes:["string","object"]},{field:"imports",expectTypes:["object"]},{field:"name",expectTypes:["string"]},{field:"version",expectTypes:["string"]},{field:"description",expectTypes:["string"]},{field:"license",expectTypes:["string"]}],Yi={meta:{docs:"Ensure package.json fields have correct value types",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[];for(let{field:R,expectTypes:I}of Hd){let[S,L]=Re(m,R);if(S==null)continue;let T=typeof S;if(!I.includes(T)){let A=I.length===1?I[0]:`${I.slice(0,-1).join(", ")} or ${I[I.length-1]}`;g.push(be(h.filePath,s,L,"publint/field-invalid-value-type",`${ve(L)} has an invalid ${T} type. Expected a ${A} type instead.`,"error",`The "${R}" field must be of type ${A}.`))}}return g}};var Xi={meta:{docs:"Suggest adding exports when module field is present",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let[g,R]=Re(m,"module"),[I]=Re(m,"exports");if(g!=null&&I==null)return[be(h.filePath,s,R,"publint/has-module-but-no-exports","pkg.module is used to output ESM, but pkg.exports is not defined. As Node.js doesn't read pkg.module, the ESM output may be skipped. Consider adding pkg.exports to export the ESM output.","warning",'Node.js only reads "exports" for module resolution. Without it, the ESM entry point in "module" is ignored by Node.js.')];return[]}};var Qi={meta:{docs:'Ensure "default" condition is last in imports objects',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"imports");if(R==null||typeof R!=="object")return[];return Oe(R,I,!0,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("default"in S))return;if(T[T.length-1]!=="default")g.push(be(h.filePath,s,L.path.concat("default"),"publint/imports-default-should-be-last",`${ve(L.path.concat("default"))} should be the last condition in the object so it doesn't take precedence over the keys following it.`,"error",'Conditions are resolved in order. "default" acts as a fallback and should come last.'))}),g}};var er={meta:{docs:'Ensure imports keys start with "#"',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"imports");if(R==null||typeof R!=="object"||Array.isArray(R))return[];for(let S of Object.keys(R))if(!S.startsWith("#")){let L=`#${S.replace(/^[/]+/,"")}`,T=I.concat(S);g.push(be(h.filePath,s,T,"publint/imports-key-invalid",`${ve(T)} is invalid as the imports key does not start with "#". Use "${L}" instead.`,"error",'All imports keys must start with "#" to distinguish them from package specifiers.'))}return g}};var tr={meta:{docs:'Ensure "module" condition precedes "require" in imports',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"imports");if(R==null||typeof R!=="object")return[];return Oe(R,I,!0,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("module"in S)||!("require"in S))return;if(T.indexOf("module")>T.indexOf("require"))g.push(be(h.filePath,s,L.path.concat("module"),"publint/imports-module-should-precede-require",`${ve(L.path.concat("module"))} should come before the "require" condition so it can take precedence when used by a bundler.`,"error",'Bundlers prioritize conditions by order. "module" should precede "require" to ensure ESM is preferred.'))}),g}};var nr={meta:{docs:'Ensure imports values start with "./"',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],[R,I]=Re(m,"imports");if(R==null||typeof R!=="object")return[];return Oe(R,I,!0,(S,L)=>{if(typeof S!=="string")return;if(!S.startsWith("."))return;if(S.startsWith("./"))return;let T=`./${S.replace(/^[/]+/,"")}`;g.push(be(h.filePath,s,L.path,"publint/imports-value-invalid",`${ve(L.path)} is "${S}" which is invalid as it does not start with "./". Use "${T}" instead.`,"error",'Relative imports values must start with "./".'))}),g}};var sr={meta:{docs:"Disallow local file references in dependencies",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],R=["dependencies","optionalDependencies","peerDependencies"];for(let I of R){let S=m[I];if(!S||typeof S!=="object")continue;for(let L of Object.keys(S)){let T=S[L];if(typeof T==="string"&&(T.startsWith("file:")||T.startsWith("link:")))g.push(be(h.filePath,s,[I,L],"publint/local-dependency",`The "${L}" dependency references "${T}" that will likely not work when installed by end-users.`,"error","Local file references (file: or link:) are not portable and will fail for consumers of the package."))}}return g}};var ir={meta:{docs:'Suggest specifying the "type" field in package.json',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];if(m.type==null)return[be(h.filePath,s,["name"],"publint/use-type",'The package does not specify the "type" field. Node.js may attempt to detect the package type causing a small performance hit. Consider adding "type": "commonjs" or "type": "module".',"warning",'Adding "type" helps Node.js resolve module format without detection overhead.')];return[]}};import{existsSync as Zd,readFileSync as Gd}from"fs";var rr={meta:{docs:"Ensure bin files have a shebang for executability",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],R=rt(h.filePath),[I,S]=Re(m,"bin");if(I==null)return[];if(typeof I==="string")$a(I,S,R,g,h.filePath,s);else if(typeof I==="object"){for(let L of Object.keys(I))if(typeof I[L]==="string")$a(I[L],S.concat(L),R,g,h.filePath,s)}return g}};function $a(s,h,m,g,R,I){let S=Qe(m,s);if(!Zd(S))return;if(!ht(s))return;let L;try{L=Gd(S,"utf8")}catch{return}if(!Ra(L))g.push(be(R,I,h,"publint/bin-file-not-executable",`${ve(h)} is "${s}" but the file is not executable. It should start with a shebang, e.g. #!/usr/bin/env node.`,"error","Bin files must start with a shebang (e.g. #!/usr/bin/env node) to be executable."))}import{existsSync as Pa,readFileSync as va}from"fs";var or={meta:{docs:'Ensure files under "module" condition in exports are ESM',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],R=rt(h.filePath),[I,S]=Re(m,"exports");if(I==null)return[];Oe(I,S,!1,(A,O)=>{if(typeof A!=="string")return;if(!O.path.includes("module"))return;if(!A.startsWith("./")&&!A.startsWith("../"))return;if(A.includes("*"))return;let _=Qe(R,A);if(!Pa(_))return;if(!ht(A))return;let D;try{D=va(_,"utf8")}catch{return}if(kt(D)==="CJS")g.push(be(h.filePath,s,O.path,"publint/exports-module-should-be-esm",`${ve(O.path)} should be ESM, but the code is written in CJS.`,"error",'The "module" condition is only used by bundlers and must contain ESM code.'))});let[L,T]=Re(m,"imports");if(L!=null&&typeof L==="object")Oe(L,T,!0,(A,O)=>{if(typeof A!=="string")return;if(!O.path.includes("module"))return;if(!A.startsWith("./"))return;if(A.includes("*"))return;let _=Qe(R,A);if(!Pa(_))return;if(!ht(A))return;let D;try{D=va(_,"utf8")}catch{return}if(kt(D)==="CJS")g.push(be(h.filePath,s,O.path,"publint/exports-module-should-be-esm",`${ve(O.path)} should be ESM, but the code is written in CJS.`,"error",'The "module" condition is only used by bundlers and must contain ESM code.'))});return g}};import{existsSync as en}from"fs";import{dirname as Jd,isAbsolute as Yd,resolve as Xd}from"path";function lr(s,h){let m=h;while(m.startsWith("./"))m=m.slice(2);let g=m.split("/")[0];if(!g||g===".."||g.startsWith("."))return!1;let R=Yd(h)?Jd(h).split("/")[0]||"/":Xd(s,g);return!en(R)}var ar={meta:{docs:"Ensure files referenced in package.json exist",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],R=rt(h.filePath),I=["main","module","types","typings","unpkg","jsdelivr"];for(let O of I){let[_,D]=Re(m,O);if(_==null||typeof _!=="string")continue;if(lr(R,_))continue;let F=Qe(R,_);if(!Ma(F))g.push(be(h.filePath,s,D,"publint/file-does-not-exist",`${ve(D)} is "${_}" but the file does not exist.`,"error","The referenced file path cannot be found. Check the path for typos."))}let[S,L]=Re(m,"bin");if(S!=null){if(typeof S==="string")Ia(S,L,g,h.filePath,s,R);else if(typeof S==="object"){for(let O of Object.keys(S))if(typeof S[O]==="string")Ia(S[O],L.concat(O),g,h.filePath,s,R)}}let[T,A]=Re(m,"exports");if(T!=null)Oe(T,A,!1,(O,_)=>{if(typeof O!=="string")return;if(!O.startsWith("./")&&!O.startsWith("../"))return;if(O.includes("*"))return;if(lr(R,O))return;let D=Qe(R,O);if(!en(D))g.push(be(h.filePath,s,_.path,"publint/file-does-not-exist",`${ve(_.path)} is "${O}" but the file does not exist.`,"error","The referenced file path cannot be found. Check the path for typos."))});return g}};function Ia(s,h,m,g,R,I){if(lr(I,s))return;let S=Qe(I,s);if(!Ma(S))m.push(be(g,R,h,"publint/file-does-not-exist",`${ve(h)} is "${s}" but the file does not exist.`,"error","The referenced file path cannot be found. Check the path for typos."))}function Ma(s){if(en(s))return!0;if(en(`${s}.js`))return!0;if(en(`${s}/index.js`))return!0;return!1}import{existsSync as Qd,readFileSync as ep}from"fs";import{extname as tp}from"path";var cr={meta:{docs:"Ensure file code format matches its extension and package type",recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let g=[],R=rt(h.filePath),I=m.type,[S,L]=Re(m,"main");if(S!=null&&typeof S==="string")Ca(S,L,R,I,g,h.filePath,s);let[T,A]=Re(m,"exports");if(T!=null)Oe(T,A,!1,(O,_)=>{if(typeof O!=="string")return;if(!O.startsWith("./")&&!O.startsWith("../"))return;if(O.includes("*"))return;if(_.path.includes("browser"))return;Ca(O,_.path,R,I,g,h.filePath,s)});return g}};function Ca(s,h,m,g,R,I,S){let L=Qe(m,s);if(!Qd(L))return;if(!ht(s))return;let T;try{T=ep(L,"utf8")}catch{return}let A=kt(T);if(A==="unknown"||A==="mixed")return;let O=ba(L,g);if(A===O)return;let _=tp(L),D=xa(A),N=(wa(_)?"FILE_INVALID_EXPLICIT_FORMAT":"FILE_INVALID_FORMAT")==="FILE_INVALID_EXPLICIT_FORMAT"?`${ve(h)} is "${s}" and ends with the ${_} extension, but the code is written in ${A}. Consider using the ${D} extension.`:`${ve(h)} is "${s}" and is written in ${A}, but is interpreted as ${O}. Consider using the ${D} extension.`;R.push(be(I,S,h,"publint/file-invalid-format",N,"warning",`The file's code format (${A}) doesn't match the expected format (${O}) based on its extension and package type.`))}import{existsSync as np,readFileSync as sp}from"fs";var ur={meta:{docs:'Ensure the "module" field points to an ESM file',recommended:!0},check(s,h){let m=ke(s);if(!m)return[];let[g,R]=Re(m,"module");if(g==null||typeof g!=="string")return[];let I=rt(h.filePath),S=Qe(I,g);if(!np(S))return[];if(!ht(g))return[];let L;try{L=sp(S,"utf8")}catch{return[]}if(kt(L)==="CJS")return[be(h.filePath,s,R,"publint/module-should-be-esm",`${ve(R)} should be ESM, but the code is written in CJS.`,"error",'The "module" field is intended for ESM output used by bundlers. It should point to an ESM file.')];return[]}};var Sa={name:"publint",rules:{"use-type":Ne(ir),"local-dependency":Ne(sr),"deprecated-field-jsnext":Ne(qi),"has-module-but-no-exports":Ne(Xi),"field-invalid-value-type":Ne(Yi),"exports-types-should-be-first":Ne(Gi),"exports-default-should-be-last":Ne(Ki),"exports-module-should-precede-require":Ne(Zi),"exports-value-invalid":Ne(Ji),"exports-missing-root-entrypoint":Ne(Hi),"exports-fallback-array-use":Ne(Vi),"imports-key-invalid":Ne(er),"imports-value-invalid":Ne(nr),"imports-default-should-be-last":Ne(Qi),"imports-module-should-precede-require":Ne(tr),"file-does-not-exist":Ne(ar),"file-invalid-format":Ne(cr),"module-should-be-esm":Ne(ur),"bin-file-not-executable":Ne(rr),"exports-module-should-be-esm":Ne(or)}};var Ea={meta:{docs:"Ensure all imports appear before other statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=0;for(let S=0;S<g.length;S++){let L=g[S].trim();if(!L||L.startsWith("//")||L.startsWith("/*")||L.startsWith("*"))continue;let T=L.match(/^\s*import\s+/);if(!T&&L.length>0){if(R=!0,I===0)I=S+1}if(R&&T)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"import/first",message:"Import statement must appear before other statements",severity:"error"})}return m}};var La={meta:{docs:"Disallow duplicate specifier names in a single import declaration"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.match(/^\s*import\s*\{([^}]*)\}\s*from\s*['"][^'"]+['"]/);if(!S)continue;let T=S[1].split(",").map((O)=>O.trim()).filter(Boolean).map((O)=>O.split(/\s+as\s+/i)[0].trim()),A=new Set;for(let O of T){if(A.has(O)){m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf(O)+1),ruleId:"pickier/import-dedupe",message:"Expect no duplication in imports",severity:"warning"});break}A.add(O)}}return m}};function Ta(s){let h=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w$])${h}(?![\\w$])`)}function ip(s,h,m){let g=[],R=/^\s*import\s+type\b/.test(s),I=s.replace(/^\s*import\s+/,"").replace(/\s+from\s+['"][^'"]+['"].*$/s,"");if(/^['"]/.test(I))return g;let S=(A,O)=>{let _=A.trim();if(!_||_==="type")return;if(!/^[A-Z_$][\w$]*$/i.test(_))return;for(let D=h;D<m.length;D++){let F=m[D].search(Ta(_));if(F!==-1){g.push({name:_,line:D+1,column:F,typeOnly:O});return}if(/\bfrom\b/.test(m[D]))break}g.push({name:_,line:h+1,column:0,typeOnly:O})},L=I.match(/\{([\s\S]*)\}/);if(L)for(let A of L[1].split(",")){let O=A.trim();if(!O)continue;let _=/^type\s+/.test(O),F=O.replace(/^type\s+/,"").split(/\s+as\s+/);S(F[F.length-1],R||_)}let T=L?I.slice(0,I.indexOf("{")):I;for(let A of T.split(",")){let O=A.trim().replace(/^type\s+/,"");if(!O)continue;let _=O.match(/^\*\s+as\s+(\w+)$/);S(_?_[1]:O,R)}return g}var Aa={meta:{docs:"Disallow imports that nothing in the file uses"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=[],I=new Set;for(let T=0;T<g.length;T++){if(!/^\s*import(?![\w$])\s*(?![(.])/.test(g[T]))continue;let A=g[T],O=T,_=Math.min(g.length-1,T+40);while(O<_&&!/\bfrom\s*['"][^'"]*['"]/.test(A)&&!/^\s*import\s*['"]/.test(A))O++,A+=`
|
|
130
|
-
${g[O]}`;if(!/\bfrom\s*['"][^'"]*['"]/.test(A)&&!/^\s*import\s*['"]/.test(A))continue;for(let D=T;D<=O;D++)I.add(D);R.push(...
|
|
131
|
-
`),L=
|
|
132
|
-
`)}};var
|
|
133
|
-
`),O=A===-1?I+1:I-A;m.push({filePath:h.filePath,line:T,column:O,ruleId:"pickier/sort-tailwind-classes",message:`Tailwind classes are not in the recommended order. Expected: "${
|
|
134
|
-
`);m.push({filePath:h.filePath,line:W,column:B,ruleId:"no-super-linear-backtracking",message:F,severity:"error"})},I=[],S=/\/\*[\s\S]*?\*\//g,L;while(L=S.exec(s))I.push({start:L.index,end:L.index+L[0].length});let T=/\/\/[^\n]*/g,A;while(A=T.exec(s))I.push({start:A.index,end:A.index+A[0].length});let O;while(O=g.exec(s)){let _=O[0],D=O.index;if(I.some((z)=>D>=z.start&&D<z.end))continue;if(D>0){let z=s[D-1];if(z===")"||z==="]"||z==="."||/[\w$]/.test(z))continue;let K=_.slice(1,_.lastIndexOf("/"));if(/^\s+\w/.test(K)&&/\w\s*\)/.test(K))continue}let F=_.slice(1,_.lastIndexOf("/")),N=F.replace(/\[.*?\]/g,"");if(N.includes(".+?\\s*")||N.includes("\\s*.+?")||N.includes(".*\\s*")||N.includes("\\s*.*")){R(D,_.length,"The combination of ' .*' or ' .+?' with '\\s*' can cause super-linear backtracking due to exchangeable characters");continue}let B=N.replace(/\s+/g,"");if(/(?:\.\*\??){2,}/.test(B)||/(?:\.\+\??){2,}/.test(B)||/\.\*\??\.\+\?|\.\+\??\.\*\?/.test(B)){R(D,_.length,"Multiple adjacent unlimited wildcard quantifiers can cause super-linear backtracking");continue}let j=F.replace(/\\./g,"_").replace(/\[[^\]]*\]/g,"_");if(/\((?:\?:)?[^)]*?[+*][^)]*\)\s*[+*]/.test(j)){R(D,_.length,"Nested unlimited quantifiers detected (e.g., (.+)+) which can cause catastrophic backtracking");continue}}return m}};function
|
|
135
|
-
`)break;S++}if(A<=h)return null;let O=s.slice(h+1,A),_=A+1;while(_<s.length&&/[gimsuvy]/.test(s[_]))_++;if(/\\[1-9]/.test(O))return null;let D=0,F=-1,N=!1;for(let W=0;W<O.length;W++){if(O[W]==="\\"){W++;continue}if(O[W]==="["&&!N){N=!0;continue}if(O[W]==="]"&&N){N=!1;continue}if(N)continue;if(O[W]==="("&&O.slice(W+1,W+3)!=="?:"&&O.slice(W+1,W+3)!=="?="&&O.slice(W+1,W+3)!=="?!"&&O.slice(W+1,W+4)!=="?<="&&O.slice(W+1,W+4)!=="?<!"){if(F<0)F=W;D++}}if(D===0)return null;return{patternStart:h,patternEnd:_,pattern:O,capCount:D,firstCapOffset:F}}function
|
|
136
|
-
`,h)+1,L=s.slice(I,h).trim().match(/(?:const|let|var)\s+(\w+)\s*=\s*$/);if(L){let T=L[1],A=s.slice(m),O=new RegExp(`\\b${T}\\.exec\\s*\\(`),_=new RegExp(`\\b${T}\\.test\\s*\\(`),D=new RegExp(`\\.match(?:All)?\\s*\\(\\s*${T}\\s*\\)`),F=new RegExp(`\\.replace(?:All)?\\s*\\(\\s*${T}`),N=O.test(A),W=D.test(A),B=F.test(A),j=_.test(A);if(N||W||B)return!0;if(j)return!1;return!0}return!0}function
|
|
137
|
-
`)break;S++}return h+1}function
|
|
138
|
-
`)R++;continue}if(I==="/"&&s[R+1]==="*"){R+=2;while(R<s.length-1&&!(s[R]==="*"&&s[R+1]==="/"))R++;R+=2;continue}if(I==="'"||I==='"'||I==="`"){let S=I;R++;while(R<s.length){if(s[R]==="\\"){R+=2;continue}if(s[R]===S){R++;break}R++}continue}if(I==="/"){let S=
|
|
139
|
-
`)+1)+1;m.push({filePath:g,line:A,column:O,ruleId:"regexp/no-unused-capturing-group",message:"Unused capturing group in regular expression; use non-capturing group (?:...) instead",severity:"error"})}R=S.patternEnd;continue}R++}return m}var
|
|
140
|
-
`)}};var
|
|
141
|
-
`)}};function
|
|
142
|
-
`)}};var
|
|
143
|
-
`)}};var
|
|
144
|
-
`)}};var
|
|
145
|
-
`)}};function
|
|
146
|
-
`)}};var
|
|
147
|
-
`)continue;if(T===" "||T==="\t"){if(I.indexOf("]",L+1)!==-1)m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/array-bracket-spacing",message:"Unexpected space after '['",severity:"warning"})}}if(I[L]==="]"&&!
|
|
148
|
-
`)}};var
|
|
129
|
+
${L}`;if(p(T)!==T)return[{filePath:h.filePath,line:R+1,column:1,ruleId:"sort-imports",message:"Imports are not sorted/grouped consistently",severity:"warning"}];return[]},fix:(s)=>p(s)};var Pa={name:"perfectionist",rules:{"sort-imports":U(Js)}};import{dirname as Vd,resolve as Hd}from"path";function Re(s){try{let h=JSON.parse(s);if(typeof h!=="object"||h===null||Array.isArray(h))return null;return h}catch{return null}}function Zd(s,h){let m=s.split(`
|
|
130
|
+
`),g=1,R=0;for(let I of h){let S=new RegExp(`"${Xd(I)}"\\s*:`);for(let L=R;L<m.length;L++)if(S.test(m[L])){g=L+1,R=L+1;break}}return g}function rt(s){return Vd(s)}function Qe(s,h){return Hd(s,h)}function Pe(s){let h="pkg";for(let m of s)if(/^\d+$/.test(m))h+=`[${m}]`;else if(!/^[a-z_$][a-z0-9_$]*$/i.test(m))h+=`["${m}"]`;else h+=`.${m}`;return h}function we(s,h){if(s.publishConfig?.[h]!==void 0)return[s.publishConfig[h],["publishConfig",h]];return[s[h],[h]]}var Gd=new RegExp(`(?:[\\s;]|^)(?:import[\\w,{}\\s*]*from|import\\s*['"*{]|export\\b\\s*(?:[*{]|default|type|function|const|var|let|async function)|import\\.meta\\b)`,"m"),Jd=new RegExp("(?:[\\s;]|^)(?:module.exports\\b|exports\\.\\w|require\\s*\\(|global\\.\\w|Object\\.(?:defineProperty|defineProperties|assign)\\s*\\(\\s*exports\\b)","m");function kt(s){let h=Yd(s),m=Gd.test(h),g=Jd.test(h);if(m&&g)return"mixed";if(m)return"ESM";if(g)return"CJS";return"unknown"}function va(s,h){if(s.endsWith(".mjs"))return"ESM";if(s.endsWith(".cjs"))return"CJS";return h==="module"?"ESM":"CJS"}function Ia(s){if(s==="ESM")return".mjs";if(s==="CJS")return".cjs";return".js"}function Ma(s){return s===".mjs"||s===".cjs"}function ht(s){return s.endsWith(".js")||s.endsWith(".mjs")||s.endsWith(".cjs")}function Ca(s){return/^#!\s*\//.test(s)}function Yd(s){return s.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*/g,"")}function Oe(s,h,m,g){Zi(s,h,m,g)}function Zi(s,h,m,g){if(typeof s==="string"){g(s,{path:h,isImports:m});return}if(Array.isArray(s)){g(s,{path:h,isImports:m});for(let R=0;R<s.length;R++)Zi(s[R],h.concat(String(R)),m,g);return}if(s!==null&&typeof s==="object"){let R=Object.keys(s);g(s,{path:h,isImports:m},R);for(let I of R)Zi(s[I],h.concat(I),m,g)}}function be(s,h,m,g,R,I,S){return{filePath:s,line:Zd(h,m),column:1,ruleId:g,message:R,severity:I,...S&&{help:S}}}function Xd(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Gi={meta:{docs:"Disallow deprecated jsnext:main and jsnext fields",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[];if(m["jsnext:main"]!=null)g.push(be(h.filePath,s,["jsnext:main"],"publint/deprecated-field-jsnext",'pkg["jsnext:main"] is deprecated. pkg.module should be used instead.',"warning",'The jsnext:main field is no longer recognized by modern bundlers. Use "module" instead.'));if(m.jsnext!=null)g.push(be(h.filePath,s,["jsnext"],"publint/deprecated-field-jsnext","pkg.jsnext is deprecated. pkg.module should be used instead.","warning",'The jsnext field is no longer recognized by modern bundlers. Use "module" instead.'));return g}};var Ji={meta:{docs:'Ensure "default" condition is last in exports objects',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("default"in S))return;if(T[T.length-1]!=="default")g.push(be(h.filePath,s,L.path.concat("default"),"publint/exports-default-should-be-last",`${Pe(L.path.concat("default"))} should be the last condition in the object so it doesn't take precedence over the keys following it.`,"error",'Conditions are resolved in order. "default" acts as a fallback and should come last.'))}),g}};var Yi={meta:{docs:"Warn against using fallback arrays in exports",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L)=>{if(!Array.isArray(S))return;g.push(be(h.filePath,s,L.path,"publint/exports-fallback-array-use",`${Pe(L.path)} uses fallback arrays which is not recommended. It works differently in some tools and may face inconsistent behaviors.`,"warning","Fallback arrays pick the first parseable value and have no practical use case in Node.js currently."))}),g}};var Xi={meta:{docs:"Ensure exports has a root entrypoint when main/module exist",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let[g]=we(m,"main"),[R]=we(m,"module"),[I,S]=we(m,"exports");if(g==null&&R==null||I==null)return[];if(typeof I!=="object"||Array.isArray(I))return[];let L=Object.keys(I);if(L.length===0)return[];if(!L[0]?.startsWith("."))return[];if(L.includes("."))return[];let A=[];if(g)A.push("main");if(R)A.push("module");return[be(h.filePath,s,S,"publint/exports-missing-root-entrypoint",`${Pe(S)} is missing the root entrypoint export, which is defined in pkg.${A[0]}. Environments that support "exports" will ignore pkg.${A[0]} as "exports" takes the highest priority.`,"warning",`Add ${Pe(S.concat("."))} to ensure the root entrypoint is accessible.`)]}};var Qi={meta:{docs:'Ensure "module" condition precedes "require" in exports',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("module"in S)||!("require"in S))return;if(T.indexOf("module")>T.indexOf("require"))g.push(be(h.filePath,s,L.path.concat("module"),"publint/exports-module-should-precede-require",`${Pe(L.path.concat("module"))} should come before the "require" condition so it can take precedence when used by a bundler.`,"error",'Bundlers prioritize conditions by order. "module" should precede "require" to ensure ESM is preferred.'))}),g}};var er={meta:{docs:'Ensure "types" condition is first in exports objects',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("types"in S))return;let A=T.indexOf("types");if(A===0)return;if(T.slice(0,A).filter((_)=>{if(_.startsWith("types"))return!1;if(typeof S[_]==="object"&&S[_]!==null&&Sa(S[_],"types"))return!1;return!0}).length>0)g.push(be(h.filePath,s,L.path.concat("types"),"publint/exports-types-should-be-first",`${Pe(L.path.concat("types"))} should be the first condition in the object so it can be resolved by TypeScript.`,"error",'TypeScript resolves conditions in order. The "types" condition must come first to ensure correct type resolution.'))}),g}};function Sa(s,h){for(let m in s){if(m===h)return!0;if(typeof s[m]==="object"&&s[m]!==null&&Sa(s[m],h))return!0}return!1}var tr={meta:{docs:'Ensure exports values start with "./"',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"exports");if(R==null)return[];return Oe(R,I,!1,(S,L)=>{if(typeof S!=="string")return;if(S.startsWith("./"))return;let T=`./${S.replace(/^[/]+/,"")}`;g.push(be(h.filePath,s,L.path,"publint/exports-value-invalid",`${Pe(L.path)} is "${S}" which is invalid as it does not start with "./". Use "${T}" instead.`,"error",'All exports values must be relative paths starting with "./".'))}),g}};var Qd=[{field:"main",expectTypes:["string"]},{field:"module",expectTypes:["string"]},{field:"types",expectTypes:["string"]},{field:"typings",expectTypes:["string"]},{field:"browser",expectTypes:["string","object"]},{field:"bin",expectTypes:["string","object"]},{field:"exports",expectTypes:["string","object"]},{field:"imports",expectTypes:["object"]},{field:"name",expectTypes:["string"]},{field:"version",expectTypes:["string"]},{field:"description",expectTypes:["string"]},{field:"license",expectTypes:["string"]}],nr={meta:{docs:"Ensure package.json fields have correct value types",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[];for(let{field:R,expectTypes:I}of Qd){let[S,L]=we(m,R);if(S==null)continue;let T=typeof S;if(!I.includes(T)){let A=I.length===1?I[0]:`${I.slice(0,-1).join(", ")} or ${I[I.length-1]}`;g.push(be(h.filePath,s,L,"publint/field-invalid-value-type",`${Pe(L)} has an invalid ${T} type. Expected a ${A} type instead.`,"error",`The "${R}" field must be of type ${A}.`))}}return g}};var sr={meta:{docs:"Suggest adding exports when module field is present",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let[g,R]=we(m,"module"),[I]=we(m,"exports");if(g!=null&&I==null)return[be(h.filePath,s,R,"publint/has-module-but-no-exports","pkg.module is used to output ESM, but pkg.exports is not defined. As Node.js doesn't read pkg.module, the ESM output may be skipped. Consider adding pkg.exports to export the ESM output.","warning",'Node.js only reads "exports" for module resolution. Without it, the ESM entry point in "module" is ignored by Node.js.')];return[]}};var ir={meta:{docs:'Ensure "default" condition is last in imports objects',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"imports");if(R==null||typeof R!=="object")return[];return Oe(R,I,!0,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("default"in S))return;if(T[T.length-1]!=="default")g.push(be(h.filePath,s,L.path.concat("default"),"publint/imports-default-should-be-last",`${Pe(L.path.concat("default"))} should be the last condition in the object so it doesn't take precedence over the keys following it.`,"error",'Conditions are resolved in order. "default" acts as a fallback and should come last.'))}),g}};var rr={meta:{docs:'Ensure imports keys start with "#"',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"imports");if(R==null||typeof R!=="object"||Array.isArray(R))return[];for(let S of Object.keys(R))if(!S.startsWith("#")){let L=`#${S.replace(/^[/]+/,"")}`,T=I.concat(S);g.push(be(h.filePath,s,T,"publint/imports-key-invalid",`${Pe(T)} is invalid as the imports key does not start with "#". Use "${L}" instead.`,"error",'All imports keys must start with "#" to distinguish them from package specifiers.'))}return g}};var or={meta:{docs:'Ensure "module" condition precedes "require" in imports',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"imports");if(R==null||typeof R!=="object")return[];return Oe(R,I,!0,(S,L,T)=>{if(!T||typeof S!=="object"||Array.isArray(S))return;if(!("module"in S)||!("require"in S))return;if(T.indexOf("module")>T.indexOf("require"))g.push(be(h.filePath,s,L.path.concat("module"),"publint/imports-module-should-precede-require",`${Pe(L.path.concat("module"))} should come before the "require" condition so it can take precedence when used by a bundler.`,"error",'Bundlers prioritize conditions by order. "module" should precede "require" to ensure ESM is preferred.'))}),g}};var lr={meta:{docs:'Ensure imports values start with "./"',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],[R,I]=we(m,"imports");if(R==null||typeof R!=="object")return[];return Oe(R,I,!0,(S,L)=>{if(typeof S!=="string")return;if(!S.startsWith("."))return;if(S.startsWith("./"))return;let T=`./${S.replace(/^[/]+/,"")}`;g.push(be(h.filePath,s,L.path,"publint/imports-value-invalid",`${Pe(L.path)} is "${S}" which is invalid as it does not start with "./". Use "${T}" instead.`,"error",'Relative imports values must start with "./".'))}),g}};var ar={meta:{docs:"Disallow local file references in dependencies",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],R=["dependencies","optionalDependencies","peerDependencies"];for(let I of R){let S=m[I];if(!S||typeof S!=="object")continue;for(let L of Object.keys(S)){let T=S[L];if(typeof T==="string"&&(T.startsWith("file:")||T.startsWith("link:")))g.push(be(h.filePath,s,[I,L],"publint/local-dependency",`The "${L}" dependency references "${T}" that will likely not work when installed by end-users.`,"error","Local file references (file: or link:) are not portable and will fail for consumers of the package."))}}return g}};var cr={meta:{docs:'Suggest specifying the "type" field in package.json',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];if(m.type==null)return[be(h.filePath,s,["name"],"publint/use-type",'The package does not specify the "type" field. Node.js may attempt to detect the package type causing a small performance hit. Consider adding "type": "commonjs" or "type": "module".',"warning",'Adding "type" helps Node.js resolve module format without detection overhead.')];return[]}};import{existsSync as ep,readFileSync as tp}from"fs";var ur={meta:{docs:"Ensure bin files have a shebang for executability",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],R=rt(h.filePath),[I,S]=we(m,"bin");if(I==null)return[];if(typeof I==="string")Ea(I,S,R,g,h.filePath,s);else if(typeof I==="object"){for(let L of Object.keys(I))if(typeof I[L]==="string")Ea(I[L],S.concat(L),R,g,h.filePath,s)}return g}};function Ea(s,h,m,g,R,I){let S=Qe(m,s);if(!ep(S))return;if(!ht(s))return;let L;try{L=tp(S,"utf8")}catch{return}if(!Ca(L))g.push(be(R,I,h,"publint/bin-file-not-executable",`${Pe(h)} is "${s}" but the file is not executable. It should start with a shebang, e.g. #!/usr/bin/env node.`,"error","Bin files must start with a shebang (e.g. #!/usr/bin/env node) to be executable."))}import{existsSync as La,readFileSync as Ta}from"fs";var fr={meta:{docs:'Ensure files under "module" condition in exports are ESM',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],R=rt(h.filePath),[I,S]=we(m,"exports");if(I==null)return[];Oe(I,S,!1,(A,O)=>{if(typeof A!=="string")return;if(!O.path.includes("module"))return;if(!A.startsWith("./")&&!A.startsWith("../"))return;if(A.includes("*"))return;let _=Qe(R,A);if(!La(_))return;if(!ht(A))return;let D;try{D=Ta(_,"utf8")}catch{return}if(kt(D)==="CJS")g.push(be(h.filePath,s,O.path,"publint/exports-module-should-be-esm",`${Pe(O.path)} should be ESM, but the code is written in CJS.`,"error",'The "module" condition is only used by bundlers and must contain ESM code.'))});let[L,T]=we(m,"imports");if(L!=null&&typeof L==="object")Oe(L,T,!0,(A,O)=>{if(typeof A!=="string")return;if(!O.path.includes("module"))return;if(!A.startsWith("./"))return;if(A.includes("*"))return;let _=Qe(R,A);if(!La(_))return;if(!ht(A))return;let D;try{D=Ta(_,"utf8")}catch{return}if(kt(D)==="CJS")g.push(be(h.filePath,s,O.path,"publint/exports-module-should-be-esm",`${Pe(O.path)} should be ESM, but the code is written in CJS.`,"error",'The "module" condition is only used by bundlers and must contain ESM code.'))});return g}};import{existsSync as nn}from"fs";import{dirname as np,isAbsolute as sp,resolve as ip}from"path";function mr(s,h){let m=h;while(m.startsWith("./"))m=m.slice(2);let g=m.split("/")[0];if(!g||g===".."||g.startsWith("."))return!1;let R=sp(h)?np(h).split("/")[0]||"/":ip(s,g);return!nn(R)}var hr={meta:{docs:"Ensure files referenced in package.json exist",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],R=rt(h.filePath),I=["main","module","types","typings","unpkg","jsdelivr"];for(let O of I){let[_,D]=we(m,O);if(_==null||typeof _!=="string")continue;if(mr(R,_))continue;let F=Qe(R,_);if(!Oa(F))g.push(be(h.filePath,s,D,"publint/file-does-not-exist",`${Pe(D)} is "${_}" but the file does not exist.`,"error","The referenced file path cannot be found. Check the path for typos."))}let[S,L]=we(m,"bin");if(S!=null){if(typeof S==="string")Aa(S,L,g,h.filePath,s,R);else if(typeof S==="object"){for(let O of Object.keys(S))if(typeof S[O]==="string")Aa(S[O],L.concat(O),g,h.filePath,s,R)}}let[T,A]=we(m,"exports");if(T!=null)Oe(T,A,!1,(O,_)=>{if(typeof O!=="string")return;if(!O.startsWith("./")&&!O.startsWith("../"))return;if(O.includes("*"))return;if(mr(R,O))return;let D=Qe(R,O);if(!nn(D))g.push(be(h.filePath,s,_.path,"publint/file-does-not-exist",`${Pe(_.path)} is "${O}" but the file does not exist.`,"error","The referenced file path cannot be found. Check the path for typos."))});return g}};function Aa(s,h,m,g,R,I){if(mr(I,s))return;let S=Qe(I,s);if(!Oa(S))m.push(be(g,R,h,"publint/file-does-not-exist",`${Pe(h)} is "${s}" but the file does not exist.`,"error","The referenced file path cannot be found. Check the path for typos."))}function Oa(s){if(nn(s))return!0;if(nn(`${s}.js`))return!0;if(nn(`${s}/index.js`))return!0;return!1}import{existsSync as rp,readFileSync as op}from"fs";import{extname as lp}from"path";var dr={meta:{docs:"Ensure file code format matches its extension and package type",recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let g=[],R=rt(h.filePath),I=m.type,[S,L]=we(m,"main");if(S!=null&&typeof S==="string")_a(S,L,R,I,g,h.filePath,s);let[T,A]=we(m,"exports");if(T!=null)Oe(T,A,!1,(O,_)=>{if(typeof O!=="string")return;if(!O.startsWith("./")&&!O.startsWith("../"))return;if(O.includes("*"))return;if(_.path.includes("browser"))return;_a(O,_.path,R,I,g,h.filePath,s)});return g}};function _a(s,h,m,g,R,I,S){let L=Qe(m,s);if(!rp(L))return;if(!ht(s))return;let T;try{T=op(L,"utf8")}catch{return}let A=kt(T);if(A==="unknown"||A==="mixed")return;let O=va(L,g);if(A===O)return;let _=lp(L),D=Ia(A),N=(Ma(_)?"FILE_INVALID_EXPLICIT_FORMAT":"FILE_INVALID_FORMAT")==="FILE_INVALID_EXPLICIT_FORMAT"?`${Pe(h)} is "${s}" and ends with the ${_} extension, but the code is written in ${A}. Consider using the ${D} extension.`:`${Pe(h)} is "${s}" and is written in ${A}, but is interpreted as ${O}. Consider using the ${D} extension.`;R.push(be(I,S,h,"publint/file-invalid-format",N,"warning",`The file's code format (${A}) doesn't match the expected format (${O}) based on its extension and package type.`))}import{existsSync as ap,readFileSync as cp}from"fs";var pr={meta:{docs:'Ensure the "module" field points to an ESM file',recommended:!0},check(s,h){let m=Re(s);if(!m)return[];let[g,R]=we(m,"module");if(g==null||typeof g!=="string")return[];let I=rt(h.filePath),S=Qe(I,g);if(!ap(S))return[];if(!ht(g))return[];let L;try{L=cp(S,"utf8")}catch{return[]}if(kt(L)==="CJS")return[be(h.filePath,s,R,"publint/module-should-be-esm",`${Pe(R)} should be ESM, but the code is written in CJS.`,"error",'The "module" field is intended for ESM output used by bundlers. It should point to an ESM file.')];return[]}};var Da={name:"publint",rules:{"use-type":Ne(cr),"local-dependency":Ne(ar),"deprecated-field-jsnext":Ne(Gi),"has-module-but-no-exports":Ne(sr),"field-invalid-value-type":Ne(nr),"exports-types-should-be-first":Ne(er),"exports-default-should-be-last":Ne(Ji),"exports-module-should-precede-require":Ne(Qi),"exports-value-invalid":Ne(tr),"exports-missing-root-entrypoint":Ne(Xi),"exports-fallback-array-use":Ne(Yi),"imports-key-invalid":Ne(rr),"imports-value-invalid":Ne(lr),"imports-default-should-be-last":Ne(ir),"imports-module-should-precede-require":Ne(or),"file-does-not-exist":Ne(hr),"file-invalid-format":Ne(dr),"module-should-be-esm":Ne(pr),"bin-file-not-executable":Ne(ur),"exports-module-should-be-esm":Ne(fr)}};var Fa={meta:{docs:"Ensure all imports appear before other statements",recommended:!1},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=!1,I=0;for(let S=0;S<g.length;S++){let L=g[S].trim();if(!L||L.startsWith("//")||L.startsWith("/*")||L.startsWith("*"))continue;let T=L.match(/^\s*import\s+/);if(!T&&L.length>0){if(R=!0,I===0)I=S+1}if(R&&T)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"import/first",message:"Import statement must appear before other statements",severity:"error"})}return m}};var Na={meta:{docs:"Disallow duplicate specifier names in a single import declaration"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.match(/^\s*import\s*\{([^}]*)\}\s*from\s*['"][^'"]+['"]/);if(!S)continue;let T=S[1].split(",").map((O)=>O.trim()).filter(Boolean).map((O)=>O.split(/\s+as\s+/i)[0].trim()),A=new Set;for(let O of T){if(A.has(O)){m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf(O)+1),ruleId:"pickier/import-dedupe",message:"Expect no duplication in imports",severity:"warning"});break}A.add(O)}}return m}};function Wa(s){let h=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w$])${h}(?![\\w$])`)}function up(s,h,m){let g=[],R=/^\s*import\s+type\b/.test(s),I=s.replace(/^\s*import\s+/,"").replace(/\s+from\s+['"][^'"]+['"].*$/s,"");if(/^['"]/.test(I))return g;let S=(A,O)=>{let _=A.trim();if(!_||_==="type")return;if(!/^[A-Z_$][\w$]*$/i.test(_))return;for(let D=h;D<m.length;D++){let F=m[D].search(Wa(_));if(F!==-1){g.push({name:_,line:D+1,column:F,typeOnly:O});return}if(/\bfrom\b/.test(m[D]))break}g.push({name:_,line:h+1,column:0,typeOnly:O})},L=I.match(/\{([\s\S]*)\}/);if(L)for(let A of L[1].split(",")){let O=A.trim();if(!O)continue;let _=/^type\s+/.test(O),F=O.replace(/^type\s+/,"").split(/\s+as\s+/);S(F[F.length-1],R||_)}let T=L?I.slice(0,I.indexOf("{")):I;for(let A of T.split(",")){let O=A.trim().replace(/^type\s+/,"");if(!O)continue;let _=O.match(/^\*\s+as\s+(\w+)$/);S(_?_[1]:O,R)}return g}var Ba={meta:{docs:"Disallow imports that nothing in the file uses"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=[],I=new Set;for(let T=0;T<g.length;T++){if(!/^\s*import(?![\w$])\s*(?![(.])/.test(g[T]))continue;let A=g[T],O=T,_=Math.min(g.length-1,T+40);while(O<_&&!/\bfrom\s*['"][^'"]*['"]/.test(A)&&!/^\s*import\s*['"]/.test(A))O++,A+=`
|
|
131
|
+
${g[O]}`;if(!/\bfrom\s*['"][^'"]*['"]/.test(A)&&!/^\s*import\s*['"]/.test(A))continue;for(let D=T;D<=O;D++)I.add(D);R.push(...up(A,T,g)),T=O}if(R.length===0)return m;let S=g.map((T,A)=>I.has(A)?"":T).join(`
|
|
132
|
+
`),L=el(S);for(let T of R){if(Wa(T.name).test(L))continue;m.push({filePath:h.filePath,line:T.line,column:T.column+1,ruleId:"pickier/no-unused-imports",message:T.typeOnly?`'${T.name}' is imported as a type but never used`:`'${T.name}' is imported but never used`,severity:"error"})}return m}};import{existsSync as fp,readFileSync as mp}from"fs";import{dirname as hp,resolve as dp}from"path";var ja={meta:{docs:"Ensure named imports correspond to a named export in the remote file",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=hp(h.filePath);for(let I=0;I<g.length;I++){let L=g[I].match(/\bimport\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(L){let T=L[1].split(",").map((D)=>D.trim().split(/\s+as\s+/)[0].trim()),A=L[2];if(!A.startsWith(".")&&!A.startsWith("/"))continue;let O=[".ts",".tsx",".js",".jsx",""],_="";for(let D of O){let F=dp(R,A+D);if(fp(F)){_=mp(F,"utf8");break}}if(_)for(let D of T){let F=new RegExp(`\\bexport\\s+(?:const|let|var|function|class)\\s+${D}\\b`),N=new RegExp(`\\bexport\\s+\\{[^}]*\\b${D}\\b[^}]*\\}`);if(![F,N].some((j)=>j.test(_)))m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"import/named",message:`'${D}' not found in '${A}'`,severity:"error"})}}}return m}};import{existsSync as Ua,readFileSync as pp}from"fs";import{dirname as za,resolve as qa}from"path";var Ka={meta:{docs:"Ensure imports don't create circular dependencies",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=h.filePath,I=new Set,S=new Set;function L(A,O){if(S.has(A))return!0;if(I.has(A))return!1;I.add(A),S.add(A);try{let _=pp(A,"utf8"),D=T(_,za(A));for(let F of D)if(L(F,[...O,F]))return!0}catch{}return S.delete(A),!1}function T(A,O){let _=[],D=/\bimport(?:\s{2,}|\s+\S.*?(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))from\s+['"]([^'"]+)['"]/g,F;for(F=D.exec(A);F!==null;F=D.exec(A)){let N=F[1];if(N.startsWith(".")||N.startsWith("/")){let W=[".ts",".tsx",".js",".jsx",""];for(let B of W){let j=qa(O,N+B);if(Ua(j)){_.push(j);break}}}}return _}for(let A=0;A<g.length;A++){let _=g[A].match(/\bimport(?:\s{2,}|\s+\S.*?(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))from\s+['"]([^'"]+)['"]/);if(_){let D=_[1];if(D.startsWith(".")||D.startsWith("/")){let F=[".ts",".tsx",".js",".jsx",""],N="";for(let W of F){let B=qa(za(R),D+W);if(Ua(B)){N=B;break}}if(N){if(I.clear(),S.clear(),S.add(R),L(N,[R,N]))m.push({filePath:h.filePath,line:A+1,column:1,ruleId:"import/no-cycle",message:"Dependency cycle detected",severity:"error"})}}}}return m}};var Va={meta:{docs:"Disallow duplicate module imports - all imports from the same module should be combined"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=new Map,I=!1;for(let S=0;S<g.length;S++){let L=g[S];if(I){let F=L.indexOf("*/");if(F>=0)L=L.slice(F+2),I=!1;else continue}let T=L.indexOf("/*"),A=L.indexOf("//");if(T>=0&&(A===-1||T<A)){let F=L.indexOf("*/",T+2);if(F>=0)L=L.slice(0,T)+L.slice(F+2);else I=!0,L=L.slice(0,T)}if(A>=0)L=L.slice(0,A);let O=L.trim();if(!O)continue;let _=O.match(/^import\s+(?:type\s+)?(?:\{[^}]*\}|[\w$]+(?:\s*,\s*\{[^}]*\})?|\*\s+as\s+[\w$]+)\s+from\s+(['"`])(.+?)\1/);if(_){let F=_[2];if(R.has(F)){let N=R.get(F);m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"no-duplicate-imports",message:`'${F}' imported multiple times (also imported on line${N.length>1?"s":""} ${N.join(", ")})`,severity:"error",help:`Combine all imports from '${F}' into a single import statement`}),N.push(S+1)}else R.set(F,[S+1])}let D=O.match(/^export\s+(?:type\s+)?(?:\{[^}]*\}|\*(?:\s+as\s+[\w$]+)?)\s+from\s+(['"`])(.+?)\1/);if(D){let F=D[2],N=`export:${F}`;if(R.has(N)){let W=R.get(N);m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"no-duplicate-imports",message:`'${F}' re-exported multiple times (also exported on line${W.length>1?"s":""} ${W.join(", ")})`,severity:"error",help:`Combine all re-exports from '${F}' into a single export statement`}),W.push(S+1)}else R.set(N,[S+1])}}return m}};var Ha={meta:{docs:"Disallow importing from dist directories"},check:(s,h)=>{let m=[],g=new RegExp(`^\\s*import\\s[^;]*?from\\s*['"]([^'"]+)['"]`,"m"),R=s.split(/\r?\n/);for(let I=0;I<R.length;I++){let S=R[I],L=S.match(g);if(!L)continue;let T=L[1];if(T==="dist"||(T.startsWith(".")||T.startsWith("/"))&&/(?:^|\/)dist(?:\/.|$)/.test(T))m.push({filePath:h.filePath,line:I+1,column:Math.max(1,S.indexOf(T)+1),ruleId:"pickier/no-import-dist",message:`Do not import modules in \`dist\` folder, got ${T}`,severity:"error"})}return m}};var Za={meta:{docs:"Disallow importing from node_modules by explicit path"},check:(s,h)=>{let m=[],g=new RegExp(`^\\s*import\\s[^;]*?from\\s*['"]([^'"]+)['"]`,"m"),R=/require\(\s*['"]([^'"]+)['"]\s*\)/,I=s.split(/\r?\n/);for(let S=0;S<I.length;S++){let L=I[S],T=L.match(g),A=L.match(R),O=T?.[1]||A?.[1];if(!O)continue;if(O.includes("/node_modules/")){let _=Math.max(1,L.indexOf(O)+1);m.push({filePath:h.filePath,line:S+1,column:_,ruleId:"pickier/no-import-node-modules-by-path",message:"Do not import modules in `node_modules` folder by path",severity:"error"})}}return m}};import{existsSync as gp}from"fs";import{dirname as yp,join as bp,resolve as xp}from"path";var Ga={meta:{docs:"Ensure imports point to a file/module that can be resolved",recommended:!0},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=yp(h.filePath);for(let I=0;I<g.length;I++){let S=g[I],L=[...S.matchAll(/\bimport(?:\s{2,}|\s+\S.*?(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))from\s+['"]([^'"]+)['"]/g),...S.matchAll(/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g),...S.matchAll(/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g)];for(let T of L){let A=T[1];if(!A.startsWith(".")&&!A.startsWith("/"))continue;let O=[],_=[".ts",".tsx",".js",".jsx",".mjs",".cjs",""];for(let F of _){let N=xp(R,A+F);O.push(N),O.push(bp(N,`index${F}`))}if(!O.some((F)=>gp(F)))m.push({filePath:h.filePath,line:I+1,column:1,ruleId:"import/no-unresolved",message:`Unable to resolve path to module '${A}'`,severity:"error"})}}return m}};function Ja(s,h,m){let g=m.order==="desc"?-1:1,R=m.type||"alphabetical",I=m.ignoreCase?s.toLowerCase():s,S=m.ignoreCase?h.toLowerCase():h;if(R==="line-length")return(I.length-S.length)*g;if(R==="natural")return I.localeCompare(S,void 0,{numeric:!0,sensitivity:"base"})*g;if(R==="unsorted")return 0;return I.localeCompare(S)*g}var wp=new RegExp(`^export\\s+\\{[^}]*\\}\\s+from\\s+['"][^'"]+['"];?\\s*$`);function Ys(s){return wp.test(s)}var Ya={meta:{docs:"Ensure contiguous export statements are sorted consistently."},check:(s,h)=>{let m=[],g=h.config.pluginRules?.["pickier/sort-exports"]?.[1]||{},R=s.split(/\r?\n/),I=0;while(I<R.length){while(I<R.length&&!Ys(R[I]))I++;if(I>=R.length)break;let S=[],L=I;while(L<R.length){let T=R[L];if(Ys(T)){S.push({idx:L,line:T}),L++;continue}if(g.partitionByNewLine&&T.trim()==="")break;else break}if(S.length>1){let T=S.map((_)=>_.line),A=[...T].sort((_,D)=>Ja(_,D,g));if(!T.every((_,D)=>_===A[D])){let _=T.findIndex((F,N)=>F!==A[N]),D=S[_]?.idx??S[0].idx;m.push({filePath:h.filePath,line:D+1,column:1,ruleId:"pickier/sort-exports",message:"Export statements are not sorted.",severity:"warning"})}}I=L+1}return m},fix:(s,h)=>{let m=h.config.pluginRules?.["pickier/sort-exports"]?.[1]||{},R=[...s.split(/\r?\n/)],I=0;while(I<R.length){while(I<R.length&&!Ys(R[I]))I++;if(I>=R.length)break;let S=[],L=I;while(L<R.length){let T=R[L];if(Ys(T)){S.push(L),L++;continue}if(m.partitionByNewLine&&T.trim()==="")break;else break}if(S.length>1){let T=S.map((_)=>R[_]),A=[...T].sort((_,D)=>Ja(_,D,m));if(!T.every((_,D)=>_===A[D]))S.forEach((_,D)=>{R[_]=A[D]})}I=L+1}return R.join(`
|
|
133
|
+
`)}};var Xa={meta:{docs:"Enforce sorted TypeScript heritage clauses (extends/implements lists)"},check:(s,h)=>{let m=h.options||{},g=m.type||"alphabetical",R=m.order||"asc",I=m.ignoreCase!==!1,S=Array.isArray(m.groups)?m.groups:[],L=m.customGroups||{},T=s.split(/\r?\n/),A=[],O=(V)=>R==="asc"?V:-V,_=(V,G)=>(I?V.toLowerCase():V).localeCompare(I?G.toLowerCase():G),D=(V,G)=>(I?V.toLowerCase():V).localeCompare(I?G.toLowerCase():G,void 0,{numeric:!0}),F=(V,G)=>{if(g==="line-length")return O(V.length-G.length);if(g==="natural")return O(D(V,G));if(g==="unsorted")return 0;return O(_(V,G))},N=Object.fromEntries(Object.entries(L).map(([V,G])=>{let Y=(Array.isArray(G)?G:[G]).map((se)=>new RegExp(se));return[V,Y]})),W=[];for(let V of S)if(Array.isArray(V))W.push(...V);else W.push(V);if(!W.includes("unknown"))W.push("unknown");let B=(V)=>{for(let[G,J]of Object.entries(N))if(J.some((Y)=>Y.test(V)))return G;return"unknown"},j=(V)=>{let G=[],J=0,Y="";for(let se=0;se<V.length;se++){let Z=V[se];if(Z==="<")J++;else if(Z===">")J=Math.max(0,J-1);if(Z===","&&J===0){G.push(Y.trim()),Y="";continue}Y+=Z}if(Y.trim())G.push(Y.trim());return G},z=(V)=>{let G=V.trim(),J=G.match(/^([A-Z_$][\w$.]*)/i);return J?J[1]:G},K=(V,G)=>{let J=j(G);if(J.length<=1)return;let Y=J.map(z),se=Y.map(B),Z=Y.map((ee,oe)=>({n:ee,g:se[oe],i:oe})).sort((ee,oe)=>{let X=W.indexOf(ee.g),te=W.indexOf(oe.g);if(X!==te)return X-te;return F(ee.n,oe.n)}).map((ee)=>ee.n);if(!Y.every((ee,oe)=>ee===Z[oe]))A.push({filePath:h.filePath,line:V,column:1,ruleId:"sort-heritage-clauses",message:"Heritage clauses are not sorted",severity:"warning"})};for(let V=0;V<T.length;V++){let G=T[V],J=G.match(/^\s*interface\s+[A-Za-z_$][^{]*\bextends\s+(.+?)\s*\{/);if(J)K(V+1,J[1]);let Y=G.match(/^\s*class\s+[A-Za-z_$][^{]*\bimplements\s+(.+?)\s*\{/);if(Y)K(V+1,Y[1])}return A}};var Qa={meta:{docs:"Require object keys to be sorted (ESLint-compatible core rule subset)"},check:()=>[]};var ec={meta:{docs:"Enforce sorted named imports within each import statement"},check:(s,h)=>{let m=h.options||{},g=m.type||"alphabetical",R=m.order||"asc",I=m.ignoreCase!==!1,S=Boolean(m.ignoreAlias),L=s.split(/\r?\n/),T=[],A=(O,_)=>{let D=0;if(g==="line-length")D=O.length-_.length;else{let F=I?O.toLowerCase():O,N=I?_.toLowerCase():_;D=F.localeCompare(N)}return R==="asc"?D:-D};for(let O=0;O<L.length;O++){let D=L[O].match(/^\s*import\s+\{([^}]*)\}\s+from\s+['"][^'"]+['"]/);if(!D)continue;let N=D[1].split(",").map((z)=>z.trim()).filter(Boolean);if(N.length<=1)continue;let W=N.map((z)=>{let K=z.replace(/^type\s+/,""),V=K.match(/^([\w$]+)\s+as\s+([\w$]+)$/);if(V)return S?V[2]:V[1];let G=K.match(/^([\w$]+)$/);return G?G[1]:K}),B=[...W].sort(A);if(!W.every((z,K)=>z===B[K]))T.push({filePath:h.filePath,line:O+1,column:1,ruleId:"sort-named-imports",message:"Named imports are not sorted",severity:"warning"})}return T}};var tc={meta:{docs:"Enforce sorted object keys"},check:(s,h)=>{let m=h.options||{},g=m.type||"alphabetical",R=m.order||"asc",I=m.ignoreCase!==!1,S=Boolean(m.partitionByNewLine),L=s.split(/\r?\n/),T=[],A=(_,D)=>{let F=0;if(g==="line-length")F=_.length-D.length;else{let N=I?_.toLowerCase():_,W=I?D.toLowerCase():D;F=N.localeCompare(W)}return R==="asc"?F:-F},O=0;while(O<L.length){let _=L[O],D=_.indexOf("{");if(D!==-1){let F=_.slice(0,D);if(/=\s*$|\(\s*$|\breturn\s*$/.test(F)){let N=0,W=O,B=O;for(;B<L.length;B++){for(let j of L[B])if(j==="{")N++;else if(j==="}")N--;if(N===0)break}if(B>W){let j=L.slice(W+1,B),z=[],K={startLine:W+2,props:[]},V=()=>{if(K.props.length)z.push(K);K={startLine:0,props:[]}};for(let G=0;G<j.length;G++){let J=j[G];if(S&&/^\s*$/.test(J)){V();continue}if(/^\s*\.\.\./.test(J))continue;if(/\{|\}/.test(J))continue;let Y=J.match(/^\s*['"]?([\w$-]+)['"]?\s*:/);if(Y){if(K.startLine===0)K.startLine=W+2+G;K.props.push({key:Y[1],line:W+2+G})}}V();for(let G of z){let J=G.props.map((Z)=>Z.key),Y=[...J].sort(A);if(!(J.length<=1||J.every((Z,re)=>Z===Y[re]))&&G.props.length>0){let Z=G.props[0];T.push({filePath:h.filePath,line:Z.line,column:1,ruleId:"sort-objects",message:"Object keys are not sorted",severity:"warning"})}}O=B+1;continue}}}O++}return T}};var nc={meta:{docs:"Enforce top-level functions to use function declarations"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(/^\s+/.test(I))continue;if(/^\s*(?:\/\/|\/\*)/.test(I))continue;let S=I.match(/^const\s+([A-Za-z_$][\w$]*)\s*=(.*)$/);if(!S)continue;let L=S[2].trim();if(/^\(?[A-Z_$,]*(?:\)\s*)?=>/i.test(L)||/^function\b/.test(L)){let T=I.indexOf("const")+1;m.push({filePath:h.filePath,line:R+1,column:T,ruleId:"pickier/top-level-function",message:"Top-level functions should be declared with function keyword",severity:"warning"});continue}if(L.trim().length===0||/[,({]$/.test(L.trim())){let T=g[R+1]||"";if(/^\s*(?:\(?[A-Za-z_$,]*(?:\)\s*)?=>|function\b)/.test(T)){let A=I.indexOf("const")+1;m.push({filePath:h.filePath,line:R+1,column:A,ruleId:"pickier/top-level-function",message:"Top-level functions should be declared with function keyword",severity:"warning"})}}}return m}};var Rp=[[/^(block|inline|inline-block|flex|inline-flex|grid|inline-grid|flow-root|contents|hidden|table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|list-item|subgrid)$/,0],[/^(container|columns|break-after|break-before|break-inside|box-decoration|box-border|box-content|float|clear|isolation|object|overflow|overscroll|position|inset|top|right|bottom|left|start|end|z-|aspect|order)/,1],[/^(static|fixed|absolute|relative|sticky)$/,1],[/^(visible|invisible|collapse)$/,1],[/^(basis|flex-|grow|shrink|order|grid-|col-|row-|auto-cols|auto-rows|gap|justify|items|content|self|place)/,2],[/^(p|px|py|ps|pe|pt|pr|pb|pl|m|mx|my|ms|me|mt|mr|mb|ml|space|indent)-/,3],[/^(-?(p|px|py|ps|pe|pt|pr|pb|pl|m|mx|my|ms|me|mt|mr|mb|ml|space|indent)-)/,3],[/^(w-|h-|min-w|max-w|min-h|max-h|size-)/,4],[/^(font|text|tracking|leading|list|placeholder|vertical|whitespace|break|hyphens|content|truncate|overflow-ellipsis|overflow-clip|line-clamp|underline|overline|line-through|no-underline|uppercase|lowercase|capitalize|normal-case|italic|not-italic|ordinal|slashed-zero|lining-nums|oldstyle-nums|proportional-nums|tabular-nums|diagonal-fractions|stacked-fractions|normal-nums|antialiased|subpixel-antialiased)/,5],[/^(bg-|from-|via-|to-|gradient-)/,6],[/^(border|rounded|outline|ring|divide|accent)/,7],[/^(shadow|opacity|mix-blend|bg-blend)/,8],[/^(blur|brightness|contrast|drop-shadow|grayscale|hue-rotate|invert|saturate|sepia|backdrop)/,9],[/^(border-collapse|border-separate|border-spacing|table-auto|table-fixed|caption)/,10],[/^(transition|duration|ease|delay|animate)/,11],[/^(scale|rotate|translate|skew|origin|transform|perspective)/,12],[/^(appearance|cursor|caret|pointer-events|resize|scroll|snap|touch|select|will-change)/,13],[/^(fill|stroke)/,14],[/^(sr-only|not-sr-only)$/,15]],kp=/^([a-z0-9][-a-z0-9]{0,50}:)+(?!\[)/;function $p(s){let h=0;while(h<s.length){if(s[h]==="[")break;let m=s.indexOf(":",h);if(m===-1)break;if(s[m+1]==="[")break;h=m+1}return s.slice(h)}function Pp(s){let h=$p(s);if(h.startsWith("!"))h=h.slice(1);for(let[m,g]of Rp)if(m.test(h))return g;return 99}function vp(s){let h=s.match(kp);if(!h)return 0;let m=h[0].slice(0,-1).split(":"),g={sm:1,md:2,lg:3,xl:4,"2xl":5},R=10;for(let I of m)if(g[I]!==void 0)R+=g[I];else R+=20;return R}var sc=new Map;function ic(s){let h=sc.get(s);if(h)return h;let m={group:Pp(s),variant:vp(s)};return sc.set(s,m),m}function gr(s){return[...s].sort((h,m)=>{let g=ic(h),R=ic(m),I=g.group,S=R.group;if(I!==S)return I-S;let L=g.variant,T=R.variant;if(L!==T)return L-T;return h.localeCompare(m)})}var Ip=/\b(?:class|className|:class)\s*=\s*(?:"([^"]*?)"|'([^']*?)')/g,Mp=/\b(?:class|className|:class)\s*=\s*\{`([^`]*?)`\}/g,Cp=/\b(?:clsx|cn|tw|cva|tv)\s*\(\s*(?:"([^"]*?)"|'([^']*?)')/g;function Sp(s){let h=s.replace(/\[[^\]]*\]/g,"");if(/['"`]/.test(h))return!0;if(/[{}()=]/.test(h))return!0;if(/ \? | && | \|\| /.test(h))return!0;if(/\b(?:true|false|null|undefined|function|return|typeof|instanceof)\b/.test(h))return!0;return!1}function rc(s){let h=[];if(!s.includes("class")&&!s.includes("clsx")&&!s.includes("cn(")&&!s.includes("tw(")&&!s.includes("cva(")&&!s.includes("tv("))return h;for(let m of[Ip,Mp,Cp]){m.lastIndex=0;let g;while((g=m.exec(s))!==null){let R=g[1]??g[2]??"";if(!R.trim())continue;if(Sp(R))continue;let I=s.indexOf(R,g.index);if(I===-1)continue;h.push({value:R,start:I,end:I+R.length})}}return h.sort((m,g)=>m.start-g.start),h}function oc(s){let h=[],m="",g=0;for(let R of s)if(R==="[")g++,m+=R;else if(R==="]")g=Math.max(0,g-1),m+=R;else if(/\s/.test(R)&&g===0){if(m)h.push(m),m=""}else m+=R;if(m)h.push(m);return h}function lc(s){let h=gr(s);return s.every((m,g)=>m===h[g])}var ac={meta:{docs:"Enforce consistent Tailwind CSS class ordering (layout \u2192 spacing \u2192 typography \u2192 etc.).",recommended:!0,editsStringContent:!0},check:(s,h)=>{let m=[],g=rc(s);for(let{value:R,start:I}of g){let S=oc(R);if(S.length<2)continue;if(!lc(S)){let L=s.slice(0,I),T=(L.match(/\n/g)??[]).length+1,A=L.lastIndexOf(`
|
|
134
|
+
`),O=A===-1?I+1:I-A;m.push({filePath:h.filePath,line:T,column:O,ruleId:"pickier/sort-tailwind-classes",message:`Tailwind classes are not in the recommended order. Expected: "${gr(S).join(" ")}"`,severity:"warning",help:"Run with --fix to automatically sort Tailwind classes, or reorder them manually."})}}return m},fix:(s)=>{let h=rc(s);if(h.length===0)return s;let m=[...h].reverse(),g=s;for(let{value:R,start:I,end:S}of m){let L=oc(R);if(L.length<2||lc(L))continue;let T=gr(L).join(" ");g=g.slice(0,I)+T+g.slice(S)}return g}};var cc={name:"pickier",rules:{"sort-exports":U(Ya),"sort-objects":U(tc),"sort-imports":U(Js),"sort-named-imports":U(ec),"sort-heritage-clauses":U(Xa),"sort-keys":U(Qa),"import-dedupe":U(Na),"no-unused-imports":U(Ba),"import-first":U(Fa),"import-named":U(ja),"import-no-cycle":U(Ka),"import-no-unresolved":U(Ga),"no-import-dist":U(Ha),"no-import-node-modules-by-path":U(Za),"no-duplicate-imports":U(Va),"top-level-function":U(nc),"sort-tailwind-classes":ac,"prefer-const":U(Hs),"prefer-template":U(Zs),"no-unused-vars":U(gt)}};var uc={name:"quality",rules:{"default-case":U(ls),eqeqeq:U(as),"no-alert":U(fs),"no-await-in-loop":U(ms),"no-caller":U(hs),"no-case-declarations":U(ds),"no-else-return":U(ps),"no-empty":U(gs),"no-empty-function":U(ys),"no-eval":U(bs),"no-extend-native":U(xs),"no-global-assign":U(Rs),"no-implied-eval":U(ks),"no-iterator":U($s),"no-new":U(Ps),"no-new-func":U(vs),"no-new-wrappers":U(Is),"no-octal":U(Ms),"no-param-reassign":U(Cs),"no-proto":U(Ss),"no-return-assign":U(Es),"no-shadow":U(Ts),"no-throw-literal":U(As),"no-use-before-define":U(Fs),"no-useless-call":U(Ns),"no-with":U(zs),"require-await":U(Ks),complexity:U(os),"max-depth":U(cs),"max-lines-per-function":U(us),"no-extra-boolean-cast":U(ws),"no-lonely-if":U(Xt),"no-sequences":U(Ls),"no-useless-concat":U(Ws),"no-useless-escape":U(Bs),"no-useless-rename":U(js),"no-useless-return":U(en),"no-var":U(Us),"prefer-arrow-callback":U(qs)}};var fc={meta:{docs:"Detects potentially super-linear backtracking patterns in regex literals (heuristic)"},check:(s,h)=>{let m=[],g=/\/[^/\\\n]*(?:\\.[^/\\\n]*)*\//g,R=(_,D,F)=>{let N=s.slice(0,_),W=(N.match(/\n/g)||[]).length+1,B=_-N.lastIndexOf(`
|
|
135
|
+
`);m.push({filePath:h.filePath,line:W,column:B,ruleId:"no-super-linear-backtracking",message:F,severity:"error"})},I=[],S=/\/\*[\s\S]*?\*\//g,L;while(L=S.exec(s))I.push({start:L.index,end:L.index+L[0].length});let T=/\/\/[^\n]*/g,A;while(A=T.exec(s))I.push({start:A.index,end:A.index+A[0].length});let O;while(O=g.exec(s)){let _=O[0],D=O.index;if(I.some((z)=>D>=z.start&&D<z.end))continue;if(D>0){let z=s[D-1];if(z===")"||z==="]"||z==="."||/[\w$]/.test(z))continue;let K=_.slice(1,_.lastIndexOf("/"));if(/^\s+\w/.test(K)&&/\w\s*\)/.test(K))continue}let F=_.slice(1,_.lastIndexOf("/")),N=F.replace(/\[.*?\]/g,"");if(N.includes(".+?\\s*")||N.includes("\\s*.+?")||N.includes(".*\\s*")||N.includes("\\s*.*")){R(D,_.length,"The combination of ' .*' or ' .+?' with '\\s*' can cause super-linear backtracking due to exchangeable characters");continue}let B=N.replace(/\s+/g,"");if(/(?:\.\*\??){2,}/.test(B)||/(?:\.\+\??){2,}/.test(B)||/\.\*\??\.\+\?|\.\+\??\.\*\?/.test(B)){R(D,_.length,"Multiple adjacent unlimited wildcard quantifiers can cause super-linear backtracking");continue}let j=F.replace(/\\./g,"_").replace(/\[[^\]]*\]/g,"_");if(/\((?:\?:)?[^)]*?[+*][^)]*\)\s*[+*]/.test(j)){R(D,_.length,"Nested unlimited quantifiers detected (e.g., (.+)+) which can cause catastrophic backtracking");continue}}return m}};function Ep(s,h){let m=h-1;while(m>=0&&(s[m]===" "||s[m]==="\t"))m--;let g=m>=0?s[m]:"",R="=(<>!&|?:;,{[+(~^%*/";if(!(m<0||R.includes(g)||/\b(?:return|typeof|void|delete|throw|new|in|of|case)\s*$/.test(s.slice(Math.max(0,m-5),m+1))))return null;let S=h+1,L=!1,T=!1,A=-1;while(S<s.length){let W=s[S];if(T)T=!1;else if(W==="\\")T=!0;else if(W==="["){if(!L)L=!0}else if(W==="]"){if(L)L=!1}else if(W==="/"&&!L){A=S;break}else if(W===`
|
|
136
|
+
`)break;S++}if(A<=h)return null;let O=s.slice(h+1,A),_=A+1;while(_<s.length&&/[gimsuvy]/.test(s[_]))_++;if(/\\[1-9]/.test(O))return null;let D=0,F=-1,N=!1;for(let W=0;W<O.length;W++){if(O[W]==="\\"){W++;continue}if(O[W]==="["&&!N){N=!0;continue}if(O[W]==="]"&&N){N=!1;continue}if(N)continue;if(O[W]==="("&&O.slice(W+1,W+3)!=="?:"&&O.slice(W+1,W+3)!=="?="&&O.slice(W+1,W+3)!=="?!"&&O.slice(W+1,W+4)!=="?<="&&O.slice(W+1,W+4)!=="?<!"){if(F<0)F=W;D++}}if(D===0)return null;return{patternStart:h,patternEnd:_,pattern:O,capCount:D,firstCapOffset:F}}function Lp(s,h,m){let g=m;while(g<s.length&&(s[g]===" "||s[g]==="\t"))g++;if(s[g]==="."){let T=s.slice(g+1,g+20);if(/^test\s*\(/.test(T))return!1;if(/^exec\s*\(/.test(T))return!0}let R=h-1;while(R>=0&&(s[R]===" "||s[R]==="\t"))R--;if(s[R]==="("){let A=R-1;while(A>=0&&(s[A]===" "||s[A]==="\t"))A--;let O=s.slice(Math.max(0,A-20),A+1);if(/\.match\s*$/.test(O))return!0;if(/\.matchAll\s*$/.test(O))return!0;if(/\.exec\s*$/.test(O))return!0;if(/\.replace\s*$/.test(O))return!0;if(/\.replaceAll\s*$/.test(O))return!0;if(/\.split\s*$/.test(O))return!0;if(/\.search\s*$/.test(O))return!1;if(/\.test\s*$/.test(O))return!1}let I=s.lastIndexOf(`
|
|
137
|
+
`,h)+1,L=s.slice(I,h).trim().match(/(?:const|let|var)\s+(\w+)\s*=\s*$/);if(L){let T=L[1],A=s.slice(m),O=new RegExp(`\\b${T}\\.exec\\s*\\(`),_=new RegExp(`\\b${T}\\.test\\s*\\(`),D=new RegExp(`\\.match(?:All)?\\s*\\(\\s*${T}\\s*\\)`),F=new RegExp(`\\.replace(?:All)?\\s*\\(\\s*${T}`),N=O.test(A),W=D.test(A),B=F.test(A),j=_.test(A);if(N||W||B)return!0;if(j)return!1;return!0}return!0}function Tp(s,h){let m=h-1;while(m>=0&&(s[m]===" "||s[m]==="\t"))m--;let g=m>=0?s[m]:"",R="=(<>!&|?:;,{[+(~^%*/";if(!(m<0||R.includes(g)||/\b(?:return|typeof|void|delete|throw|new|in|of|case)\s*$/.test(s.slice(Math.max(0,m-5),m+1))))return h+1;let S=h+1,L=!1,T=!1;while(S<s.length){let A=s[S];if(T)T=!1;else if(A==="\\")T=!0;else if(A==="["){if(!L)L=!0}else if(A==="]"){if(L)L=!1}else if(A==="/"&&!L){S++;while(S<s.length&&/[gimsuvy]/.test(s[S]))S++;return S}else if(A===`
|
|
138
|
+
`)break;S++}return h+1}function Ap(s,h){let m=[],g=h.filePath,R=0;while(R<s.length){let I=s[R];if(I==="/"&&s[R+1]==="/"){while(R<s.length&&s[R]!==`
|
|
139
|
+
`)R++;continue}if(I==="/"&&s[R+1]==="*"){R+=2;while(R<s.length-1&&!(s[R]==="*"&&s[R+1]==="/"))R++;R+=2;continue}if(I==="'"||I==='"'||I==="`"){let S=I;R++;while(R<s.length){if(s[R]==="\\"){R+=2;continue}if(s[R]===S){R++;break}R++}continue}if(I==="/"){let S=Ep(s,R);if(!S){let L=Tp(s,R);if(L>R+1)R=L;else R++;continue}if(!Lp(s,S.patternStart,S.patternEnd)){let L=S.patternStart+1+(S.firstCapOffset>=0?S.firstCapOffset:0),T=s.slice(0,L),A=(T.match(/\r?\n/g)||[]).length+1,O=L-(T.lastIndexOf(`
|
|
140
|
+
`)+1)+1;m.push({filePath:g,line:A,column:O,ruleId:"regexp/no-unused-capturing-group",message:"Unused capturing group in regular expression; use non-capturing group (?:...) instead",severity:"error"})}R=S.patternEnd;continue}R++}return m}var mc={meta:{docs:"Flags regex literals with unused capturing groups (context-aware)",recommended:!1},check(s,h){return Ap(s,h)}};var hc={meta:{docs:"Disallow lazy quantifiers that don't affect the matching behavior",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(I.trim().startsWith("//")||I.trim().startsWith("/*")||I.trim().startsWith("*"))continue;let S=/\/(?![/*])([^/\n\r\\]|\\.)+\/[gimsuvy]*/g,L;for(L=S.exec(I);L!==null;L=S.exec(I)){let T=L[0],A=T.slice(1,T.lastIndexOf("/"));if(/[+*?]\?\$$/.test(A))m.push({filePath:h.filePath,line:R+1,column:L.index+A.search(/[+*?]\?\$$/)+2,ruleId:"regexp/no-useless-lazy",message:"Lazy quantifier is useless before end-of-string anchor",severity:"error"});if(/[+*?]\?$/.test(A))m.push({filePath:h.filePath,line:R+1,column:L.index+A.length-1,ruleId:"regexp/no-useless-lazy",message:"Lazy quantifier is useless at the end of the pattern",severity:"error"})}}return m}};var dc={name:"regexp",rules:{"no-super-linear-backtracking":U(fc),"no-unused-capturing-group":U(mc),"no-useless-lazy":U(hc)}};var pc={meta:{docs:"Use $() instead of backticks for command substitution",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="",S=!1;for(let L=0;L<g.length;L++){let T=g[L];if(R){if(T.trim()===I)R=!1;continue}let A=T.match(/<<-?\s*['"]?(\w+)['"]?/);if(A)R=!0,I=A[1];if(T.replace(/^\s+/,"").startsWith("#"))continue;S=!1;for(let _=0;_<T.length;_++){let D=T[_];if(D==="#"&&!S)break;if(D==="\\"){_++;continue}if(D==="'"){S=!S;continue}if(S)continue;if(D==="`"){m.push({filePath:h.filePath,line:L+1,column:_+1,ruleId:"shell/command-substitution",message:"Use $(...) instead of backticks for command substitution",severity:"error",help:"Replace `cmd` with $(cmd) for better readability and nesting support"});for(_++;_<T.length&&T[_]!=="`";_++)if(T[_]==="\\")_++}}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[],R=!1,I="";for(let S of m){if(R){if(g.push(S),S.trim()===I)R=!1;continue}let L=S.match(/<<-?\s*['"]?(\w+)['"]?/);if(L)R=!0,I=L[1];let T="",A=!1,O=0;while(O<S.length){let _=S[O];if(_==="#"&&!A){T+=S.slice(O);break}if(_==="\\"){T+=S.slice(O,O+2),O+=2;continue}if(_==="'"){A=!A,T+=_,O++;continue}if(A){T+=_,O++;continue}if(_==="`"){let D="";O++;while(O<S.length&&S[O]!=="`")if(S[O]==="\\")D+=S[O+1]||"",O+=2;else D+=S[O],O++;O++,T+=`$(${D})`}else T+=_,O++}g.push(T)}return g.join(`
|
|
141
|
+
`)}};var gc={meta:{docs:"Require error handling after cd commands",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];let A=L.replace(/^\s+/,"");if(A.startsWith("#"))continue;let O=A.match(/^cd\s+/);if(!O)continue;let _=/\|\||&&/.test(L),D=/^\s*(?:if|elif|while|until)\s/.test(A)||/\bif\s+cd\b/.test(L),F=/\(.*\bcd\b.*\)/.test(L);if(!_&&!D&&!F)m.push({filePath:h.filePath,line:S+1,column:O.index+1,ruleId:"shell/no-cd-without-check",message:"cd without error handling \u2014 if it fails, subsequent commands run in the wrong directory",severity:"warning",help:"Use: cd dir || exit 1 (or || return 1 inside functions)"})}return m}};var yc={meta:{docs:"Disallow use of eval in shell scripts",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];if(L.replace(/^\s+/,"").startsWith("#"))continue;if(L.match(/(?:^|[;&|]\s*|^\s+)eval\s/)){let _=L.indexOf("eval");m.push({filePath:h.filePath,line:S+1,column:_+1,ruleId:"shell/no-eval",message:"Avoid using eval \u2014 it re-parses arguments and can lead to code injection",severity:"error",help:"Refactor to avoid eval. Consider using arrays for dynamic commands or indirect variable references with ${!var}"})}}return m}};var bc={meta:{docs:"Flag exit inside subshells where it only exits the subshell",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="",S=0;for(let L=0;L<g.length;L++){let T=g[L];if(R){if(T.trim()===I)R=!1;continue}let A=T.match(/<<-?\s*['"]?(\w+)['"]?/);if(A)R=!0,I=A[1];if(T.replace(/^\s+/,"").startsWith("#"))continue;let _=!1,D=!1;for(let F=0;F<T.length;F++){let N=T[F];if(N==="#"&&!_&&!D)break;if(N==="\\"&&!_){F++;continue}if(N==="'"&&!D){_=!_;continue}if(N==='"'&&!_){D=!D;continue}if(!_&&!D){if(N==="("&&F>0&&T[F-1]!=="$"&&T[F+1]!=="(")S++;else if(N==="("&&F===0&&T[F+1]!=="(")S++;else if(N===")"&&S>0&&(F+1>=T.length||T[F+1]!==")"))S--}}if(S>0){let F=T.match(/\bexit\b/);if(F)m.push({filePath:h.filePath,line:L+1,column:F.index+1,ruleId:"shell/no-exit-in-subshell",message:"exit inside a subshell only exits the subshell, not the script",severity:"warning",help:"Restructure to avoid subshells, or use return if inside a function"})}if(S===0){let F=T.match(/(?<!\$)\((?!\()([^)]*\bexit\b[^)]*)\)(?!\))/);if(F){let N=T.indexOf("exit",F.index);m.push({filePath:h.filePath,line:L+1,column:N+1,ruleId:"shell/no-exit-in-subshell",message:"exit inside a subshell only exits the subshell, not the script",severity:"warning",help:"Restructure to avoid subshells, or use return if inside a function"})}}}return m}};var xc={meta:{docs:"Disallow parsing ls output \u2014 use globs or find instead",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];if(L.replace(/^\s+/,"").startsWith("#"))continue;if(L.match(/\bls\b[^|]*\|/)){let F=L.indexOf("ls");m.push({filePath:h.filePath,line:S+1,column:F+1,ruleId:"shell/no-ls-parsing",message:"Don't parse ls output \u2014 filenames can contain special characters",severity:"warning",help:'Use globs (for f in *.txt), find (find . -name "*.txt"), or stat instead'});continue}let _=L.match(/\$\(\s*ls\b/);if(_){let F=_.index+1;m.push({filePath:h.filePath,line:S+1,column:F,ruleId:"shell/no-ls-parsing",message:"Don't use ls in command substitution \u2014 use globs instead",severity:"warning",help:"Replace $(ls *.txt) with glob patterns: for f in *.txt; do ...; done"});continue}let D=L.match(/`\s*ls\b/);if(D){let F=D.index+1;m.push({filePath:h.filePath,line:S+1,column:F,ruleId:"shell/no-ls-parsing",message:"Don't use ls in command substitution \u2014 use globs instead",severity:"warning",help:"Replace `ls` with glob patterns"})}}return m}};var wc={meta:{docs:"Detect useless use of cat (UUOC)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];if(L.replace(/^\s+/,"").startsWith("#"))continue;let O=L.match(/\bcat\s+(["']?[\w.\/~${}*?-]+["']?)\s*\|/);if(O){let _=L.indexOf("cat");m.push({filePath:h.filePath,line:S+1,column:_+1,ruleId:"shell/no-useless-cat",message:`Useless use of cat \u2014 pipe the file directly instead of \`cat ${O[1]} | ...\``,severity:"warning",help:`Use \`cmd < ${O[1]}\` or pass the file as an argument to the command`})}}return m}};var Rc={meta:{docs:"Flag variables inside single quotes where they won't expand",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];if(L.replace(/^\s+/,"").startsWith("#"))continue;let O=!1,_=!1,D=-1;for(let F=0;F<L.length;F++){let N=L[F];if(N==="#"&&!O&&!_)break;if(N==="\\"&&!O){F++;continue}if(N==='"'&&!O){_=!_;continue}if(N==="'"&&!_)if(!O)O=!0,D=F;else{let B=L.slice(D+1,F).match(/\$(?:[A-Za-z_]\w*|\{[^}]+\}|\([^)]*\))/);if(B)m.push({filePath:h.filePath,line:S+1,column:D+1+B.index+1,ruleId:"shell/no-variable-in-single-quotes",message:`Variable ${B[0]} is inside single quotes and won't be expanded`,severity:"warning",help:`Use double quotes if you want variable expansion: "..." instead of '...'`});O=!1}}}return m}};var Op=[/^\s*(?:local|export|declare|typeset|readonly)\s+/,/\[\[.*\]\]/,/\(\(.*\)\)/],yr=/^\$(?:\{[A-Za-z_]\w*(?:[:#%\/][^}]*)?\}|[A-Za-z_]\w*)/,kc={meta:{docs:"Quote variable expansions to prevent word splitting and globbing",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=t(L);if(T){if(R=!0,I=T,new RegExp(`<<-?\\s*['"]${T}['"]`).test(L))continue}if(L.replace(/^\s+/,"").startsWith("#"))continue;if(Op.some((D)=>D.test(L)))continue;let O=[],_=0;while(_<L.length){let D=O[O.length-1];if(D==="squote"){if(L[_]==="'")O.pop();_++;continue}if(L[_]==="\\"&&_+1<L.length){_+=2;continue}if(D==="dquote"){let N=L[_];if(N==='"'){O.pop(),_++;continue}if(N==="$"&&L[_+1]==="("&&L[_+2]==="("){O.push("arith"),_+=3;continue}if(N==="$"&&L[_+1]==="("){O.push("subshell"),_+=2;continue}if(N==="$"){let W=L.slice(_).match(yr);if(W){_+=W[0].length;continue}}_++;continue}if(D==="arith"){let N=L[_];if(N===")"&&L[_+1]===")"){O.pop(),_+=2;continue}if(N==="$"){let W=L.slice(_).match(yr);if(W){_+=W[0].length;continue}}_++;continue}let F=L[_];if(F==="#"&&(_===0||/\s/.test(L[_-1])))break;if(F==="'"){O.push("squote"),_++;continue}if(F==='"'){O.push("dquote"),_++;continue}if(F==="$"&&L[_+1]==="("&&L[_+2]==="("){O.push("arith"),_+=3;continue}if(F==="$"&&L[_+1]==="("){O.push("subshell"),_+=2;continue}if(F===")"&&D==="subshell"){O.pop(),_++;continue}if(F==="$"){let N=L.slice(_).match(yr);if(N){let W=N[0];if(!/^\$[?!#@*0-9-]/.test(W))m.push({filePath:h.filePath,line:S+1,column:_+1,ruleId:"shell/quote-variables",message:`Unquoted variable ${W} \u2014 use "${W}" to prevent word splitting`,severity:"warning",help:`Wrap in double quotes: "${W}"`});_+=W.length;continue}}_++}}return m}};var $c={meta:{docs:"Enforce consistent function declaration style",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];let A=L.replace(/^\s+/,"");if(A.startsWith("#"))continue;let O=A.match(/^function\s+(\w+)\s*(?:\(\s*\))?\s*\{?\s*$/);if(O){let _=O[1],D=L.indexOf("function");m.push({filePath:h.filePath,line:S+1,column:D+1,ruleId:"shell/function-style",message:`Use \`${_}() {\` instead of \`function ${_}\` \u2014 POSIX-compatible style`,severity:"warning",help:`Replace with: ${_}() {`})}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g.match(/^(\s*)function\s+(\w+)\s*(?:\(\s*\))?\s*(\{?\s*)$/);if(R){let[,I,S,L]=R;m.push(`${I}${S}() ${L||"{"}`)}else m.push(g)}return m.join(`
|
|
142
|
+
`)}};function Pc(s,h){if(/^then\b/.test(s)||/^do\b/.test(s)||/^else\b/.test(s))return!0;if(/^if\b/.test(s)&&/\bthen\s*$/.test(s))return!0;if(/^elif\b/.test(s)&&/\bthen\s*$/.test(s))return!0;if(/^(?:while|for|until)\b/.test(s)&&/\bdo\s*$/.test(s))return!0;if(/^case\b/.test(s)&&/\bin\s*$/.test(s))return!0;if(h&&/\)\s*$/.test(s)&&!/\$\(/.test(s)&&!/^\s*\(/.test(s)&&!s.startsWith("#"))return!0;if(/\{\s*$/.test(s)&&!s.startsWith("#"))return!0;return!1}function vc(s){return/^(?:fi|done|esac|elif|else)\b/.test(s)||/^\}/.test(s)||/^;[;&]\s*$/.test(s)}var Ic={meta:{docs:"Enforce consistent indentation in shell scripts",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=h.config.format.indent||2,I=0,S=!1,L="",T=!1,A=0;for(let O=0;O<g.length;O++){let _=g[O];if(/^\s*$/.test(_))continue;if(S){if(_.trim()===L)S=!1;continue}let D=_.match(/<<-?\s*['"]?(\w+)['"]?/);if(D)S=!0,L=D[1];let F=_.replace(/^\s+/,"");if(O===0&&F.startsWith("#!"))continue;if(/^case\b/.test(F)&&/\bin\s*$/.test(F))A++,T=!0;if(/^esac\b/.test(F)){if(A=Math.max(0,A-1),A===0)T=!1}if(vc(F))I=Math.max(0,I-1);let N=0;for(let B=0;B<_.length;B++)if(_[B]===" ")N++;else if(_[B]==="\t")N+=R;else break;let W=I*R;if(N!==W&&!F.startsWith("#"))m.push({filePath:h.filePath,line:O+1,column:1,ruleId:"shell/indent",message:`Expected ${W} spaces of indentation, found ${N}`,severity:"warning"});if(Pc(F,T))I++}return m},fix(s,h){let m=s.split(/\r?\n/),g=h.config.format.indent||2,R=h.config.format.indentStyle==="tabs",I=[],S=0,L=!1,T="",A=!1,O=0;for(let _=0;_<m.length;_++){let D=m[_];if(/^\s*$/.test(D)){I.push("");continue}if(L){if(I.push(D),D.trim()===T)L=!1;continue}let F=D.match(/<<-?\s*['"]?(\w+)['"]?/);if(F)L=!0,T=F[1];let N=D.replace(/^\s+/,"").trimEnd();if(_===0&&N.startsWith("#!")){I.push(N);continue}if(/^case\b/.test(N)&&/\bin\s*$/.test(N))O++,A=!0;if(/^esac\b/.test(N)){if(O=Math.max(0,O-1),O===0)A=!1}if(vc(N))S=Math.max(0,S-1);let W=R?"\t".repeat(S):" ".repeat(S*g);if(I.push(W+N),Pc(N,A))S++}return I.join(`
|
|
143
|
+
`)}};var Mc={meta:{docs:"Enforce spacing around shell keywords (if, then, do, else, fi, etc.)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=t(L);if(T)R=!0,I=T;if(L.replace(/^\s+/,"").startsWith("#"))continue;let O=r(L),_=O.match(/;(?![;\s$])\S/);if(_)m.push({filePath:h.filePath,line:S+1,column:(_.index||0)+1,ruleId:"shell/keyword-spacing",message:"Missing space after semicolon",severity:"warning"});let D=O.match(/\w(then|do|else|elif|fi|done|esac)\b/);if(D&&!/[a-z]/.test(O[D.index])){let F=D[1],N=O[D.index];if(N!==" "&&N!=="\t"&&N!==";")m.push({filePath:h.filePath,line:S+1,column:(D.index||0)+2,ruleId:"shell/keyword-spacing",message:`Missing space before keyword '${F}'`,severity:"warning"})}}return m}};var Cc={meta:{docs:"Disallow unnecessary trailing semicolons",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];let A=L.replace(/^\s+/,"").trimEnd();if(A.startsWith("#"))continue;if(/;;\s*$/.test(A))continue;if(/\bfor\b/.test(A)||/\bwhile\b/.test(A)||/\buntil\b/.test(A))continue;if(/;\s*(?:then|do|else|elif|fi|done|esac)\s*$/.test(A))continue;if(/;\s*$/.test(A)){let O=L.lastIndexOf(";");m.push({filePath:h.filePath,line:S+1,column:O+1,ruleId:"shell/no-trailing-semicolons",message:"Unnecessary trailing semicolon",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[],g=!1,R="";for(let I of h){if(g){if(m.push(I),I.trim()===R)g=!1;continue}let S=I.match(/<<-?\s*['"]?(\w+)['"]?/);if(S)g=!0,R=S[1];let L=I.replace(/^\s+/,"").trimEnd();if(L.startsWith("#")||/;;\s*$/.test(L)||/\bfor\b/.test(L)||/\bwhile\b/.test(L)||/\buntil\b/.test(L)||/;\s*(?:then|do|else|elif|fi|done|esac)\s*$/.test(L)){m.push(I);continue}m.push(I.replace(/;\s*$/,""))}return m.join(`
|
|
144
|
+
`)}};var Sc={meta:{docs:"Disallow trailing whitespace",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=t(L);if(T)R=!0,I=T;if(/[ \t]+$/.test(L)){let A=L.match(/[ \t]+$/);m.push({filePath:h.filePath,line:S+1,column:A.index+1,ruleId:"shell/no-trailing-whitespace",message:"Trailing whitespace",severity:"error"})}}return m},fix(s){let h=s.split(/\r?\n/),m=!1,g="";return h.map((I)=>{if(m){if(I.trim()===g)m=!1;return I}let S=t(I);if(S)m=!0,g=S;return I.replace(/[ \t]+$/,"")}).join(`
|
|
145
|
+
`)}};var Ec={meta:{docs:"Enforce spaces inside [ ] and [[ ]] test expressions",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=t(L);if(T)R=!0,I=T;if(L.replace(/^\s+/,"").startsWith("#"))continue;let O=r(L);for(let _ of _p(O,S+1,h.filePath))m.push(_)}return m},fix(s){let h=s.split(/\r?\n/),m=[],g=!1,R="";for(let I of h){if(g){if(I.trim()===R)g=!1;m.push(I);continue}let S=t(I);if(S){g=!0,R=S,m.push(I);continue}if(I.replace(/^\s+/,"").startsWith("#")){m.push(I);continue}m.push(Dp(I))}return m.join(`
|
|
146
|
+
`)}};function _p(s,h,m){let g=[],R=/\[\[(?!\s|\]|$)/g;for(let S of s.matchAll(R))g.push({filePath:m,line:h,column:(S.index??0)+1,ruleId:"shell/operator-spacing",message:"Missing space after [[",severity:"warning"});let I=/(?<!\s|\[)\]\]/g;for(let S of s.matchAll(I))g.push({filePath:m,line:h,column:(S.index??0)+1,ruleId:"shell/operator-spacing",message:"Missing space before ]]",severity:"warning"});for(let S=0;S<s.length;S++){if(s[S]!=="[")continue;if(s[S+1]==="[")continue;if(S>0&&s[S-1]==="[")continue;if(!Lc(s,S))continue;let L=s[S+1];if(L!==void 0&&L!==" "&&L!=="\t")g.push({filePath:m,line:h,column:S+1,ruleId:"shell/operator-spacing",message:"Missing space after [",severity:"warning"})}for(let S=0;S<s.length;S++){if(s[S]!=="]")continue;if(s[S+1]==="]")continue;if(S>0&&s[S-1]==="]")continue;if(!Tc(s,S))continue;let L=s[S-1];if(L!==void 0&&L!==" "&&L!=="\t")g.push({filePath:m,line:h,column:S+1,ruleId:"shell/operator-spacing",message:"Missing space before ]",severity:"warning"})}return g}function Dp(s){let h=r(s),m=[];for(let R of h.matchAll(/\[\[(?!\s|\]|$)/g)){let I=(R.index??0)+2;m.push({pos:I,text:" "})}for(let R of h.matchAll(/(?<!\s|\[)\]\]/g)){let I=R.index??0;m.push({pos:I,text:" "})}for(let R=0;R<h.length;R++){if(h[R]!=="[")continue;if(h[R+1]==="[")continue;if(R>0&&h[R-1]==="[")continue;if(!Lc(h,R))continue;let I=h[R+1];if(I!==void 0&&I!==" "&&I!=="\t")m.push({pos:R+1,text:" "})}for(let R=0;R<h.length;R++){if(h[R]!=="]")continue;if(h[R+1]==="]")continue;if(R>0&&h[R-1]==="]")continue;if(!Tc(h,R))continue;let I=h[R-1];if(I!==void 0&&I!==" "&&I!=="\t")m.push({pos:R,text:" "})}if(m.length===0)return s;m.sort((R,I)=>I.pos-R.pos);let g=s;for(let{pos:R,text:I}of m)g=`${g.slice(0,R)}${I}${g.slice(R)}`;return g}function Lc(s,h){let m=h-1;while(m>=0&&(s[m]===" "||s[m]==="\t"))m--;if(m<0)return!0;let g=s[m];if(g===";"||g==="|"||g==="&"||g==="!"||g==="(")return!0;let R=s.slice(0,m+1);if(/(?:^|\s)(?:if|while|until|elif|then|else|do)\s*$/.test(R))return!0;return!1}function Tc(s,h){let m=s[h+1];if(m===void 0)return!0;return m===" "||m==="\t"||m===";"||m==="|"||m==="&"||m===")"}var Fp=/^#!\s*(?:\/usr\/bin\/env\s+(?:ba|z|k|da)?sh|\/bin\/(?:ba|z|k|da)?sh|\/usr\/bin\/(?:ba|z|k|da)?sh)\b/,Ac={meta:{docs:"Ensure shell scripts have a proper shebang line",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);if(g.length===0)return m;let R=g[0];if(g.every((I)=>I.trim()===""))return m;if(!R.startsWith("#!"))return m.push({filePath:h.filePath,line:1,column:1,ruleId:"shell/shebang",message:"Missing shebang line \u2014 shell scripts should start with #!/usr/bin/env bash (or similar)",severity:"warning",help:"Add #!/usr/bin/env bash as the first line"}),m;if(!Fp.test(R))m.push({filePath:h.filePath,line:1,column:1,ruleId:"shell/shebang",message:`Invalid shebang: ${R} \u2014 use #!/usr/bin/env bash or #!/bin/sh`,severity:"warning",help:"Use #!/usr/bin/env bash for portability or #!/bin/sh for POSIX scripts"});return m}};var Oc={meta:{docs:"Enforce consistent case statement terminator placement",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="",S=[];for(let L of g){if(R){if(L.trim()===I)R=!1;S.push("");continue}let T=t(L);if(T)R=!0,I=T;if(L.replace(/^\s+/,"").startsWith("#")){S.push("");continue}S.push(r(L))}for(let L=0;L<S.length;L++){if(!/\bcase\b[\s\S]*\bin\s*$/.test(S[L].trimEnd()))continue;let T=1,A=-1;for(let F=L+1;F<S.length;F++){let N=S[F].trimEnd();if(/^\s*esac\b/.test(N)){if(T--,T===0){A=F;break}continue}if(/\bcase\b[\s\S]*\bin\s*$/.test(N))T++}if(A===-1)continue;let O=0,_=!1,D=!1;for(let F=L+1;F<A;F++){let N=S[F],W=N.trim();if(W==="")continue;if(O===0){let B=Np(N);if(B!==-1){if(_&&D)m.push({filePath:h.filePath,line:F+1,column:1,ruleId:"shell/consistent-case-terminators",message:"Missing ;; terminator for previous case branch",severity:"warning",help:"Add ;; at the end of the case branch before the next pattern"});_=!0,D=!0;let j=N.slice(B+1).trimEnd();if(/;;\s*$/.test(j))_=!1;continue}}if(O+=Wp(N),O<0)O=0;if(_&&O===0&&/;;\s*$/.test(W))_=!1}}return m}};function Np(s){let h=s.replace(/^\s+/,"");if(h==="")return-1;if(/^(?:for|while|until|if|case|do|then|else|elif|fi|done|esac)\b/.test(h))return-1;let m=s.length-h.length,g=0;if(h[g]==="(")g++;let R=0;while(g<h.length){let I=h[g];if(I==="(")R++;else if(I===")"){if(R===0)return m+g;R--}else if(I===";"||I==="&"||I==="<"||I===">"||I==="=")return-1;g++}return-1}function Wp(s){let h=s.trim();if(h==="")return 0;let m=h.split(/[\s;]+/),g=0;for(let R of m)if(R==="if"||R==="for"||R==="while"||R==="until")g++;else if(R==="fi"||R==="done")g--;return g}var _c={meta:{docs:"Recommend <<- for heredocs inside indented blocks"},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(I.replace(/^\s+/,"").startsWith("#"))continue;if(!I.match(/^\s+/))continue;let A=r(I).match(/(?<!<)<<(?![<-])/);if(!A||A.index===void 0)continue;let _=I.slice(A.index+2).match(/^\s*(['"]?)(\w+)\1\s*$/);if(_){let D=_[2];m.push({filePath:h.filePath,line:R+1,column:A.index+1,ruleId:"shell/heredoc-indent",message:`Use <<- instead of << for indented heredoc (delimiter '${D}' must be at column 0 otherwise)`,severity:"warning",help:"Use <<- to strip leading tabs from heredoc content, allowing proper indentation"})}}return m}};var Dc={meta:{docs:"Detect incorrect redirect ordering (2>&1 before > file)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=t(L);if(T)R=!0,I=T;if(L.replace(/^\s+/,"").startsWith("#"))continue;let O=r(L);if(O.match(/2>&1\s+>(?!&)\s*\S/)){let D=O.indexOf("2>&1");m.push({filePath:h.filePath,line:S+1,column:D+1,ruleId:"shell/no-broken-redirect",message:"Broken redirect: 2>&1 before > file \u2014 stderr goes to terminal, not the file",severity:"error",help:"Swap the order: cmd > file 2>&1 (or use &> file in bash)"})}}return m}};var Fc={meta:{docs:"Prefer [[ ]] over [ ] for test expressions in bash/zsh",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/)[0]||"",R=/bash|zsh/.test(g);if(/^#!.*\bsh\b/.test(g)&&!R||!R)return m;let S=s.split(/\r?\n/),L=!1,T="";for(let A=0;A<S.length;A++){let O=S[A];if(L){if(O.trim()===T)L=!1;continue}let _=O.match(/<<-?\s*['"]?(\w+)['"]?/);if(_)L=!0,T=_[1];if(O.replace(/^\s+/,"").startsWith("#"))continue;if(O.match(/(?:^|\s|;)\[\s(?!\[)/)){if(/(?<!\])\](?!\])/.test(O)){let N=O.indexOf("[");m.push({filePath:h.filePath,line:A+1,column:N+1,ruleId:"shell/prefer-double-brackets",message:"Use [[ ]] instead of [ ] for test expressions in bash/zsh",severity:"warning",help:"[[ ]] prevents word splitting and supports && || regex; [ ] is only needed for POSIX sh"})}}}return m},fix(s){let h=s.split(/\r?\n/)[0]||"";if(!/bash|zsh/.test(h))return s;let g=s.split(/\r?\n/),R=[];for(let I of g){let S=I;S=S.replace(/(?:^|(?<=\s|;))\[(\s(?!\[).*?(?<!\]))\](?!\])/g,"[[$1]]"),R.push(S)}return R.join(`
|
|
147
|
+
`)}};var Nc={meta:{docs:"Prefer printf over echo -e and echo -n",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I="";for(let S=0;S<g.length;S++){let L=g[S];if(R){if(L.trim()===I)R=!1;continue}let T=L.match(/<<-?\s*['"]?(\w+)['"]?/);if(T)R=!0,I=T[1];if(L.replace(/^\s+/,"").startsWith("#"))continue;let O=L.match(/\becho\s+-[en]+\b/);if(O){let _=L.indexOf("echo"),D=O[0].replace("echo ","");m.push({filePath:h.filePath,line:S+1,column:_+1,ruleId:"shell/prefer-printf",message:`Use printf instead of echo ${D} \u2014 echo behavior varies across platforms`,severity:"warning",help:'printf is portable: printf "format\\n" args... (use \\n for newline)'})}}return m}};var Wc={meta:{docs:"Recommend set -euo pipefail for safer script execution"},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I=!1,S=!1,L=-1,T=!1;for(let O=0;O<g.length;O++){let _=g[O].replace(/^\s+/,"");if(O===0&&_.startsWith("#!")){L=O;continue}if(_.startsWith("#"))continue;if(_==="")continue;if(T=!0,/\bset\s+-\w*e/.test(_))R=!0;if(/\bset\s+-\w*u/.test(_))I=!0;if(/\bset\s+.*-o\s+pipefail/.test(_))S=!0;if(/\bset\s+-euo\s+pipefail/.test(_))R=!0,I=!0,S=!0}if(!T)return m;let A=[];if(!R)A.push("-e");if(!I)A.push("-u");if(!S)A.push("-o pipefail");if(A.length>0)m.push({filePath:h.filePath,line:L>=0?L+2:1,column:1,ruleId:"shell/set-options",message:`Missing shell safety options: set ${A.join(" ")}`,severity:"warning",help:"Add `set -euo pipefail` near the top of the script for safer execution"});return m}};var Bc={name:"shell",rules:{"command-substitution":De(pc),"quote-variables":De(kc),"no-cd-without-check":De(gc),"no-eval":De(yc),"no-useless-cat":De(wc),"no-ls-parsing":De(xc),"no-variable-in-single-quotes":De(Rc),"no-exit-in-subshell":De(bc),shebang:De(Ac),indent:De(Ic),"function-style":De($c),"operator-spacing":De(Ec),"keyword-spacing":De(Mc),"no-trailing-semicolons":De(Cc),"no-trailing-whitespace":De(Sc),"prefer-double-brackets":De(Fc),"set-options":De(Wc),"prefer-printf":De(Nc),"consistent-case-terminators":De(Oc),"no-broken-redirect":De(Dc),"heredoc-indent":De(_c)}};var Qs=null,Xs=null,br=!1,xr=!0;function Bp(){if(br)return xr;try{return Qs=(()=>{throw new Error("Cannot require module "+"@stacksjs/ts-spell-check");})(),Qs.SpellChecker.create({minWordLength:3,maxSuggestions:3}).then((s)=>{Xs=s}).catch(()=>{xr=!1}),br=!0,!0}catch{return br=!0,xr=!1,!1}}function wr(s,h){return{meta:{docs:s==="spell/check"?"Check spelling in text content":s==="spell/check-comments"?"Check spelling in code comments only":"Check spelling in markdown files"},check(m,g){if(!Bp()||!Qs)return[];let{extractWords:R,parseDirectives:I,isSuppressed:S,getProgrammingWords:L}=Qs,T=g.options,A=new Set((T?.words||[]).map((W)=>W.toLowerCase())),O=T?.minWordLength||3,_=L(),D=I(m);for(let W of D)if(W.type==="word")W.words.forEach((B)=>A.add(B.toLowerCase()));let F=m.split(/\r?\n/),N=[];for(let W=0;W<F.length;W++){let B=F[W],j=W+1;if(h&&!h(B))continue;let z=R(B);for(let{word:K,offset:V}of z){if(K.length<O)continue;if(K===K.toUpperCase()&&K.length<=5)continue;if(A.has(K.toLowerCase()))continue;if(_.has(K.toLowerCase()))continue;if(S(K,j,D,A))continue;if(Xs){if(Xs.isCorrect(K))continue;let G=Xs.suggest(K);N.push({filePath:g.filePath,line:j,column:V+1,ruleId:s,message:`Unknown word: "${K}"`,severity:"warning",help:G.length?`Did you mean: ${G.slice(0,3).join(", ")}? Or add to config words.`:`Add "${K}" to your config words array, or use: // spell-check:ignore ${K}`})}}}return N}}}function jp(s){let h=s.trimStart();return h.startsWith("//")||h.startsWith("/*")||h.startsWith("*")||h.startsWith("#")}var jc={name:"spell",rules:{check:wr("spell/check"),"check-comments":wr("spell/check-comments",jp),"check-markdown":{meta:{docs:"Check spelling in markdown files"},check(s,h){if(!h.filePath.endsWith(".md"))return[];return wr("spell/check-markdown").check(s,h)}}}};function Uc(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var zc={meta:{docs:"Disallow spaces inside array brackets",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]==="["&&!Uc(I,L)){let T=I[L+1];if(T==="]"||T===void 0||T===`
|
|
148
|
+
`)continue;if(T===" "||T==="\t"){if(I.indexOf("]",L+1)!==-1)m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/array-bracket-spacing",message:"Unexpected space after '['",severity:"warning"})}}if(I[L]==="]"&&!Uc(I,L)){let T=L>0?I[L-1]:void 0;if(T==="["||T===void 0)continue;if(T===" "||T==="\t"){if(I.lastIndexOf("[",L-1)!==-1)m.push({filePath:h.filePath,line:R+1,column:L,ruleId:"style/array-bracket-spacing",message:"Unexpected space before ']'",severity:"warning"})}}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/\[\s+(\S)/g,(I,S)=>{if(S==="]")return I;return`[${S}`}),R=R.replace(/(\S)\s+\]/g,"$1]"),m.push(R)}return m.join(`
|
|
149
|
+
`)}};var qc=/(?<![(\[{,=:?&|+\-*/])\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/g;function Up(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Kc={meta:{docs:"Require parentheses around arrow function parameters",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;qc.lastIndex=0;while((L=qc.exec(I))!==null){let T=L.index;if(Up(I,T))continue;let A=L[1];if(I.slice(0,T).trimEnd().endsWith("("))continue;if(A==="async")continue;m.push({filePath:h.filePath,line:R+1,column:T+1,ruleId:"style/arrow-parens",message:`Arrow function parameter '${A}' should be wrapped in parentheses`,severity:"warning"})}}return m},fix(s){return s.replace(/(?<![(\[{,=:?&|+\-*/])\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/g,(h,m)=>{if(m==="async")return h;return h.replace(m,`(${m})`)})}};var ei=/=>/g;function Vc(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Hc={meta:{docs:"Require space before and after => in arrow functions",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;ei.lastIndex=0;while((L=ei.exec(I))!==null){let T=L.index;if(Vc(I,T))continue;if(T>0&&I[T-1]!==" "&&I[T-1]!=="\t")m.push({filePath:h.filePath,line:R+1,column:T+1,ruleId:"style/arrow-spacing",message:"Missing space before =>",severity:"warning"});let A=T+2;if(A<I.length&&I[A]!==" "&&I[A]!=="\t"&&I[A]!==`
|
|
149
150
|
`)m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/arrow-spacing",message:"Missing space after =>",severity:"warning"})}}return m},fix(s){let h=s.split(`
|
|
150
|
-
`);for(let m=0;m<h.length;m++){let g=h[m],R=g.trim();if(!R||R.startsWith("//")||R.startsWith("*")||R.startsWith("/*"))continue;let I="",S=0;
|
|
151
|
-
`)}};function
|
|
152
|
-
`)}};var
|
|
153
|
-
`)}};function
|
|
151
|
+
`);for(let m=0;m<h.length;m++){let g=h[m],R=g.trim();if(!R||R.startsWith("//")||R.startsWith("*")||R.startsWith("/*"))continue;let I="",S=0;ei.lastIndex=0;let L;while((L=ei.exec(g))!==null){let T=L.index;if(Vc(g,T))continue;let A=g[T-1],O=g[T+2],_=T>0&&A!==" "&&A!=="\t",D=O!==void 0&&O!==" "&&O!=="\t";if(!_&&!D)continue;I+=g.slice(S,T),I+=`${_?" ":""}=>${D?" ":""}`,S=T+2}if(S>0)h[m]=I+g.slice(S)}return h.join(`
|
|
152
|
+
`)}};function Rr(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Zc={meta:{docs:"Require spaces inside single-line blocks",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]!=="{")continue;if(Rr(I,L))continue;if(L>0&&I[L-1]==="$")continue;let T=1,A=-1;for(let _=L+1;_<I.length;_++){if(I[_]==="{"&&!Rr(I,_))T++;if(I[_]==="}"&&!Rr(I,_)){if(T--,T===0){A=_;break}}}if(A===-1)continue;let O=I.slice(L+1,A);if(!O.trim())continue;if(O[0]!==" "&&O[0]!=="\t")m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/block-spacing",message:"Missing space after '{'",severity:"warning"});if(O[O.length-1]!==" "&&O[O.length-1]!=="\t")m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/block-spacing",message:"Missing space before '}'",severity:"warning"});break}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g.replace(/(?<!\$)\{(\S)([^}]*?)(\S)\}/g,(I,S,L,T)=>`{ ${S}${L}${T} }`);R=R.replace(/(?<!\$)\{(\S)([^}]*?)\s\}/g,(I,S,L)=>`{ ${S}${L} }`),R=R.replace(/(?<!\$)\{\s([^}]*?)(\S)\}/g,(I,S,L)=>`{ ${S}${L} }`),m.push(R)}return m.join(`
|
|
153
|
+
`)}};var Gc={meta:{docs:"Enforce consistent brace style for blocks",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let S=g[R].trim();if(S.startsWith("//")||S.startsWith("/*"))continue;if(/\}\s+(?:else|catch|finally)\b/.test(S))m.push({filePath:h.filePath,line:R+1,column:S.indexOf("}")+1,ruleId:"style/brace-style",message:"Closing curly brace appears on the same line as the subsequent block",severity:"error"});if(S==="{"&&R>0){let T=g[R-1].trim();if(!T||T.startsWith("//")||T.startsWith("/*")||T.endsWith("*/"))continue;if(T&&!T.endsWith("{")&&!T.endsWith(",")&&!T.endsWith("(")){if(!T.match(/[=:]\s*$/)&&!T.endsWith("["))m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"style/brace-style",message:"Opening curly brace should be on the same line",severity:"error"})}}}return m}};var Jc=/,\s*$/,Yc=new RegExp("^\\s*[}\\])](?:\\s*;?\\s*)?$"),Xc={meta:{docs:"Require trailing commas in multiline constructs",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=1;R<g.length;R++){let S=g[R].trim();if(!Yc.test(S))continue;let L=g[R-1],T=L.trim();if(!T||T==="{"||T==="["||T==="(")continue;if(T.startsWith("//")||T.startsWith("*")||T.startsWith("/*"))continue;if(Jc.test(T))continue;if(T.endsWith("{")||T.endsWith("[")||T.endsWith("("))continue;if(T.endsWith("=>"))continue;m.push({filePath:h.filePath,line:R,column:L.length+1,ruleId:"style/comma-dangle",message:"Missing trailing comma",severity:"warning",help:"Add a trailing comma after the last element in multiline constructs."})}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g=0;g<h.length;g++){let R=h[g];if(g+1<h.length){let I=h[g+1].trim(),S=R.trim();if(Yc.test(I)&&S&&S!=="{"&&S!=="["&&S!=="("&&!S.startsWith("//")&&!S.startsWith("*")&&!S.startsWith("/*")&&!Jc.test(S)&&!S.endsWith("{")&&!S.endsWith("[")&&!S.endsWith("(")&&!S.endsWith("=>")){m.push(R.replace(/(\s*)$/,",$1"));continue}}m.push(R)}return m.join(`
|
|
154
|
+
`)}};function zp(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Qc={meta:{docs:"Require space after commas, disallow space before commas",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]!==",")continue;if(zp(I,L))continue;if(L>0&&I[L-1]===" "){if(I.slice(0,L).trim().length>0)m.push({filePath:h.filePath,line:R+1,column:L+1,ruleId:"style/comma-spacing",message:"Unexpected space before comma",severity:"warning"})}if(L+1<I.length&&I[L+1]!==" "&&I[L+1]!=="\t"&&I[L+1]!==`
|
|
154
155
|
`&&I[L+1]!=="\r")m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/comma-spacing",message:"Missing space after comma",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/ ,/g,","),R=R.replace(/,(\S)/g,", $1"),m.push(R)}return m.join(`
|
|
155
|
-
`)}};var
|
|
156
|
-
`)}};function
|
|
157
|
-
`).length;h.push({start:O,end:_}),R=A}}g+=I.length+1}return h}var
|
|
158
|
-
`)h.push(g+1);function m(g){let R=0,I=h.length-1;while(R<=I){let L=R+I>>1,T=h[L],A=L+1<h.length?h[L+1]:1/0;if(g<T)I=L-1;else if(g>=A)R=L+1;else return{line:L+1,column:g-T+1}}let S=h[h.length-1];return{line:h.length,column:Math.max(1,g-S+1)}}return{lineStarts:h,indexToLoc:m}}function
|
|
156
|
+
`)}};var eu={meta:{docs:"Enforce comma-last style (commas at the end of lines, not the beginning)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;if(S.startsWith(","))m.push({filePath:h.filePath,line:R+1,column:I.indexOf(",")+1,ruleId:"style/comma-style",message:"Comma should be placed at the end of the previous line",severity:"warning"})}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g=0;g<h.length;g++){let R=h[g],I=R.trim();if(I.startsWith(",")&&m.length>0){let S=m.length-1;m[S]=m[S].replace(/\s*$/,",");let L=R.match(/^(\s*)/)?.[1]||"";m.push(L+I.slice(1).trim())}else m.push(R)}return m.join(`
|
|
157
|
+
`)}};function qp(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var tu={meta:{docs:"Disallow spaces inside computed property brackets [expr]",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]!=="[")continue;if(qp(I,L))continue;if(L===0)continue;let T=I[L-1];if(!/[a-zA-Z0-9_$)\]]/.test(T))continue;if(L+1<I.length&&(I[L+1]===" "||I[L+1]==="\t"))m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/computed-property-spacing",message:"Unexpected space after '['",severity:"warning"});let A=1,O=L+1;while(O<I.length&&A>0){if(I[O]==="[")A++;if(I[O]==="]")A--;if(A>0)O++}if(A===0&&O>0){if(I[O-1]===" "||I[O-1]==="\t")m.push({filePath:h.filePath,line:R+1,column:O,ruleId:"style/computed-property-spacing",message:"Unexpected space before ']'",severity:"warning"})}}}return m},fix(s){return s.replace(/([a-zA-Z0-9_$)\]])\[\s+([\s\S]*?)\s+\]/g,"$1[$2]")}};function Kp(s){let h=[],m=s.split(/\r?\n/),g=0;for(let R=0;R<m.length;R++){let I=m[R],S=/\b[\w$)\]]+\s*\./.test(I),L=R+1<m.length&&/^\s*\./.test(m[R+1]);if(S||L){let T=R,A=R;while(T+1<m.length&&/^\s*\./.test(m[T+1]))T++,A=T;if(A>R){let O=g,_=g+m[R].length+1+m.slice(R+1,A+1).join(`
|
|
158
|
+
`).length;h.push({start:O,end:_}),R=A}}g+=I.length+1}return h}var nu={meta:{docs:"Enforce consistent line breaks in member-access/call chains"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/),R=Kp(s);for(let{start:I,end:S}of R){let T=s.slice(I,S).split(/\r?\n/),A=[];for(let F=0;F<T.length;F++){let N=T[F],W=[...N.matchAll(/\./g)].map((B)=>B.index||0);for(let B of W){if(B>0&&N[B-1]==="?")continue;if(/^\s*\./.test(N)&&B===N.indexOf(".")&&N.slice(0,B).trim()==="")A.push("newline");else A.push("inline")}}if(A.length<=1)continue;let O=A[0];if(A.every((F)=>F===O))continue;let _=A.findIndex((F)=>F!==O),D=0;for(let F=0;F<T.length;F++){let N=T[F],W=[...N.matchAll(/\./g)].map((B)=>B.index||0);for(let B of W){if(B>0&&N[B-1]==="?")continue;if(D===_){let z=s.slice(0,I).split(/\r?\n/),K=z.length,V=(z[z.length-1]||"").length;m.push({filePath:h.filePath,line:K+F,column:(F===0?V:0)+B+1,ruleId:"style/consistent-chaining",message:`Inconsistent chaining style: mix of ${O} and ${O==="inline"?"newline":"inline"}.`,severity:"warning"}),F=T.length;break}D++}}}return m}};function su(s){let h=[0];for(let g=0;g<s.length;g++)if(s[g]===`
|
|
159
|
+
`)h.push(g+1);function m(g){let R=0,I=h.length-1;while(R<=I){let L=R+I>>1,T=h[L],A=L+1<h.length?h[L+1]:1/0;if(g<T)I=L-1;else if(g>=A)R=L+1;else return{line:L+1,column:g-T+1}}let S=h[h.length-1];return{line:h.length,column:Math.max(1,g-S+1)}}return{lineStarts:h,indexToLoc:m}}function iu(s){let h=[],m=(I,S,L)=>h.push({type:I,value:s.slice(S,L),start:S,end:L}),g=0,R=s.length;while(g<R){let I=s[g];if(I<=" "){g++;continue}if(I==="/"&&s[g+1]==="/"){let T=g;g+=2;while(g<R&&s[g]!==`
|
|
159
160
|
`)g++;m("LineComment",T,g);continue}if(I==="/"&&s[g+1]==="*"){let T=g;g+=2;while(g<R&&!(s[g]==="*"&&s[g+1]==="/"))g++;g=Math.min(R,g+2),m("BlockComment",T,g);continue}if(I==='"'||I==="'"){let T=I,A=g;g++;while(g<R){let O=s[g];if(O==="\\"){g+=2;continue}if(O===T){g++;break}g++}m("String",A,g);continue}if(I==="`"){let T=g;g++;let A=0;while(g<R){let O=s[g];if(O==="\\"){g+=2;continue}if(O==="`"&&A===0){g++;break}if(O==="$"&&s[g+1]==="{"){A++,g+=2;continue}if(O==="}"&&A>0){A--,g++;continue}g++}m("Template",T,g);continue}if(I==="/"){if(s[g+1]==="/"){let T=g;g+=2;while(g<R&&s[g]!==`
|
|
160
|
-
`)g++;m("LineComment",T,g);continue}if(s[g+1]==="*"){let T=g;g+=2;while(g<R&&!(s[g]==="*"&&s[g+1]==="/"))g++;g=Math.min(R,g+2),m("BlockComment",T,g);continue}if(
|
|
161
|
-
`)_++;return _},L=(_)=>{_+=2;while(_<s.length&&!(s[_]==="*"&&s[_+1]==="/"))_++;return Math.min(s.length,_+2)},T=(_,D)=>{let F=s.length;if(D==="`"){_++;let N=0;while(_<F){let W=s[_];if(W==="\\"){_+=2;continue}if(W==="`"&&N===0){_++;break}if(W==="$"&&s[_+1]==="{"){N++,_+=2;continue}if(W==="}"&&N>0){N--,_++;continue}if(W==='"'||W==="'"){_=T(_,W);continue}if(W==="/"&&s[_+1]==="/"){_=S(_+2);continue}if(W==="/"&&s[_+1]==="*"){_=L(_);continue}_++}return _}_++;while(_<F){let N=s[_];if(N==="\\"){_+=2;continue}if(N===D){_++;break}_++}return _},A=(_)=>{let D=_-1;while(D>=0&&I(s[D]))D--;let F=D>=0?s[D]:"";if(new RegExp("[(:[{;?,=!&|^~+\\-*%<>]").test(F))return!0;if(F==="")return!0;return!1},O=(_)=>{_++;let D=s.length;while(_<D){let F=s[_];if(F==="\\"){_+=2;continue}if(F==="/"){_++;break}_++}while(_<D&&/[a-z]/i.test(s[_]))_++;return _};for(let _=h;_<s.length;_++){let D=s[_];if(D===m){R++;continue}if(D===g){if(R--,R===0)return _;continue}if(D==='"'||D==="'"||D==="`"){_=T(_,D)-1;continue}if(D==="/"&&s[_+1]==="/"){_=S(_+2)-1;continue}if(D==="/"&&s[_+1]==="*"){_=L(_)-1;continue}if(D==="/"&&A(_)){_=O(_)-1;continue}}return-1}function
|
|
161
|
+
`)g++;m("LineComment",T,g);continue}if(s[g+1]==="*"){let T=g;g+=2;while(g<R&&!(s[g]==="*"&&s[g+1]==="/"))g++;g=Math.min(R,g+2),m("BlockComment",T,g);continue}if(Vp(h)){let T=g;g++;while(g<R){let A=s[g];if(A==="\\"){g+=2;continue}if(A==="/"){g++;break}g++}while(g<R&&/[a-z]/i.test(s[g]))g++;m("Regex",T,g);continue}m("Punct",g,g+1),g++;continue}if("(){}[];:,.<>+-*%&|^!?=~".includes(I)){m("Punct",g,g+1),g++;continue}let S=g,L=new RegExp("[^\\s(){}[\\];:,.<>+\\-*%&|^!?=~'\"`/]");while(g<R&&L.test(s[g]))g++;if(g>S)m("Word",S,g);else m("Word",g,g+1),g++}return h}function Vp(s){if(s.length===0)return!0;let h=s[s.length-1],m=new RegExp("[(!,{;:?=]");return h.type==="Punct"&&m.test(h.value)||h.type==="Word"&&/^(?:return|throw|case|of|in|instanceof|typeof|void|new)$/.test(h.value)}function ru(s,h,m,g){let R=0,I=(_)=>_<=" ",S=(_)=>{while(_<s.length&&s[_]!==`
|
|
162
|
+
`)_++;return _},L=(_)=>{_+=2;while(_<s.length&&!(s[_]==="*"&&s[_+1]==="/"))_++;return Math.min(s.length,_+2)},T=(_,D)=>{let F=s.length;if(D==="`"){_++;let N=0;while(_<F){let W=s[_];if(W==="\\"){_+=2;continue}if(W==="`"&&N===0){_++;break}if(W==="$"&&s[_+1]==="{"){N++,_+=2;continue}if(W==="}"&&N>0){N--,_++;continue}if(W==='"'||W==="'"){_=T(_,W);continue}if(W==="/"&&s[_+1]==="/"){_=S(_+2);continue}if(W==="/"&&s[_+1]==="*"){_=L(_);continue}_++}return _}_++;while(_<F){let N=s[_];if(N==="\\"){_+=2;continue}if(N===D){_++;break}_++}return _},A=(_)=>{let D=_-1;while(D>=0&&I(s[D]))D--;let F=D>=0?s[D]:"";if(new RegExp("[(:[{;?,=!&|^~+\\-*%<>]").test(F))return!0;if(F==="")return!0;return!1},O=(_)=>{_++;let D=s.length;while(_<D){let F=s[_];if(F==="\\"){_+=2;continue}if(F==="/"){_++;break}_++}while(_<D&&/[a-z]/i.test(s[_]))_++;return _};for(let _=h;_<s.length;_++){let D=s[_];if(D===m){R++;continue}if(D===g){if(R--,R===0)return _;continue}if(D==='"'||D==="'"||D==="`"){_=T(_,D)-1;continue}if(D==="/"&&s[_+1]==="/"){_=S(_+2)-1;continue}if(D==="/"&&s[_+1]==="*"){_=L(_)-1;continue}if(D==="/"&&A(_)){_=O(_)-1;continue}}return-1}function ti(s,h,m,g,R,I,S){let L=ru(s,g,R,I);if(L<=g)return;let T=s.slice(g+1,L),A=/\r?\n/.test(T),O=su(s),_=[],D=0,F=g+1,N=iu(s.slice(g+1,L)),W=0;for(let j of N){let z=g+1+j.start,K=g+1+j.end;if(W=K,j.type==="Punct"){if(j.value===R)D++;else if(j.value===I&&D>0)D--;else if(j.value===","&&D===0)_.push({start:F,end:z}),F=K}}if(_.push({start:F,end:L}),!A){for(let j of _){let z=s.slice(j.start,j.end);if(/\r?\n/.test(z)){let K=O.indexToLoc(j.start);m.push({filePath:h,line:K.line,column:K.column,ruleId:S,message:"Should not have line breaks between items",severity:"warning"});break}}return}let B=T.indexOf(`
|
|
162
163
|
`);if(B>0){let j=T.slice(0,B),z=(j.match(/,/g)||[]).length,K=T.slice(B+1),V=K.includes(`
|
|
163
|
-
`),
|
|
164
|
-
`)}};function
|
|
165
|
-
`)}};var
|
|
166
|
-
`)}};var
|
|
167
|
-
`&&I[D]!=="(")m.push({filePath:h.filePath,line:R+1,column:D+1,ruleId:"style/generator-star-spacing",message:"Missing space after * in generator function",severity:"warning"})}if(S.match(/^(?:async\s+)?\*\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/)){let A=I.indexOf("*",I.indexOf(S.charAt(0)));if(!
|
|
168
|
-
`)m.push({filePath:h.filePath,line:R+1,column:A+2,ruleId:"style/key-spacing",message:"Missing space after colon in property",severity:"warning"})}}let T=S.match(/^(["']?[a-zA-Z_$][a-zA-Z0-9_$]*["']?)\s+:/);if(T&&!S.match(/^\s*(case|default)\b/)){let A=I.indexOf(":",I.indexOf(T[1])+T[1].length);if(A!==-1&&!
|
|
169
|
-
`)}};var
|
|
170
|
-
`)}};var
|
|
171
|
-
`)}};var
|
|
172
|
-
`)}};var
|
|
173
|
-
`)}};function
|
|
174
|
-
`)continue;if(L>0&&I[L-1]==="$")continue;if(T!==" "&&T!=="\t")m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/object-curly-spacing",message:"Missing space after '{'",severity:"warning"})}if(I[L]==="}"&&!
|
|
164
|
+
`),G=K.includes(",");if(z>=1&&/\S,\s*\S/.test(j)&&!V&&!G){let J=O.indexToLoc(g+1+B+1);m.push({filePath:h,line:J.line,column:J.column,ruleId:S,message:"Should not have line breaks between items",severity:"warning"});return}else if(z>=1&&/\S,\s*\S/.test(j)){let J=O.indexToLoc(g+1+j.search(/,\s*\S/));m.push({filePath:h,line:J.line,column:J.column,ruleId:S,message:"Should have line breaks between items",severity:"warning"});return}}for(let j of _){let z=s.slice(g+1,j.start);if(!/\n[ \t]*$/.test(z)&&z.trim()!==""){let K=O.indexToLoc(j.start);m.push({filePath:h,line:K.line,column:K.column,ruleId:S,message:"Should have line breaks between items",severity:"warning"});break}}}var ou={meta:{docs:"Enforce consistent newlines for list-like constructs (objects, arrays, named imports/exports)"},check:(s,h)=>{let m=[],g="style/consistent-list-newline";for(let R=0;R<s.length;R++){let I=s[R];if(I==="{"){let S=R-1;while(S>=0&&/[ \t]/.test(s[S]))S--;if(S>=0&&s[S]===")")continue;let L=s.slice(Math.max(0,R-60),R);if(/\b(?:function|class|interface|type|enum|try|catch|finally|if|else|for|while|switch)\b[\s\S]*$/.test(L))continue;ti(s,h.filePath,m,R,"{","}","style/consistent-list-newline")}else if(I==="[")ti(s,h.filePath,m,R,"[","]","style/consistent-list-newline");else if(I==="i"&&s.startsWith("import",R)){let S=s.indexOf("{",R);if(S>-1)ti(s,h.filePath,m,S,"{","}","style/consistent-list-newline")}else if(I==="e"&&s.startsWith("export",R)){let S=s.indexOf("{",R);if(S>-1)ti(s,h.filePath,m,S,"{","}","style/consistent-list-newline")}}return m}};function Hp(s){let h=s.trim();return h===""||h.startsWith("//")||h.startsWith("/*")}function kr(s,h){for(let m=h;m<s.length;m++)if(!Hp(s[m]))return m;return-1}function Nt(s,h,m){if(s[h].slice(m).includes("{"))return!0;let R=kr(s,h+1);if(R>=0){if(s[R].trim().startsWith("{"))return!0}return!1}function ni(s,h,m){let g=s[h].slice(m);if(/\bif\b|\bfor\b|\bwhile\b|\bdo\b/.test(g))return!0;return!1}var lu={meta:{docs:"Enforce curly brackets similar to src-2: require braces when any branch/body requires them"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let I=0;I<g.length;I++){let S=g[I],L=S.match(/^(\s*)if\s*\(([^)]*)\)/);if(L){let A=L[0].length,O=Nt(g,I,A),_=ni(g,I,A),D=I,F=O,N=_;while(!0){let W=kr(g,D+1);if(W<0)break;let B=g[W].trim();if(!B.startsWith("else"))break;let j=B.match(/^else\s+if\s*\(([^)]*)\)/);if(j){let z=g[W].indexOf(j[0])+j[0].length;F=F||Nt(g,W,z),N=N||ni(g,W,z),D=W;continue}else{let z=g[W].indexOf("else")+4;F=F||Nt(g,W,z),N=N||ni(g,W,z),D=W;break}}if(F||N){if(!O)m.push({filePath:h.filePath,line:I+1,column:Math.max(1,S.indexOf("if")+1),ruleId:"style/curly",message:"Expect curly brackets",severity:"warning"});let W=I;while(!0){let B=kr(g,W+1);if(B<0)break;let j=g[B],z=j.trim();if(!z.startsWith("else"))break;let K=z.match(/^else\s+if\s*\(([^)]*)\)/);if(K){let V=j.indexOf(K[0])+K[0].length;if(!Nt(g,B,V))m.push({filePath:h.filePath,line:B+1,column:Math.max(1,j.indexOf("else")+1),ruleId:"style/curly",message:"Expect curly brackets",severity:"warning"});W=B;continue}else{let V=j.indexOf("else")+4;if(!Nt(g,B,V))m.push({filePath:h.filePath,line:B+1,column:Math.max(1,j.indexOf("else")+1),ruleId:"style/curly",message:"Expect curly brackets",severity:"warning"});break}}}}let T=S.match(/^(\s*)(while|do|for|for\s+await)\b/);if(T){let A=T[0].length,O=Nt(g,I,A),_=ni(g,I,A);if((O||_)&&!O)m.push({filePath:h.filePath,line:I+1,column:Math.max(1,S.indexOf(T[2])+1),ruleId:"style/curly",message:"Expect curly brackets",severity:"warning"})}}let R=Zp(s,h.filePath);for(let I of R)m.push({filePath:h.filePath,line:I.line,column:I.column,ruleId:"style/curly",message:I.message,severity:"warning"});return m}};function Zp(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim(),L=/^if\s*\(/.test(S)?"if":/^else\s+if\s*\(/.test(S)?"else-if":/^else\b/.test(S)?"else":null;if(!L)continue;let T=0;if(L==="if"){let N=I.match(/if\s*\([^)]*\)/);T=N?I.indexOf(N[0])+N[0].length:I.indexOf("if")+2}else if(L==="else-if"){let N=I.match(/else\s+if\s*\([^)]*\)/);T=N?I.indexOf(N[0])+N[0].length:I.indexOf("else")+4}else T=I.indexOf("else")+4;let A=R,O=I.indexOf("{",T);if(O<0){let N=function(B){for(let j=B;j<g.length;j++)if(g[j].trim()!=="")return j;return-1}(R+1);if(N<0)continue;if(O=g[N].indexOf("{"),O<0)continue;A=N}let _=0,D=-1;for(let N=A;N<g.length;N++){let W=g[N],B=N===A?Math.max(0,O):0;for(let j=B;j<W.length;j++){let z=W[j];if(z==="{")_++;else if(z==="}"){if(_--,_===0){D=N;break}}}if(D>=0)break}if(D<0)continue;let F=[];for(let N=A+1;N<D;N++){let W=g[N].trim();if(W===""||/^\/\//.test(W))continue;if(F.push(W),F.length>1)break}if(F.length===1&&D===A+2){let N=F[0],W=/^(?:if|for|while|do|switch|try|catch|else)\b/.test(N),B=/[{}]/.test(N),j=(N.match(/\(/g)||[]).length,z=(N.match(/\)/g)||[]).length,K=j!==z,V=!1;for(let G=R+1;G<g.length;G++){let J=g[G].trim();if(J===""||J==="}"||/^\/\//.test(J))continue;if(!/^else\b/.test(J))break;let Y=g[G].indexOf("else")+4,se=J.match(/^else\s+if\s*\([^)]*\)/);if(se)Y=g[G].indexOf(se[0])+se[0].length;let Z=G,re=g[G].indexOf("{",Y);if(re<0){let X=function(le){for(let ne=le;ne<g.length;ne++)if(g[ne].trim()!=="")return ne;return-1}(G+1);if(X<0)break;if(re=g[X].indexOf("{"),re<0)continue;Z=X}let ee=0,oe=-1;for(let X=Z;X<g.length;X++){let te=g[X],le=X===Z?Math.max(0,re):0;for(let ne=le;ne<te.length;ne++){let q=te[ne];if(q==="{")ee++;else if(q==="}"){if(ee--,ee===0){oe=X;break}}}if(oe>=0)break}if(oe>=0){let X=0;for(let te=Z+1;te<oe;te++){let le=g[te].trim();if(le===""||/^\/\//.test(le))continue;if(X++,X>1){V=!0;break}}}if(V)break}if(!V&&L==="if"){let G=function(Y){for(let se=Y;se<g.length;se++){let Z=g[se].trim();if(Z!==""&&Z!=="}"&&!/^\/\//.test(Z))return se}return-1}(D+1);if(G>=0&&/^else\b/.test(g[G].trim())){let J=g[G].indexOf("else")+4,Y=g[G].trim().match(/^else\s+if\s*\([^)]*\)/);if(Y)J=g[G].indexOf(Y[0])+Y[0].length;let se=G,Z=g[G].indexOf("{",J);if(Z<0){let re=function(oe){for(let X=oe;X<g.length;X++)if(g[X].trim()!=="")return X;return-1}(G+1);if(re>=0)Z=g[re].indexOf("{"),se=Z>=0?re:se}if(Z>=0){let re=0,ee=-1;for(let oe=se;oe<g.length;oe++){let X=g[oe],te=oe===se?Math.max(0,Z):0;for(let le=te;le<X.length;le++){let ne=X[le];if(ne==="{")re++;else if(ne==="}"){if(re--,re===0){ee=oe;break}}}if(ee>=0)break}if(ee>=0){let oe=0;for(let X=se+1;X<ee;X++){let te=g[X].trim();if(te===""||/^\/\//.test(te))continue;if(++oe>1){V=!0;break}}}}}}if(!W&&!B&&!K&&!V)m.push({line:A+1,column:Math.max(1,g[A].indexOf("{")+1),message:"Unnecessary curly braces around single statement"})}}return m}var au={meta:{docs:"Enforce dot on the property line in chained method calls",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=yt(s);for(let I=0;I<g.length;I++){let S=g[I],L=S.trim();if(!L||L.startsWith("//")||L.startsWith("*")||L.startsWith("/*"))continue;if(R[I+1])continue;if(L.endsWith(".")&&I+1<g.length){let T=g[I+1].trim();if(T&&/^[a-zA-Z_$]/.test(T))m.push({filePath:h.filePath,line:I+1,column:S.length,ruleId:"style/dot-location",message:"Dot should be on the same line as the property",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[],g=yt(s);for(let R=0;R<h.length;R++){let I=h[R];if(I.trim().endsWith(".")&&!g[R+1]&&R+1<h.length){let L=h[R+1],T=L.trim();if(T&&/^[a-zA-Z_$]/.test(T)){m.push(I.replace(/\.\s*$/,""));let A=L.match(/^(\s*)/)?.[1]||"";h[R+1]=`${A}.${T}`;continue}}m.push(I)}return m.join(`
|
|
165
|
+
`)}};function cu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var uu=["===","!==",">>>","==","!=",">=","<=","&&","||","??","**","<<",">>","+","-","*","/","%","|","&","^",">","<","instanceof","in"],WI=new RegExp(`^(${uu.map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\s`),Gp=new Set(["in","instanceof"]),Jp=/^(?:instanceof|in)\s/;function si(s){if(Jp.test(s))return!0;for(let h of uu){if(Gp.has(h))continue;if(s.startsWith(h)){let m=s[h.length];if(m===void 0||m===" "||m==="\t")return!0}}return!1}function $r(s){let h=s.match(/^(\s*)/);return h?h[1].length:0}var fu={meta:{docs:"Enforce consistent indentation of continuation lines in multiline binary expressions",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;if(!si(S))continue;if(cu(I,0))continue;let L=R-1;while(L>=0){let O=g[L].trim();if(!O||O.startsWith("//")||O.startsWith("*")||O.startsWith("/*")){L--;continue}if(si(O)){L--;continue}break}if(L<0)continue;let T=$r(g[L])+2,A=$r(I);if(A!==T)m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/indent-binary-ops",message:`Expected indentation of ${T} spaces for binary operator continuation, but found ${A}`,severity:"warning"})}return m},fix(s,h){let m=s.split(/\r?\n/),g=[];for(let R=0;R<m.length;R++){let I=m[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*")){g.push(I);continue}if(!si(S)||cu(I,0)){g.push(I);continue}let L=-1;for(let O=g.length-1;O>=0;O--){let _=g[O].trim();if(!_||_.startsWith("//")||_.startsWith("*")||_.startsWith("/*"))continue;if(si(_))continue;L=O;break}if(L<0){g.push(I);continue}let T=$r(g[L])+2,A=" ".repeat(T)+S;g.push(A);continue}return g.join(`
|
|
166
|
+
`)}};var mu=new Set(["if","for","while","switch","catch","function","return","typeof","void","delete","throw","new","await","class","import","export","from","of","in","case","default","yield","else","do","try","finally","with","async","super","this","extends","implements","instanceof"]),ii=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s+\(/g;function hu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var du={meta:{docs:"Disallow spaces between function name and opening parenthesis in calls",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;ii.lastIndex=0;while((L=ii.exec(I))!==null){let T=L[1],A=L.index;if(hu(I,A))continue;if(mu.has(T))continue;let O=I.slice(0,A).trimEnd();if(O.endsWith("function")||O.endsWith("function*"))continue;if(/\b(?:get|set)\s*$/.test(O))continue;let _=A+T.length;m.push({filePath:h.filePath,line:R+1,column:_+1,ruleId:"style/function-call-spacing",message:"Unexpected space between function name and parenthesis",severity:"warning"})}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[];for(let R=0;R<m.length;R++){let I=m[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*")){g.push(I);continue}let L=I,T=[],A;ii.lastIndex=0;while((A=ii.exec(I))!==null){let O=A[1],_=A.index;if(hu(I,_))continue;if(mu.has(O))continue;let D=I.slice(0,_).trimEnd();if(D.endsWith("function")||D.endsWith("function*"))continue;if(/\b(?:get|set)\s*$/.test(D))continue;T.push({index:_,fullMatch:A[0],identifier:O})}for(let O=T.length-1;O>=0;O--){let _=T[O],D=_.index,F=D+_.fullMatch.length;L=`${L.slice(0,D)}${_.identifier}(${L.slice(F)}`}g.push(L)}return g.join(`
|
|
167
|
+
`)}};var pu=/\bfunction\s*\*/g;function gu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var yu={meta:{docs:"Enforce spacing around * in generator functions (space after, no space before)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;pu.lastIndex=0;while((L=pu.exec(I))!==null){let A=L.index;if(gu(I,A))continue;let O=L[0],_=A+O.indexOf("*"),D=_+1;if(O!=="function*")m.push({filePath:h.filePath,line:R+1,column:_+1,ruleId:"style/generator-star-spacing",message:"Unexpected space before * in generator function",severity:"warning"});if(D<I.length&&I[D]!==" "&&I[D]!=="\t"&&I[D]!==`
|
|
168
|
+
`&&I[D]!=="(")m.push({filePath:h.filePath,line:R+1,column:D+1,ruleId:"style/generator-star-spacing",message:"Missing space after * in generator function",severity:"warning"})}if(S.match(/^(?:async\s+)?\*\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/)){let A=I.indexOf("*",I.indexOf(S.charAt(0)));if(!gu(I,A)){let O=A+1;if(O<I.length&&I[O]!==" "&&I[O]!=="\t")m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"style/generator-star-spacing",message:"Missing space after * in generator method",severity:"warning"})}}}return m},fix(s,h){let m=s;return m=m.replace(/\bfunction\s+\*/g,"function*"),m=m.replace(/\bfunction\*([a-zA-Z_$])/g,"function* $1"),m=m.replace(/(^\s*(?:async\s+)?)\*([a-zA-Z_$])/gm,"$1* $2"),m}};var bu={meta:{docs:"Enforce newline after if when without braces"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(!I.match(/^\s*if\s*\([^)]*\)\s*([^\s{/].*)$/))continue;m.push({filePath:h.filePath,line:R+1,column:Math.max(1,I.indexOf("if")+1),ruleId:"style/if-newline",message:"Expect newline after if",severity:"warning"})}return m}};var Yp=["$","unindent","unIndent"],xu={meta:{docs:"Enforce consistent indentation inside unindent-style tagged templates"},check:(s,h)=>{let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.match(/^\s*/)?.[0]??"",L=/([$A-Z_][\w$]*)\s*`/gi,T;while(T=L.exec(I)){let A=T[1];if(!Yp.includes(A))continue;if(I.slice(T.index+T[0].length).includes("`"))continue;let _=-1;for(let F=R+1;F<g.length;F++)if(g[F].includes("`")){_=F;break}if(_<0)continue;let D=`${S} `;for(let F=R+1;F<_;F++){let N=g[F];if(N.trim()==="")continue;let W=N.match(/^\s*/)?.[0]??"";if(!W.startsWith(D)){m.push({filePath:h.filePath,line:F+1,column:(W.length||0)+1,ruleId:"style/indent-unindent",message:"Consistent indentation in unindent tag",severity:"warning"});break}}}}return m}};var Xp=/^(\s*)(["']?[a-zA-Z_$][a-zA-Z0-9_$]*["']?\s*(?:\?)?):(\S)/;function wu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Ru={meta:{docs:"Require space after colon in object properties",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=I.match(Xp);if(L){let A=I.indexOf(":",L[1].length);if(A!==-1&&!wu(I,A)){let O=I[A+1];if(O&&O!==" "&&O!=="\t"&&O!==`
|
|
169
|
+
`)m.push({filePath:h.filePath,line:R+1,column:A+2,ruleId:"style/key-spacing",message:"Missing space after colon in property",severity:"warning"})}}let T=S.match(/^(["']?[a-zA-Z_$][a-zA-Z0-9_$]*["']?)\s+:/);if(T&&!S.match(/^\s*(case|default)\b/)){let A=I.indexOf(":",I.indexOf(T[1])+T[1].length);if(A!==-1&&!wu(I,A))m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/key-spacing",message:"Unexpected space before colon in property",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/^(\s*)(["']?[a-zA-Z_$][a-zA-Z0-9_$]*["']?\s*(?:\?)?):(\S)/,"$1$2: $3"),m.push(R)}return m.join(`
|
|
170
|
+
`)}};var Qp=["if","else","for","while","do","switch","case","return","throw","try","catch","finally","const","let","var","typeof","instanceof","in","of","new","delete","void","yield","await","async","from","import","export","default","class","extends","as","break","continue"],ku=new RegExp(`(?:^|[^\\w$.])(${Qp.join("|")})(?=[^\\w$]|$)`,"g");function eg(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var $u={meta:{docs:"Require space before and after keywords",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;ku.lastIndex=0;while((L=ku.exec(I))!==null){let T=L[0].charAt(0)===L[1].charAt(0)?"":L[0].charAt(0),A=L.index+T.length,O=A+L[1].length;if(eg(I,A))continue;if(A>0){let _=I[A-1];if(_===")"||_==="}")m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/keyword-spacing",message:`Missing space before keyword '${L[1]}'`,severity:"warning"})}if(O<I.length){let _=I[O];if(_!==" "&&_!=="\t"&&_!==";"&&_!==","&&_!==":"&&_!=="."){if(_==="("&&(L[1]==="if"||L[1]==="for"||L[1]==="while"||L[1]==="switch"||L[1]==="catch"))m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"style/keyword-spacing",message:`Missing space after keyword '${L[1]}'`,severity:"warning"})}}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;for(let I of["if","for","while","switch","catch"]){let S=new RegExp(`(\\b${I})\\(`,"g");R=R.replace(S,"$1 (")}for(let I of["else","catch","finally"])R=R.replace(new RegExp(`\\)${I}\\b`,"g"),`) ${I}`),R=R.replace(new RegExp(`\\}${I}\\b`,"g"),`} ${I}`);m.push(R)}return m.join(`
|
|
171
|
+
`)}};var Pu=/^\s*(?:public|private|protected|static|readonly|abstract|override|async|get|set|\*|#|[a-zA-Z_$])/,vu={meta:{docs:"Require blank line between class members",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I=0,S=0,L=-1;for(let T=0;T<g.length;T++){let O=g[T].trim();if(O.match(/\bclass\b/)&&(O.includes("{")||T+1<g.length&&g[T+1].trim()==="{"))R=!0,S=I+1;let _=I;for(let D of O){if(D==="{")I++;if(D==="}")I--}if(R&&I<S){R=!1,L=-1;continue}if(!R)continue;if(_>S&&I===S&&O.endsWith("}")){L=T;continue}if(_===S){if(!O||O.startsWith("//")||O.startsWith("*")||O.startsWith("/*")||O==="}")continue;if(Pu.test(O)){if(L!==-1&&T===L+1)m.push({filePath:h.filePath,line:T+1,column:1,ruleId:"style/lines-between-class-members",message:"Missing blank line between class members",severity:"warning"});if(!O.endsWith("{"))L=T}}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[],R=!1,I=0,S=0,L=-1;for(let T=0;T<m.length;T++){let A=m[T],O=A.trim();if(O.match(/\bclass\b/)&&(O.includes("{")||T+1<m.length&&m[T+1].trim()==="{"))R=!0,S=I+1;let _=I;for(let D of O){if(D==="{")I++;if(D==="}")I--}if(R&&I<S){R=!1,L=-1,g.push(A);continue}if(R&&_>S&&I===S&&O.endsWith("}")){L=T,g.push(A);continue}if(R&&_===S&&O&&!O.startsWith("//")&&!O.startsWith("*")&&!O.startsWith("/*")&&O!=="}"&&Pu.test(O)){if(L!==-1&&T===L+1)g.push("");if(!O.endsWith("{"))L=T}g.push(A)}return g.join(`
|
|
172
|
+
`)}};var Iu={meta:{docs:"Limit the number of statements allowed on a single line"},check:(s,h)=>{let m=h.options&&typeof h.options.max==="number"?h.options.max:1,g=[],R=s.split(/\r?\n/),I=(S)=>{let L=tg(S),T=L>=0?S.slice(0,L):S,A=0,O=!1,_=!1,D=!1,F=!1,N=!1,W=!1,B=!1,j=0,z="",K=(J)=>{if(J===" "||J==="\t")return;z=J};for(let J=0;J<T.length;J++){let Y=T[J];if(W){W=!1;continue}if(Y==="\\"){W=!0;continue}if(F){if(N){if(Y==="]")N=!1;continue}if(Y==="["){N=!0;continue}if(Y==="/"){F=!1;while(J+1<T.length&&/[a-z]/i.test(T[J+1]))J++;z="/"}continue}if(!_&&!D&&Y==="'"){O=!O,K(O?"'":"x");continue}if(!O&&!D&&Y==='"'){_=!_,K(_?'"':"x");continue}if(!O&&!_&&Y==="`"){D=!D,K(D?"`":"x");continue}if(O||_||D)continue;if(Y==="/"&&Mu(z,T,J)){F=!0;continue}if(!B){if(Y==="f"&&T.slice(J,J+4).match(/^for\b/)){let se=T.slice(J+3).trimStart(),Z=T.length-se.length;if(T[Z]==="("){B=!0,j=1,J=Z,z="(";continue}}}else if(Y==="(")j++;else if(Y===")"){if(j--,j<=0)B=!1}else if(Y===";"){K(Y);continue}if(Y===";")A++;K(Y)}if(A===0)return 1;return T.trimEnd().endsWith(";")?A:A+1};for(let S=0;S<R.length;S++){let L=R[S];if(/^\s*$/.test(L))continue;let T=I(L);if(T>m)g.push({filePath:h.filePath,line:S+1,column:1,ruleId:"max-statements-per-line",message:`This line has ${T} statements. Maximum allowed is ${m}`,severity:"warning"})}return g}};function tg(s){let h=!1,m=!1,g=!1,R=!1,I=!1,S=!1,L="";for(let T=0;T<s.length;T++){let A=s[T];if(S){S=!1;continue}if(A==="\\"){S=!0;continue}if(R){if(I){if(A==="]")I=!1;continue}if(A==="["){I=!0;continue}if(A==="/"){R=!1;while(T+1<s.length&&/[a-z]/i.test(s[T+1]))T++;L="/"}continue}if(!m&&!g&&A==="'"){h=!h,L=A;continue}if(!h&&!g&&A==='"'){m=!m,L=A;continue}if(!h&&!m&&A==="`"){g=!g,L=A;continue}if(h||m||g)continue;if(A==="/"&&s[T+1]==="/")return T;if(A==="/"&&Mu(L,s,T)){R=!0;continue}if(A!==" "&&A!=="\t")L=A}return-1}function Mu(s,h,m){if(s==="")return!0;if("([{,:;!?&|=<>~^+*%-".includes(s))return!0;if(/[A-Za-z_$]/.test(s)){if(h.slice(0,m).trimEnd().match(/(?:^|[^A-Za-z0-9_$])(return|typeof|instanceof|new|delete|void|in|of|yield|await|throw|case)$/))return!0}return!1}function Cu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Su={meta:{docs:"Enforce consistent multiline ternary expressions",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=I.indexOf("?");if(L===-1)continue;if(I[L+1]==="."||I[L+1]==="?")continue;if(Cu(I,L))continue;if(I.indexOf(":",L+1)!==-1)continue;for(let A=R+1;A<Math.min(R+10,g.length);A++){let O=g[A].trim();if(O.startsWith(":"))break;let _=O.indexOf(":");if(_>0&&!Cu(g[A],_)){if(O.match(/^\w+\s*:/)||O.match(/^case\b/))continue;m.push({filePath:h.filePath,line:A+1,column:g[A].indexOf(":")+1,ruleId:"style/multiline-ternary",message:"In multiline ternary, ':' should be at the start of the line",severity:"warning"});break}}}return m}};var Eu=new RegExp("\\bnew\\s+([A-Z][a-zA-Z0-9_$.]+)(?![a-zA-Z0-9_$])(?:\\s*<[^>]*>)?\\s*(?=[^(;\\n]|$)","g");function ng(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Lu={meta:{docs:"Require parentheses when invoking a constructor with no arguments",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;Eu.lastIndex=0;while((L=Eu.exec(I))!==null){if(ng(I,L.index))continue;if(I.slice(L.index+L[0].length).startsWith("("))continue;if(L[0].includes("new."))continue;m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"style/new-parens",message:`Missing parentheses invoking constructor '${L[1]}'`,severity:"warning",help:"Add () after the constructor name."})}}return m},fix(s){return s.replace(/\bnew\s+([A-Z][a-zA-Z0-9_$.]+)(?![a-zA-Z0-9_$])(\s*<[^>]*>)?\s*(?=[^(]|$)/g,(h,m,g)=>{if(h.slice(h.indexOf(m)+m.length+(g?.length||0)).trim().startsWith("("))return h;return`new ${m}${g||""}()`})}};var YI=new RegExp("\\breturn\\s+\\(([^()]*)\\)\\s*[;\\n]","g"),Tu=/^[a-zA-Z_$][a-zA-Z0-9_$.[\]'"`]*$/;var Au={meta:{docs:"Remove redundant parentheses in return statements",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=new RegExp("^return\\s+\\(([^()]*)\\)\\s*;?\\s*$"),T=S.match(L);if(T){let A=T[1].trim();if(Tu.test(A)||/^['"`]/.test(A)||/^\d/.test(A)||A==="true"||A==="false"||A==="null"||A==="undefined")m.push({filePath:h.filePath,line:R+1,column:I.indexOf("(")+1,ruleId:"style/no-extra-parens",message:"Unnecessary parentheses around return value",severity:"warning",help:"Remove the outer parentheses."})}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g.trim(),I=new RegExp("^return\\s+\\(([^()]*)\\)\\s*(;?)\\s*$"),S=R.match(I);if(S){let L=S[1].trim(),T=S[2];if(Tu.test(L)||/^['"`]/.test(L)||/^\d/.test(L)||L==="true"||L==="false"||L==="null"||L==="undefined"){let A=g.match(/^(\s*)/)?.[1]||"";m.push(`${A}return ${L}${T}`);continue}}m.push(g)}return m.join(`
|
|
173
|
+
`)}};var Ou=/(\S)\s+(\.)[a-zA-Z_$]/g,_u=/(\S)\s+(\?\.)[a-zA-Z_$]/g;function ri(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Du={meta:{docs:"Disallow whitespace before . or ?. in property access",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;Ou.lastIndex=0;while((L=Ou.exec(I))!==null){let T=L.index+L[0].indexOf(".");if(ri(I,L.index))continue;if(T+1<I.length&&I[T+1]===".")continue;if(T>0&&I[T-1]===".")continue;m.push({filePath:h.filePath,line:R+1,column:T+1,ruleId:"style/no-whitespace-before-property",message:"Unexpected whitespace before property access dot",severity:"warning"})}_u.lastIndex=0;while((L=_u.exec(I))!==null){let T=L.index+L[0].indexOf("?.");if(ri(I,L.index))continue;m.push({filePath:h.filePath,line:R+1,column:T+1,ruleId:"style/no-whitespace-before-property",message:"Unexpected whitespace before optional chaining operator",severity:"warning"})}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[];for(let R=0;R<m.length;R++){let I=m[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*")){g.push(I);continue}let L=I;L=L.replace(/(\S)\s+(\?\.[a-zA-Z_$])/g,(T,A,O,_)=>{if(ri(I,_))return T;return A+O}),L=L.replace(/(\S)\s+(\.[a-zA-Z_$])/g,(T,A,O,_)=>{if(ri(I,_))return T;let D=_+T.indexOf(".");if(D+1<L.length&&L[D+1]===".")return T;return A+O}),g.push(L)}return g.join(`
|
|
174
|
+
`)}};function Wt(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Fu=/&&/g,Nu=/\|\|/g,Wu=/\?\?/g,Bu=/(?<![&])&(?![&=])/g,ju=/(?<![|])\|(?![|=])/g,Uu=/\^(?!=)/g;function sg(s){let h=[];Fu.lastIndex=0;let m;while((m=Fu.exec(s))!==null)if(!Wt(s,m.index))h.push({op:"&&",group:0,index:m.index});Nu.lastIndex=0;while((m=Nu.exec(s))!==null)if(!Wt(s,m.index))h.push({op:"||",group:1,index:m.index});Wu.lastIndex=0;while((m=Wu.exec(s))!==null)if(!Wt(s,m.index))h.push({op:"??",group:2,index:m.index});Bu.lastIndex=0;while((m=Bu.exec(s))!==null)if(!Wt(s,m.index))h.push({op:"&",group:3,index:m.index});ju.lastIndex=0;while((m=ju.exec(s))!==null)if(!Wt(s,m.index))h.push({op:"|",group:4,index:m.index});Uu.lastIndex=0;while((m=Uu.exec(s))!==null)if(!Wt(s,m.index))h.push({op:"^",group:5,index:m.index});return h.sort((g,R)=>g.index-R.index)}function ig(s,h){if(h.length<2)return!0;let m=[];for(let I of h){let S=0;for(let L=0;L<I.index;L++)if(s[L]==="(")S++;else if(s[L]===")")S--;m.push(S)}let g=new Map;for(let I=0;I<h.length;I++){let S=h[I].group;if(!g.has(S))g.set(S,[]);g.get(S).push(m[I])}let R=[...g.entries()];if(R.length===2){let[,I]=R[0],[,S]=R[1],L=Math.min(...I),T=Math.max(...I),A=Math.min(...S),O=Math.max(...S);if(L>O||A>T)return!0}return!1}var rg=[{groups:[0,1],label:"&& and ||"},{groups:[0,2],label:"&& and ??"},{groups:[1,2],label:"|| and ??"},{groups:[3,4],label:"& and |"},{groups:[3,5],label:"& and ^"},{groups:[4,5],label:"| and ^"}],zu={meta:{docs:"Disallow mixed logical/bitwise operators without parentheses",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=sg(I);if(L.length<2)continue;let T=new Set(L.map((A)=>A.group));for(let A of rg)if(T.has(A.groups[0])&&T.has(A.groups[1])){let O=L.filter((_)=>_.group===A.groups[0]||_.group===A.groups[1]);if(!ig(I,O)){let _=O.find((D)=>D.group===A.groups[1]);if(_)m.push({filePath:h.filePath,line:R+1,column:_.index+1,ruleId:"style/no-mixed-operators",message:`Unexpected mix of ${A.label} without parentheses`,severity:"warning"})}}}return m}};var qu=/(?<![0-9.])\.\d/g,Ku=/\d\.(?!\d|\.|\w)/g;function Vu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Hu={meta:{docs:"Disallow floating decimals like .5 or 2.",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;qu.lastIndex=0;while((L=qu.exec(I))!==null){if(Vu(I,L.index))continue;if(L.index>0){let T=I[L.index-1];if(/[a-zA-Z_$)\]]/.test(T))continue}m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"style/no-floating-decimal",message:"Unexpected leading decimal point",severity:"warning",help:"Add a leading 0 before the decimal point: 0.5 instead of .5"})}Ku.lastIndex=0;while((L=Ku.exec(I))!==null){if(Vu(I,L.index))continue;m.push({filePath:h.filePath,line:R+1,column:L.index+1,ruleId:"style/no-floating-decimal",message:"Unexpected trailing decimal point",severity:"warning",help:"Add a trailing 0 after the decimal point: 2.0 instead of 2."})}}return m},fix(s){let h=s;return h=h.replace(/(?<![a-zA-Z_$0-9.)\]])\.\d/g,(m)=>`0${m}`),h=h.replace(/(\d)\.(?!\d|\.|\w)/g,(m,g)=>`${g}.0`),h}};var Zu={meta:{docs:"Disallow mixed spaces and tabs for indentation",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let S=g[R].match(/^(\s*)/)?.[1]||"";if(!S)continue;let L=S.includes("\t"),T=S.includes(" ");if(L&&T)m.push({filePath:h.filePath,line:R+1,column:1,ruleId:"style/no-mixed-spaces-and-tabs",message:"Mixed spaces and tabs in indentation",severity:"warning",help:"Use either spaces or tabs for indentation, not both."})}return m}};var Gu={meta:{docs:"Disallow multiple consecutive spaces",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];if(!I.trim())continue;let S=I.match(/^(\s*)/)?.[1]||"",L=I.slice(S.length),T=/ {2,}/g,A;for(A=T.exec(L);A!==null;A=T.exec(L)){let O=S.length+A.index+1,_=L.slice(0,A.index),D=(_.match(/'/g)||[]).length,F=(_.match(/"/g)||[]).length,N=(_.match(/`/g)||[]).length;if(D%2===1||F%2===1||N%2===1)continue;if(_.includes("//"))continue;if(I.trim().startsWith("*")||I.trim().startsWith("/*"))continue;m.push({filePath:h.filePath,line:R+1,column:O,ruleId:"style/no-multi-spaces",message:"Multiple spaces found",severity:"warning",help:"Remove extra spaces. Use single spaces between tokens."})}}return m}};var Ju={meta:{docs:"Disallow multiple consecutive blank lines",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=0,I=-1;for(let S=0;S<g.length;S++)if(g[S].trim()===""){if(R++,I===-1)I=S;if(R>1&&S===I+R-1)m.push({filePath:h.filePath,line:S+1,column:1,ruleId:"style/no-multiple-empty-lines",message:"More than 1 blank line not allowed",severity:"error",help:"Remove extra blank lines. Maximum 1 consecutive blank line allowed."})}else R=0,I=-1;return m}};var Yu={meta:{docs:"Disallow tab characters (when using spaces for indentation)",recommended:!1},check(s,h){let m=[];if(h.config.format?.indentStyle==="tabs")return m;let g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let S=g[R].indexOf("\t");if(S!==-1)m.push({filePath:h.filePath,line:R+1,column:S+1,ruleId:"style/no-tabs",message:"Unexpected tab character",severity:"warning",help:"Use spaces for indentation instead of tabs."})}return m},fix(s,h){let m=h.config.format?.indent??2;return s.replace(/\t/g," ".repeat(m))}};var Xu={meta:{docs:"Disallow trailing whitespace at the end of lines",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.match(/(\s+)$/);if(S){let L=I.length-S[1].length+1;m.push({filePath:h.filePath,line:R+1,column:L,ruleId:"style/no-trailing-spaces",message:"Trailing spaces not allowed",severity:"error",help:"Remove trailing whitespace from the end of this line."})}}return m}};function Qu(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var ef={meta:{docs:"Require spaces inside curly braces in objects and destructuring",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]==="{"&&!Qu(I,L)){let T=I[L+1];if(T==="}"||T===void 0||T===`
|
|
175
|
+
`)continue;if(L>0&&I[L-1]==="$")continue;if(T!==" "&&T!=="\t")m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/object-curly-spacing",message:"Missing space after '{'",severity:"warning"})}if(I[L]==="}"&&!Qu(I,L)){let T=L>0?I[L-1]:void 0;if(T==="{"||T===void 0||T===`
|
|
175
176
|
`)continue;if(L+1<I.length&&I.slice(L+1).match(/^[^}]*\$\{/))continue;if(T!==" "&&T!=="\t")m.push({filePath:h.filePath,line:R+1,column:L+1,ruleId:"style/object-curly-spacing",message:"Missing space before '}'",severity:"warning"})}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/(?<!\$)\{(\S)/g,(I,S)=>{if(S==="}")return I;return`{ ${S}`}),R=R.replace(/(\S)\}/g,(I,S)=>{if(S==="{"||S==="$")return I;return`${S} }`}),m.push(R)}return m.join(`
|
|
176
|
-
`)}};var
|
|
177
|
-
`)}};var
|
|
178
|
-
`)}};var
|
|
179
|
-
`)}};function
|
|
177
|
+
`)}};var tf=/(\&\&|\|\||\?\?|\?|\+|(?<!=)-(?!=)|\*|\/|%|\*\*|\|(?!\|)|&(?!&)|\^|<<|>>>?)\s*$/;function nf(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var sf={meta:{docs:"Enforce operators at the beginning of continued lines",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=S.match(tf);if(L&&R+1<g.length){let T=g[R+1].trim();if(T&&!T.startsWith("//")&&!T.startsWith("*")){let A=I.lastIndexOf(L[1]);if(!nf(I,A)){if(L[1]==="?"||L[1]===":")continue;m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/operator-linebreak",message:`Operator '${L[1]}' should be at the beginning of the next line`,severity:"warning"})}}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g=0;g<h.length;g++){let R=h[g],I=R.trim();if(!I||I.startsWith("//")||I.startsWith("*")||I.startsWith("/*")||I.endsWith("*/")){m.push(R);continue}let S=I.match(tf);if(S&&g+1<h.length&&S[1]!=="?"&&S[1]!==":"){let L=h[g+1],T=L.trim();if(T&&!T.startsWith("//")&&!T.startsWith("*")){let A=S[1],O=R.lastIndexOf(S[1]);if(nf(R,O)){m.push(R);continue}m.push(R.replace(new RegExp(`\\s*${A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*$`),""));let _=L.match(/^(\s*)/)?.[1]||"";h[g+1]=`${_}${A} ${T}`;continue}}m.push(R)}return m.join(`
|
|
178
|
+
`)}};var rf={meta:{docs:"Disallow empty lines at the beginning and end of blocks",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let S=g[R].trim();if(S.endsWith("{")&&R+1<g.length){if(g[R+1].trim()==="")m.push({filePath:h.filePath,line:R+2,column:1,ruleId:"style/padded-blocks",message:"Unexpected empty line after opening brace",severity:"warning"})}if(S==="}"&&R>0){if(g[R-1].trim()==="")m.push({filePath:h.filePath,line:R,column:1,ruleId:"style/padded-blocks",message:"Unexpected empty line before closing brace",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=new Set;for(let g=0;g<h.length;g++){let R=h[g].trim();if(R.endsWith("{")&&g+1<h.length&&h[g+1].trim()==="")m.add(g+1);if(R==="}"&&g>0&&h[g-1].trim()==="")m.add(g-1)}return h.filter((g,R)=>!m.has(R)).join(`
|
|
179
|
+
`)}};var Pr=/^(\s*)(["'])([a-zA-Z_$][a-zA-Z0-9_$]*)\2\s*:/;var of={meta:{docs:"Remove unnecessary quotes from object property keys",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=I.match(Pr);if(L){let T=L[3];if(["class","return","function","var","let","const","delete","typeof","void","in","instanceof","new","this","throw","try","catch","finally","switch","case","default","break","continue","do","while","for","if","else","with","import","export","extends","super","yield","await","enum","implements","interface","package","private","protected","public","static"].includes(T))continue;m.push({filePath:h.filePath,line:R+1,column:I.indexOf(L[2])+1,ruleId:"style/quote-props",message:`Unnecessarily quoted property '${T}'`,severity:"warning",help:"Remove quotes from this property key."})}}return m},fix(s){let h=s.split(/\r?\n/),m=[],g=new Set(["class","return","function","var","let","const","delete","typeof","void","in","instanceof","new","this","throw","try","catch","finally","switch","case","default","break","continue","do","while","for","if","else","with","import","export","extends","super","yield","await","enum","implements","interface","package","private","protected","public","static"]);for(let R of h){let I=R,S=R.match(Pr);if(S&&!g.has(S[3]))I=R.replace(Pr,"$1$3:");m.push(I)}return m.join(`
|
|
180
|
+
`)}};function og(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var lf=/\.\.\.\s+([a-zA-Z_$])/g,af={meta:{docs:"Disallow space after spread/rest operator (...)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;lf.lastIndex=0;while((L=lf.exec(I))!==null){if(og(I,L.index))continue;m.push({filePath:h.filePath,line:R+1,column:L.index+4,ruleId:"style/rest-spread-spacing",message:"Unexpected space after spread operator",severity:"warning"})}}return m},fix(s){return s.replace(/\.\.\.\s+([a-zA-Z_$\[{])/g,"...$1")}};function lg(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var cf={meta:{docs:"Disallow space before semicolons, require space after",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]!==";")continue;if(lg(I,L))continue;if(L>0&&I[L-1]===" "){if(I.slice(0,L).trim().length>0)m.push({filePath:h.filePath,line:R+1,column:L+1,ruleId:"style/semi-spacing",message:"Unexpected space before semicolon",severity:"warning"})}if(L+1<I.length&&I[L+1]!==" "&&I[L+1]!=="\t"&&I[L+1]!==`
|
|
180
181
|
`&&I[L+1]!=="\r"&&I[L+1]!==")"){let T=I.slice(L+1);if(I.slice(0,L).includes(";")||T.includes(";"))m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/semi-spacing",message:"Missing space after semicolon",severity:"warning"})}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g,I=new RegExp(" ;","g");R=R.replace(I,String.fromCharCode(59));let S=new RegExp(";(\\S)","g");R=R.replace(S,(L,T)=>{if(T===";"||T===")")return L;return`; ${T}`}),m.push(R)}return m.join(`
|
|
181
|
-
`)}};var
|
|
182
|
-
`)}};var
|
|
183
|
-
`)continue;if(T===" ")m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/space-in-parens",message:"Unexpected space after '('",severity:"warning"})}if(I[L]===")"&&!
|
|
184
|
-
`)}};var
|
|
185
|
-
`&&_!=="\r")m.push({filePath:h.filePath,line:R+1,column:A+L.length+1,ruleId:"style/space-infix-ops",message:`Missing space after '${L}'`,severity:"warning"})}}}return m},fix(s){let h=s,m=[...
|
|
182
|
+
`)}};var uf=/(\S)\{/g;function ag(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var ff={meta:{docs:"Require space before opening brace of blocks",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;uf.lastIndex=0;while((L=uf.exec(I))!==null){let T=L.index,A=L[1];if(ag(I,T))continue;if(A==="$")continue;if(A==="="||A===":"||A==="("||A===","||A==="[")continue;if(A==="{")continue;if(A===")"||/[a-zA-Z0-9_]/.test(A))m.push({filePath:h.filePath,line:R+1,column:L.index+2,ruleId:"style/space-before-blocks",message:"Missing space before '{'",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g.replace(/([)a-zA-Z0-9_])\{/g,"$1 {");m.push(R)}return m.join(`
|
|
183
|
+
`)}};var mf=/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s+\(/g,hf=/\bfunction\(/g;function df(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var pf={meta:{docs:"Control spacing before ( in function declarations",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;mf.lastIndex=0;while((L=mf.exec(I))!==null){if(df(I,L.index))continue;m.push({filePath:h.filePath,line:R+1,column:L.index+L[0].length,ruleId:"style/space-before-function-paren",message:"Unexpected space before function parentheses",severity:"warning"})}hf.lastIndex=0;while((L=hf.exec(I))!==null){if(df(I,L.index))continue;if(I.slice(0,L.index+8).match(/function\s+[a-zA-Z_$]/))continue;m.push({filePath:h.filePath,line:R+1,column:L.index+9,ruleId:"style/space-before-function-paren",message:"Missing space before function parentheses",severity:"warning"})}}return m},fix(s){let h=s;return h=h.replace(/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s+\(/g,"function $1("),h=h.replace(/\bfunction\(/g,"function ("),h}};function gf(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var yf={meta:{docs:"Disallow spaces inside parentheses",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L=0;L<I.length;L++){if(I[L]==="("&&!gf(I,L)){let T=I[L+1];if(T===")"||T===void 0||T===`
|
|
184
|
+
`)continue;if(T===" ")m.push({filePath:h.filePath,line:R+1,column:L+2,ruleId:"style/space-in-parens",message:"Unexpected space after '('",severity:"warning"})}if(I[L]===")"&&!gf(I,L)){if(L===0)continue;let T=I[L-1];if(T==="(")continue;if(T===" "){if(I.slice(0,L).includes("("))m.push({filePath:h.filePath,line:R+1,column:L,ruleId:"style/space-in-parens",message:"Unexpected space before ')'",severity:"warning"})}}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/\(\s+(\S)/g,"($1"),R=R.replace(/(\S)\s+\)/g,"$1)"),m.push(R)}return m.join(`
|
|
185
|
+
`)}};var bf=["&&","||","??","+=","-=","*=","/=","%=","**=","<<=",">>=",">>>=","&=","|=","^=","??=","||=","&&="];function cg(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var xf={meta:{docs:"Require spacing around infix operators (&&, ||, ??, assignment operators)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let L of bf){let T=0,A;while((A=I.indexOf(L,T))!==-1){if(T=A+L.length,cg(I,A))continue;if(L==="&&"&&I[A+2]==="=")continue;if(L==="||"&&I[A+2]==="=")continue;if(L==="??"&&I[A+2]==="=")continue;let O=A>0?I[A-1]:" ",_=A+L.length<I.length?I[A+L.length]:" ";if(O!==" "&&O!=="\t")m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/space-infix-ops",message:`Missing space before '${L}'`,severity:"warning"});if(_!==" "&&_!=="\t"&&_!==`
|
|
186
|
+
`&&_!=="\r")m.push({filePath:h.filePath,line:R+1,column:A+L.length+1,ruleId:"style/space-infix-ops",message:`Missing space after '${L}'`,severity:"warning"})}}}return m},fix(s){let h=s,m=[...bf].sort((g,R)=>R.length-g.length);for(let g of m){let R=g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");h=h.replace(new RegExp(`(\\S)${R}`,"g"),`$1 ${g}`),h=h.replace(new RegExp(`${R}(\\S)`,"g"),`${g} $1`)}return h}};var wf=["typeof","void","delete","new","throw","yield","await"];function vr(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Rf={meta:{docs:"Require space after word unary operators, disallow space after symbol unary operators",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;for(let O of wf){let _=new RegExp(`\\b${O}([^\\s;,)])`,"g"),D;while((D=_.exec(I))!==null){if(vr(I,D.index))continue;m.push({filePath:h.filePath,line:R+1,column:D.index+O.length+1,ruleId:"style/space-unary-ops",message:`Missing space after '${O}'`,severity:"warning"})}}let L=/!\s+([a-zA-Z_$({[])/g,T;while((T=L.exec(I))!==null){if(vr(I,T.index))continue;let O=I.slice(0,T.index),_=O.trimEnd().slice(-1),D=new RegExp("[=(<[{,;|&?:+\\-*/!~^%]");if(!_||D.test(_)||O.trimEnd().endsWith("return")||O.trimEnd().endsWith("case"))m.push({filePath:h.filePath,line:R+1,column:T.index+2,ruleId:"style/space-unary-ops",message:"Unexpected space after '!'",severity:"warning"})}let A=/~\s+([a-zA-Z_$({[])/g;while((T=A.exec(I))!==null){if(vr(I,T.index))continue;m.push({filePath:h.filePath,line:R+1,column:T.index+2,ruleId:"style/space-unary-ops",message:"Unexpected space after '~'",severity:"warning"})}}return m},fix(s){let h=s;for(let m of wf)h=h.replace(new RegExp(`\\b${m}([^\\s;,)])`,"g"),`${m} $1`);return h=h.replace(/!\s+([a-zA-Z_$({[])/g,"!$1"),h=h.replace(/~\s+([a-zA-Z_$({[])/g,"~$1"),h}};var kf={meta:{docs:"Require space after // and /* in comments",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim(),L=I.indexOf("//");if(L!==-1){let A=I.slice(0,L),O=(A.match(/'/g)||[]).length,_=(A.match(/"/g)||[]).length,D=(A.match(/`/g)||[]).length;if(O%2===0&&_%2===0&&D%2===0){if(!A.match(/https?:$/)){let F=I.slice(L+2);if(F.length>0&&F[0]!==" "&&F[0]!=="\t"&&F[0]!=="/"&&F[0]!=="!")m.push({filePath:h.filePath,line:R+1,column:L+3,ruleId:"style/spaced-comment",message:"Missing space after '//'",severity:"warning",help:"Add a space after // in comments."})}}}let T=I.indexOf("/*");if(T!==-1&&I[T+2]!=="*"&&I[T+2]!=="!"){let A=I.slice(0,T),O=(A.match(/'/g)||[]).length,_=(A.match(/"/g)||[]).length,D=(A.match(/`/g)||[]).length;if(O%2===0&&_%2===0&&D%2===0){let F=I.slice(T+2);if(F.length>0&&F[0]!==" "&&F[0]!=="\t"&&F[0]!==`
|
|
186
187
|
`)m.push({filePath:h.filePath,line:R+1,column:T+3,ruleId:"style/spaced-comment",message:"Missing space after '/*'",severity:"warning",help:"Add a space after /* in comments."})}}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/(\/\/)([^\s/!])/,"$1 $2"),R=R.replace(/(\/\*)([^\s*!])/,"$1 $2"),m.push(R)}return m.join(`
|
|
187
|
-
`)}};var
|
|
188
|
-
`)m.push({filePath:h.filePath,line:R+1,column:A+2,ruleId:"style/switch-colon-spacing",message:"Missing space after colon in switch case",severity:"warning"})}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g,I=g.trim();if(
|
|
189
|
-
`)}};var
|
|
190
|
-
`)}};var
|
|
188
|
+
`)}};var $f=/^\s*(case\b.+?|default)\s*:/,Pf={meta:{docs:"Enforce spacing around colon in switch case/default clauses",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S)continue;let L=S.match($f);if(!L)continue;let T=L[1],A=I.indexOf(":",I.indexOf(T)+T.length);if(A===-1)continue;if(A>0&&I[A-1]===" ")m.push({filePath:h.filePath,line:R+1,column:A+1,ruleId:"style/switch-colon-spacing",message:"Unexpected space before colon in switch case",severity:"warning"});if(A+1<I.length&&I[A+1]!==" "&&I[A+1]!=="\t"&&I[A+1]!==`
|
|
189
|
+
`)m.push({filePath:h.filePath,line:R+1,column:A+2,ruleId:"style/switch-colon-spacing",message:"Missing space after colon in switch case",severity:"warning"})}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g,I=g.trim();if($f.test(I))R=R.replace(/(case\b.+?|default)\s+:/,"$1:"),R=R.replace(/(case\b.+?:|default:)(\S)/,"$1 $2");m.push(R)}return m.join(`
|
|
190
|
+
`)}};var vf="${",If={meta:{docs:"Disallow spaces inside template literal interpolation curly braces",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R];for(let S=I.indexOf(vf,0);S!==-1;S=I.indexOf(vf,S)){let L=S+2;if(L<I.length&&(I[L]===" "||I[L]==="\t")){if((I.slice(0,S).match(/`/g)||[]).length%2===1)m.push({filePath:h.filePath,line:R+1,column:L+1,ruleId:"style/template-curly-spacing",message:"Unexpected space after '${'",severity:"warning"})}let T=1,A=L;while(A<I.length&&T>0){if(I[A]==="{")T++;if(I[A]==="}")T--;if(T>0)A++}if(T===0&&A>0){let O=I[A-1];if(O===" "||O==="\t"){if((I.slice(0,S).match(/`/g)||[]).length%2===1)m.push({filePath:h.filePath,line:R+1,column:A,ruleId:"style/template-curly-spacing",message:"Unexpected space before '}'",severity:"warning"})}}S=L}}return m},fix(s){return s.replace(/\$\{\s+([^}]*?)\s+\}/g,"${$1}")}};var Bt=/([a-zA-Z_$][a-zA-Z0-9_$]*)\s+`/g;function Mf(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Cf=new Set(["return","case","typeof","void","delete","throw","new","in","of","await","yield","export","default","extends","else","instanceof"]),Sf={meta:{docs:"Disallow space between tag function and template literal",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;Bt.lastIndex=0;for(L=Bt.exec(I);L!==null;L=Bt.exec(I)){let T=L[1],A=L.index;if(Mf(I,A))continue;if(Cf.has(T))continue;let O=A+T.length;m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"style/template-tag-spacing",message:"Unexpected space between tag function and template literal",severity:"warning"})}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[];for(let R=0;R<m.length;R++){let I=m[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*")){g.push(I);continue}let L=I,T=[],A;Bt.lastIndex=0;for(A=Bt.exec(I);A!==null;A=Bt.exec(I)){let O=A[1],_=A.index;if(Mf(I,_))continue;if(Cf.has(O))continue;T.push({index:_,fullMatch:A[0],identifier:O})}for(let O=T.length-1;O>=0;O--){let _=T[O],D=_.index,F=D+_.fullMatch.length;L=L.slice(0,D)+_.identifier+"`"+L.slice(F)}g.push(L)}return g.join(`
|
|
191
|
+
`)}};var Ef={meta:{docs:"Require parentheses around immediately invoked function expressions (IIFEs)",recommended:!0},check(s,h){let m=[],g=/[^a-zA-Z_$](function\s*\([^)]*\)\s*\{[^}]*\})\s*\(/g,R;for(R=g.exec(s);R!==null;R=g.exec(s)){if(R.index>0&&s[R.index]==="(")continue;let I=s.slice(0,R.index).split(`
|
|
191
192
|
`).length,S=s.lastIndexOf(`
|
|
192
|
-
`,R.index),L=R.index-S;m.push({filePath:h.filePath,line:I,column:L,ruleId:"style/wrap-iife",message:"Wrap immediately invoked function expressions in parentheses",severity:"warning"})}return m},fix(s){return s.replace(/([^a-zA-Z_$(\n])(function\s*\([^)]*\)\s*\{[^}]*\})\s*\(/g,"$1($2)(")}};var
|
|
193
|
-
`)m.push({filePath:h.filePath,line:R+1,column:_+1,ruleId:"style/yield-star-spacing",message:"Missing space after * in yield expression",severity:"warning"})}}return m},fix(s,h){let m=s;return m=m.replace(/\byield\s+\*/g,"yield*"),m=m.replace(/\byield\*(\S)/g,"yield* $1"),m}};var
|
|
194
|
-
`)}};var
|
|
195
|
-
`)}};var
|
|
196
|
-
`){S
|
|
197
|
-
`)}};var
|
|
198
|
-
`)}};function
|
|
199
|
-
`)}};function
|
|
200
|
-
`)}};function
|
|
201
|
-
`)}};function
|
|
193
|
+
`,R.index),L=R.index-S;m.push({filePath:h.filePath,line:I,column:L,ruleId:"style/wrap-iife",message:"Wrap immediately invoked function expressions in parentheses",severity:"warning"})}return m},fix(s){return s.replace(/([^a-zA-Z_$(\n])(function\s*\([^)]*\)\s*\{[^}]*\})\s*\(/g,"$1($2)(")}};var Lf=/\byield\s*\*/g;function ug(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Tf={meta:{docs:"Enforce spacing around * in yield* expressions (no space before *, space after)",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;Lf.lastIndex=0;while((L=Lf.exec(I))!==null){let T=L.index;if(ug(I,T))continue;let A=L[0],O=T+A.length-1,_=O+1;if(A!=="yield*")m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"style/yield-star-spacing",message:"Unexpected space before * in yield expression",severity:"warning"});if(_<I.length&&I[_]!==" "&&I[_]!=="\t"&&I[_]!==`
|
|
194
|
+
`)m.push({filePath:h.filePath,line:R+1,column:_+1,ruleId:"style/yield-star-spacing",message:"Missing space after * in yield expression",severity:"warning"})}}return m},fix(s,h){let m=s;return m=m.replace(/\byield\s+\*/g,"yield*"),m=m.replace(/\byield\*(\S)/g,"yield* $1"),m}};var Af={name:"style",rules:{"brace-style":U(Gc),curly:U(lu),"max-statements-per-line":U(Iu),"if-newline":U(bu),"consistent-chaining":U(nu),"consistent-list-newline":U(ou),"indent-unindent":U(xu),"no-multi-spaces":Gu,"no-multiple-empty-lines":Ju,"no-trailing-spaces":Xu,"keyword-spacing":U($u),"arrow-spacing":U(Hc),"space-infix-ops":U(xf),"object-curly-spacing":U(ef),"spaced-comment":U(kf),"block-spacing":U(Zc),"space-before-blocks":U(ff),"comma-spacing":U(Qc),"semi-spacing":U(cf),"rest-spread-spacing":U(af),"generator-star-spacing":U(yu),"yield-star-spacing":U(Tf),"function-call-spacing":U(du),"template-tag-spacing":U(Sf),"no-whitespace-before-property":U(Du),"key-spacing":U(Ru),"computed-property-spacing":U(tu),"array-bracket-spacing":U(zc),"space-in-parens":U(yf),"template-curly-spacing":U(If),"space-unary-ops":U(Rf),"switch-colon-spacing":U(Pf),"comma-dangle":U(Xc),"arrow-parens":U(Kc),"space-before-function-paren":U(pf),"quote-props":U(of),"no-floating-decimal":U(Hu),"new-parens":U(Lu),"no-extra-parens":U(Au),"wrap-iife":U(Ef),"comma-style":U(eu),"dot-location":U(au),"operator-linebreak":U(sf),"multiline-ternary":U(Su),"padded-blocks":U(rf),"lines-between-class-members":U(vu),"no-mixed-operators":U(zu),"indent-binary-ops":U(fu),"no-tabs":U(Yu),"no-mixed-spaces-and-tabs":U(Zu)}};var Of={meta:{docs:"Enforce consistent member delimiter style in interfaces and type literals",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/),R=!1,I=0,S=0;for(let L=0;L<g.length;L++){let T=g[L],A=T.trim();if(!A||A.startsWith("//")||A.startsWith("*")||A.startsWith("/*"))continue;if(A.match(/\b(interface|type)\b.*\{/))R=!0,S=I+1;for(let O of A){if(O==="{")I++;if(O==="}")I--}if(R&&I<S){R=!1;continue}if(!R||I!==S)continue;if(A==="}"||A==="};"||A==="},")continue;if(A.endsWith(",")){if(A.startsWith("|")||A.startsWith("&"))continue;m.push({filePath:h.filePath,line:L+1,column:T.length,ruleId:"ts/member-delimiter-style",message:"Expected semicolon delimiter in interface, found comma",severity:"warning"})}if(!A.endsWith(";")&&!A.endsWith(",")&&!A.endsWith("{")&&!A.endsWith("(")){if(A.match(/^\w+[\s?]*:/)||A.match(/^\[/)||A.match(/^readonly\b/))m.push({filePath:h.filePath,line:L+1,column:T.length+1,ruleId:"ts/member-delimiter-style",message:"Missing semicolon delimiter in interface member",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[],g=!1,R=0,I=0;for(let S=0;S<h.length;S++){let L=h[S],T=L.trim();if(T.match(/\b(interface|type)\b.*\{/))g=!0,I=R+1;let A=R;for(let O of T){if(O==="{")R++;if(O==="}")R--}if(g&&R<I){g=!1,m.push(L);continue}if(g&&A===I&&T!=="}"&&T!=="};"&&T!=="},"){let O=L;if(T.endsWith(","))O=L.replace(/,\s*$/,";");m.push(O);continue}m.push(L)}return m.join(`
|
|
195
|
+
`)}};var _f={meta:{docs:"Disallow the use of the `any` type - it defeats the purpose of TypeScript type safety"},check:(s,h)=>{let m=[];if(!/\.tsx?$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S;if(R){let F=S.indexOf("*/");if(F>=0)S=S.slice(F+2),R=!1;else continue}let T=S.indexOf("/*"),A=S.indexOf("//");if(T>=0&&(A===-1||T<A)){let F=S.indexOf("*/",T+2);if(F>=0)S=S.slice(0,T)+S.slice(F+2);else R=!0,S=S.slice(0,T)}if(A>=0)S=S.slice(0,A);let O=S.replace(/(['"`])(?:(?!\1)[^\\]|\\.)*?\1/g,'""'),_=/\b(any)\b/g,D;while((D=_.exec(O))!==null){let F=D.index,N=O[F-1]||" ",W=O[F+3]||" ",B=O.slice(Math.max(0,F-10),F),j=O.slice(F+3,Math.min(O.length,F+10));if(/\w/.test(N)||/\w/.test(W))continue;if(/:/.test(B)||/</.test(B)||/\bas\s*$/.test(B)||/,/.test(B)||/\|/.test(B)||/&/.test(B)||/\[/.test(j)||/>/.test(j)||/,/.test(j)||/\|/.test(j)||/extends\s+$/.test(B)||/=\s*$/.test(B)){let K=L.indexOf("any",Math.max(0,F-5));m.push({filePath:h.filePath,line:I+1,column:K>=0?K+1:F+1,ruleId:"ts/no-explicit-any",message:"Unexpected `any` type. Specify a more precise type or use `unknown` if the type is truly unknown.",severity:"error",help:"Replace `any` with a specific type, `unknown`, or a generic type parameter"})}}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/:\s*any\b(?!\s*\))/g,(I)=>I.replace("any","unknown")),m.push(R)}return m.join(`
|
|
196
|
+
`)}};var Df={meta:{docs:"Require promises to be handled - must be awaited, returned, or have .catch() called"},check:(s,h)=>{let m=[];if(!/\.tsx?$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S;if(R){let D=S.indexOf("*/");if(D>=0)S=S.slice(D+2),R=!1;else continue}let T=S.indexOf("/*"),A=S.indexOf("//");if(T>=0&&(A===-1||T<A)){let D=S.indexOf("*/",T+2);if(D>=0)S=S.slice(0,T)+S.slice(D+2);else R=!0,S=S.slice(0,T)}if(A>=0)S=S.slice(0,A);let O=S.replace(/(['"`])(?:(?!\1)[^\\]|\\.)*?\1/g,'""');if(/\b(?:await|return|void)\s/.test(O))continue;if(/\.(?:then|catch|finally)\s*\(/.test(O))continue;let _=[/\b(fetch|axios|request)\s*\(/,/\b[\w$]*(?:async|Async|load|Load|get|Get|post|Post|put|Put|delete|Delete|save|Save|update|Update|fetch|Fetch)[\w$]*\s*\(/,/\bnew\s+Promise\s*\(/,/\bPromise\s*\.\s*(?:resolve|reject|all|allSettled|race|any)\s*\(/];for(let D of _){let F=O.match(D);if(!F)continue;let N=O.indexOf(F[0]),W=O.slice(0,N).trim();if(/\b(?:const|let|var)\s+[\w$]+\s*=\s*$/.test(W))continue;if(/[\w$]+\s*=\s*$/.test(W))continue;if(/\breturn\s+$/.test(W))continue;if(/\(\s*$/.test(W)||/,\s*$/.test(W))continue;let B=O.slice(N+F[0].length),j=1,z=F[0].length;while(z<B.length&&j>0){if(B[z]==="(")j++;else if(B[z]===")")j--;z++}let K=B.slice(z).trim();if(/^\.(?:then|catch|finally)\s*\(/.test(K))continue;if(K===""||K.startsWith(";")){let V=L.indexOf(F[0]);m.push({filePath:h.filePath,line:I+1,column:V>=0?V+1:N+1,ruleId:"ts/no-floating-promises",message:"Promise returned by this call is not handled. Add await, return, .catch(), or void.",severity:"error",help:"Either await the promise, return it, add .catch() to handle errors, or use void to explicitly mark as fire-and-forget"});break}}}return m}};var Ff={meta:{docs:"Disallow promises in places not designed to handle them (conditionals, logical expressions)"},check:(s,h)=>{let m=[];if(!/\.tsx?$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S;if(R){let B=S.indexOf("*/");if(B>=0)S=S.slice(B+2),R=!1;else continue}let T=S.indexOf("/*"),A=S.indexOf("//");if(T>=0&&(A===-1||T<A)){let B=S.indexOf("*/",T+2);if(B>=0)S=S.slice(0,T)+S.slice(B+2);else R=!0,S=S.slice(0,T)}if(A>=0)S=S.slice(0,A);let O=S.replace(/(['"`])(?:(?!\1)[^\\]|\\.)*?\1/g,'""'),_=O.match(/\bif\s*\(\s*(!?)\s*([\w$]+\s*\([^)]*\))/);if(_){let B=_[1],j=_[2];if(/async|Async|fetch|Fetch|load|Load|get|Get|save|Save/.test(j)){let z=O.slice(0,O.indexOf(_[0])),K=O.slice(O.indexOf("if (")+4);if(!/\bawait\s/.test(K)){let V=L.indexOf(j);m.push({filePath:h.filePath,line:I+1,column:V>=0?V+1:1,ruleId:"ts/no-misused-promises",message:"Promise used in conditional expression without await. Promises are always truthy.",severity:"error",help:"Add await before the async call in the condition"})}}}let D=/(?:async|Async|fetch|Fetch|load|Load|get|Get|save|Save|Promise\.)[\w$]*\s*\([^)]*\)/g,F;while((F=D.exec(O))!==null){let B=F.index,j=F[0],z=O.slice(Math.max(0,B-10),B),K=O.slice(B+j.length,Math.min(O.length,B+j.length+10));if(/(?:&&|\|\|)\s*$/.test(z)||/^\s*(?:&&|\|\|)/.test(K)){if(!/\bawait\s*$/.test(z)){let G=L.indexOf(j,Math.max(0,B-5));m.push({filePath:h.filePath,line:I+1,column:G>=0?G+1:B+1,ruleId:"ts/no-misused-promises",message:"Promise used in logical expression without await. This will not work as expected.",severity:"error",help:"Add await before the async call or restructure the logic"})}}let V=O.slice(Math.max(0,B-20),B);if(/\?\s*$/.test(z)||/\?[^:]*$/.test(V)){if(!/\bawait\s*$/.test(z)){let G=L.indexOf(j,Math.max(0,B-5));m.push({filePath:h.filePath,line:I+1,column:G>=0?G+1:B+1,ruleId:"ts/no-misused-promises",message:"Promise used in ternary expression without await.",severity:"error",help:"Add await before the async call"})}}}let N=O.match(/\b(?:while|for)\s*\([^)]*(?:async|Async|fetch|Fetch|load|Load|get|Get)[\w$]*\s*\([^)]*\)/);if(N){if(!/\bawait\s/.test(N[0])){let B=L.indexOf(N[0]);m.push({filePath:h.filePath,line:I+1,column:B>=0?B+1:1,ruleId:"ts/no-misused-promises",message:"Promise used in loop condition without await. This will cause unexpected behavior.",severity:"error",help:"Add await before the async call in the loop condition"})}}let W=O.match(/\.(forEach|map|filter|reduce|every|some|find|findIndex)\s*\(\s*async\s*(?:\(|[\w$]+\s*=>)/);if(W){if(W[1]==="forEach"){let j=L.indexOf(W[0]);m.push({filePath:h.filePath,line:I+1,column:j>=0?j+1:1,ruleId:"ts/no-misused-promises",message:"async callback in forEach - forEach does not wait for promises to resolve.",severity:"error",help:"Use for...of loop with await, or Promise.all() with map()"})}}}return m}};var Nf={meta:{docs:"Disallow require() in TypeScript files; prefer ESM imports"},check:(s,h)=>{let m=[];if(!/\.ts$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S;if(R){let D=L.indexOf("*/");if(D>=0)L=L.slice(D+2),R=!1;else continue}let T=L.indexOf("/*"),A=L.indexOf("//");if(T>=0&&(A===-1||T<A)){let D=L.indexOf("*/",T+2);if(D>=0)L=L.slice(0,T)+L.slice(D+2);else R=!0,L=L.slice(0,T)}if(A>=0)L=L.slice(0,A);let O=L.trim();if(!O)continue;if(/\bimport\s*\(/.test(O))continue;let _=O.indexOf("require(");if(_>=0){m.push({filePath:h.filePath,line:I+1,column:S.indexOf("require(")+1||_+1,ruleId:"ts/no-require-imports",message:"Do not use require() in TypeScript files. Use ESM import syntax instead.",severity:"error"});continue}if(/^import\s+(?:\S.*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])=\s*require\s*\(/.test(O)){let D=S.indexOf("require(");m.push({filePath:h.filePath,line:I+1,column:D>-1?D+1:1,ruleId:"ts/no-require-imports",message:"Do not use require() in TypeScript files. Use ESM import syntax instead.",severity:"error"})}}return m}};var Wf={meta:{docs:"Disallow top-level await in TypeScript/JavaScript files"},check:(s,h)=>{let m=[],g=h.filePath.split(".").pop()||"";if(!["ts","tsx","mts","cts","js","mjs","cjs"].includes(g))return m;let R=_s(s),I=0,S=0,L=1;for(let T=0;T<R.length;T++){let A=R[T];if(S++,A===`
|
|
197
|
+
`){L++,S=0;continue}if(A==="{"){I++;continue}if(A==="}"){if(I>0)I--;continue}if(A==="a"&&R.slice(T,T+5)==="await"){let O=R.slice(Math.max(0,T-6),T),_=/for\s+$/.test(O),D=T===0||/[^$\w]/.test(R[T-1]),F=/[^$\w]/.test(R[T+5]||" ");if(!_&&D&&F&&I===0)m.push({filePath:h.filePath,line:L,column:S,ruleId:"ts/no-top-level-await",message:"Do not use top-level await",severity:"error"});T+=4,S+=4}}return m}};var Bf={meta:{docs:"Disallow `exports =` in TypeScript; prefer ESM export default"},check:(s,h)=>{let m=[],g=h.filePath.split(".").pop()||"";if(!["ts","tsx","mts","cts","d.ts"].includes(g))return m;let R=s.split(/\r?\n/);for(let I=0;I<R.length;I++){let T=R[I].replace(/\/\*.*?\*\//g,"").replace(/\/\/.*$/,"").match(/\bexports\s*=\s*/);if(T)m.push({filePath:h.filePath,line:I+1,column:(T.index||0)+1,ruleId:"ts/no-ts-export-equal",message:"Use ESM `export default` instead of `exports =`",severity:"error"})}return m}};var jf={meta:{docs:"Disallow assignment of `any` typed values to variables - unsafe assignments bypass type checking"},check:(s,h)=>{let m=[];if(!/\.tsx?$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S;if(R){let z=S.indexOf("*/");if(z>=0)S=S.slice(z+2),R=!1;else continue}let T=S.indexOf("/*"),A=S.indexOf("//");if(T>=0&&(A===-1||T<A)){let z=S.indexOf("*/",T+2);if(z>=0)S=S.slice(0,T)+S.slice(z+2);else R=!0,S=S.slice(0,T)}if(A>=0)S=S.slice(0,A);let O=S.replace(/(['"`])(?:(?!\1)[^\\]|\\.)*?\1/g,'""'),_=/(\w+)\s+as\s+any/g,D;while((D=_.exec(O))!==null){let z=D[1],K=D.index,V=O.slice(K+D[0].length).trim(),G=O.slice(0,K).trim();if(/=\s*$/.test(G)&&!/==|===|!=|!==/.test(G)){let J=L.indexOf(D[0]);m.push({filePath:h.filePath,line:I+1,column:J>=0?J+1:K+1,ruleId:"ts/no-unsafe-assignment",message:"Unsafe assignment: value cast to `any` is being assigned. This bypasses type checking.",severity:"error",help:"Avoid casting to `any` or use a more specific type"})}}let F=["JSON.parse","eval","Function","require"];for(let z of F){let K=new RegExp(`\\b${z.replace(".","\\.")}\\s*\\(`,"g");K.lastIndex=0;while((D=K.exec(O))!==null){let V=D.index,G=O.slice(0,V).trim(),J=G.match(/(?:const|let|var)\s+([\w$]+)\s*=\s*$/);if(J){let Z=J[1];if(!new RegExp(`\\b${Z}\\s*:\\s*\\w+`).test(O)){let ee=L.indexOf(D[0]);m.push({filePath:h.filePath,line:I+1,column:ee>=0?ee+1:V+1,ruleId:"ts/no-unsafe-assignment",message:`Unsafe assignment from ${z}() without type annotation. This function returns 'any'.`,severity:"error",help:`Add a type annotation to ${Z} or use a type assertion with a specific type`})}}let Y=G.match(/([\w$.]+)\s*=\s*$/),se=/(?:const|let|var)\s+/.test(G);if(Y&&!J&&!se){let Z=L.indexOf(D[0]);m.push({filePath:h.filePath,line:I+1,column:Z>=0?Z+1:V+1,ruleId:"ts/no-unsafe-assignment",message:`Unsafe assignment from ${z}() which returns 'any'.`,severity:"error",help:"Consider adding a type assertion with a specific type"})}}}let N=/(?:const|let|var)\s+([\w$]+)\s*:\s*any\s*=/,W=O.match(N);if(W){let z=W[1],K=L.indexOf(W[0]);m.push({filePath:h.filePath,line:I+1,column:K>=0?K+1:1,ruleId:"ts/no-unsafe-assignment",message:`Variable '${z}' is explicitly typed as 'any'. This defeats TypeScript's type safety.`,severity:"error",help:"Use a more specific type or `unknown` instead of `any`"})}let B=/(?:const|let|var)\s+(?:\{[^}]+\}|\[[^\]]+\])\s*=\s*([\w$]+)/,j=O.match(B);if(j){let z=j[1];if(/^(?:params|query|body|req|res|response|data|result)$/.test(z));}}return m}};var Uf={meta:{docs:"Prefer nullish coalescing operator (??) over logical OR (||) when checking for null/undefined"},check:(s,h)=>{let m=[];if(!/\.tsx?$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S.split(""),T=L.length,A=0;if(R){let N=S.indexOf("*/");if(N<0)continue;for(let W=0;W<=N+1;W++)L[W]=" ";R=!1,A=N+2}let O=null;for(;A<T;A++){let N=L[A];if(O){if(N==="\\"){if(L[A]=" ",A+1<T)L[A+1]=" ",A++;continue}if(N===O){O=null;continue}L[A]=" ";continue}if(N==="/"&&L[A+1]==="/"){for(let W=A;W<T;W++)L[W]=" ";break}if(N==="/"&&L[A+1]==="*"){let W=S.indexOf("*/",A+2);if(W<0){for(let B=A;B<T;B++)L[B]=" ";R=!0;break}for(let B=A;B<=W+1;B++)L[B]=" ";A=W+1;continue}if(N==='"'||N==="'"||N==="`")O=N}let _=L.join(""),D=/\|\|/g,F;while((F=D.exec(_))!==null){let N=F.index,W=N-1,B=0,j=0,z=0;while(W>=0){let Z=_[W];if(Z===")")B++;else if(Z==="("){if(B===0){W++;break}B--}else if(Z==="}")j++;else if(Z==="{"){if(j===0){W++;break}j--}else if(Z==="]")z++;else if(Z==="["){if(z===0){W++;break}z--}else if(B===0&&j===0&&z===0){if(new RegExp("[;,=:?]").test(Z)){W++;break}if(Z==="&"||Z==="|"){W++;break}}W--}if(W<0)W=0;let K=_.slice(W,N).trim();if(/[<>!=]/.test(K))continue;if(/\b(?:true|false)\b/.test(K))continue;let V=N+2,G=V;B=0,j=0,z=0;while(G<_.length){let Z=_[G];if(Z==="(")B++;else if(Z===")"){if(B===0)break;B--}else if(Z==="{")j++;else if(Z==="}"){if(j===0)break;j--}else if(Z==="[")z++;else if(Z==="]"){if(z===0)break;z--}else if(B===0&&j===0&&z===0){if(new RegExp("[;,?:]").test(Z))break;if(Z==="&"||Z==="|"&&_[G+1]==="|")break}G++}let J=_.slice(V,G).trim(),Y=/^["'`\d]/.test(J)||/^\{/.test(J)||/^[\w$]+\(/.test(J)||/^[\w$.[\]]+$/.test(J),se=/^[\w$]+$/.test(K)||/^[\w$.?[\]()]+$/.test(K);if(Y&&se)m.push({filePath:h.filePath,line:I+1,column:N+1,ruleId:"ts/prefer-nullish-coalescing",message:"Prefer nullish coalescing operator (??) over logical OR (||)",severity:"error",help:'Use `??` instead of `||` to only handle null/undefined, not falsy values like 0, "", or false'})}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g,I=new RegExp("(\\b[\\w$.]+)\\s*\\|\\|\\s*([^|&]+?)(?=\\s*[;,)\\]}]|$)","g");R=R.replace(I,(S,L,T)=>{if(/\b(?:true|false)\b/.test(T.trim()))return S;return`${L} ?? ${T}`}),m.push(R)}return m.join(`
|
|
198
|
+
`)}};var zf={meta:{docs:"Prefer optional chaining (?.) over chained logical AND (&&) for property access"},check:(s,h)=>{let m=[];if(!/\.tsx?$/.test(h.filePath))return m;let g=s.split(/\r?\n/),R=!1;for(let I=0;I<g.length;I++){let S=g[I],L=S;if(R){let W=S.indexOf("*/");if(W>=0)S=S.slice(W+2),R=!1;else continue}let T=S.indexOf("/*"),A=S.indexOf("//");if(T>=0&&(A===-1||T<A)){let W=S.indexOf("*/",T+2);if(W>=0)S=S.slice(0,T)+S.slice(W+2);else R=!0,S=S.slice(0,T)}if(A>=0)S=S.slice(0,A);let O=S.replace(/(['"`])(?:(?!\1)[^\\]|\\.)*?\1/g,'""'),_=/(\b[\w$]+)\s*&&\s*\1\.([\w$]+)/g,D;while((D=_.exec(O))!==null){let W=D[1],B=D[2],j=D.index,z=L.indexOf(D[0],Math.max(0,j-5));m.push({filePath:h.filePath,line:I+1,column:z>=0?z+1:j+1,ruleId:"ts/prefer-optional-chain",message:`Prefer optional chaining over && for property access: ${W}?.${B}`,severity:"error",help:`Use \`${W}?.${B}\` instead of \`${W} && ${W}.${B}\``})}let F=/([\w$]+\.[\w$.]+)\s*&&\s*\1\.([\w$]+)/g;F.lastIndex=0;while((D=F.exec(O))!==null){let W=D[1],B=D[2],j=D.index,z=L.indexOf(D[0],Math.max(0,j-5));m.push({filePath:h.filePath,line:I+1,column:z>=0?z+1:j+1,ruleId:"ts/prefer-optional-chain",message:`Prefer optional chaining over && for nested property access: ${W}?.${B}`,severity:"error",help:`Use \`${W}?.${B}\` instead of \`${W} && ${W}.${B}\``})}let N=O.split(/\s*&&\s*/);if(N.length>=3)for(let W=0;W<N.length-2;W++){let B=N[W].trim(),j=N[W+1].trim(),z=N[W+2].trim();if(j.startsWith(`${B}.`)&&z.startsWith(`${j}.`)){let K=L.indexOf(B);m.push({filePath:h.filePath,line:I+1,column:K>=0?K+1:1,ruleId:"ts/prefer-optional-chain",message:"Prefer optional chaining over multiple && checks for nested properties",severity:"error",help:`Use optional chaining like \`${B}?.${j.slice(B.length+1)}?.${z.slice(j.length+1)}\``});break}}}return m},fix:(s)=>{let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/(\b[\w$]+)\s*&&\s*\1\.([\w$]+)/g,"$1?.$2"),R=R.replace(/([\w$]+\.[\w$.]+)\s*&&\s*\1\.([\w$]+)/g,"$1?.$2"),m.push(R)}return m.join(`
|
|
199
|
+
`)}};function fg(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var qf=/([a-zA-Z_$][a-zA-Z0-9_$]*\??)\s*:\s*([A-Z][a-zA-Z0-9_$<>[\]|&]*|string|number|boolean|null|undefined|void|never|any|unknown|object|symbol|bigint)/g,Kf={meta:{docs:"Require consistent spacing around type annotation colons",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L;qf.lastIndex=0;while((L=qf.exec(I))!==null){if(fg(I,L.index))continue;let T=L[0],A=T.indexOf(":"),O=L.index+A;if(A>0&&T[A-1]===" "&&!T.startsWith("?")){if(!L[1].endsWith("?")||T[A-1]===" "){if(I[O-1]===" "&&!/\?\s*$/.test(L[1]))m.push({filePath:h.filePath,line:R+1,column:O+1,ruleId:"ts/type-annotation-spacing",message:"Unexpected space before colon in type annotation",severity:"warning"})}}if(O+1<I.length&&I[O+1]!==" "&&I[O+1]!=="\t")m.push({filePath:h.filePath,line:R+1,column:O+2,ruleId:"ts/type-annotation-spacing",message:"Missing space after colon in type annotation",severity:"warning"})}}return m},fix(s){let h=s.split(/\r?\n/),m=[];for(let g of h){let R=g;R=R.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*\??)\s*:\s*([A-Z][a-zA-Z0-9_$<>[\]|&]*|string|number|boolean|null|undefined|void|never|any|unknown|object|symbol|bigint)/g,"$1: $2"),m.push(R)}return m.join(`
|
|
200
|
+
`)}};function Vf(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Hf=/([A-Za-z_$][A-Za-z0-9_$]*)\s*<(\s+)/g,Zf=/(\s+)>(?!=)/g,mg=/([A-Za-z_$][A-Za-z0-9_$]*)\s*<\s+/g,hg=/\s+>(?!=)/g,Gf={meta:{docs:"Disallow spaces inside TypeScript generic angle brackets",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;Hf.lastIndex=0;let L;while((L=Hf.exec(I))!==null){let T=L.index+L[1].length,A=I.indexOf("<",T);if(A===-1)continue;if(Vf(I,A))continue;m.push({filePath:h.filePath,line:R+1,column:A+2,ruleId:"ts/type-generic-spacing",message:"Unexpected space after '<' in generic type",severity:"warning"})}Zf.lastIndex=0;while((L=Zf.exec(I))!==null){let T=L.index+L[1].length;if(Vf(I,T))continue;let A=I.slice(0,T);if(!/[A-Za-z_$][A-Za-z0-9_$]*\s*</.test(A))continue;m.push({filePath:h.filePath,line:R+1,column:T+1,ruleId:"ts/type-generic-spacing",message:"Unexpected space before '>' in generic type",severity:"warning"})}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[];for(let R of m){let I=R.trim();if(!I||I.startsWith("//")||I.startsWith("*")||I.startsWith("/*")){g.push(R);continue}let S=R;if(S=S.replace(mg,(L,T)=>`${T}<`),/[A-Za-z_$][A-Za-z0-9_$]*\s*</.test(S))S=S.replace(hg,">");g.push(S)}return g.join(`
|
|
201
|
+
`)}};function dg(s,h){let m=s.slice(0,h);if(m.includes("//"))return!0;let g=(m.match(/'/g)||[]).length,R=(m.match(/"/g)||[]).length,I=(m.match(/`/g)||[]).length;return g%2===1||R%2===1||I%2===1}var Jf=/([a-zA-Z_$][a-zA-Z0-9_$?]*):(\S)/g,Qf={meta:{docs:"Require space after colon in named tuple members",recommended:!0},check(s,h){let m=[],g=s.split(/\r?\n/);for(let R=0;R<g.length;R++){let I=g[R],S=I.trim();if(!S||S.startsWith("//")||S.startsWith("*")||S.startsWith("/*"))continue;let L=Yf(I);for(let T of L){Jf.lastIndex=0;let A;while((A=Jf.exec(T.text))!==null){let _=T.start+A.index+A[1].length;if(dg(I,_))continue;if(!Xf(I))continue;m.push({filePath:h.filePath,line:R+1,column:_+2,ruleId:"ts/type-named-tuple-spacing",message:"Missing space after colon in named tuple member",severity:"warning"})}}}return m},fix(s,h){let m=s.split(/\r?\n/),g=[];for(let R of m){let I=R.trim();if(!I||I.startsWith("//")||I.startsWith("*")||I.startsWith("/*")){g.push(R);continue}if(!Xf(R)){g.push(R);continue}let S=R,L=Yf(R);for(let T=L.length-1;T>=0;T--){let A=L[T],O=A.text.replace(/([a-zA-Z_$][a-zA-Z0-9_$?]*):(\S)/g,"$1: $2");if(O!==A.text)S=S.slice(0,A.start)+O+S.slice(A.start+A.text.length)}g.push(S)}return g.join(`
|
|
202
|
+
`)}};function Yf(s){let h=[],m=0,g=-1;for(let R=0;R<s.length;R++)if(s[R]==="["){if(m===0)g=R;m++}else if(s[R]==="]"){if(m--,m===0&&g>=0)h.push({start:g,text:s.slice(g,R+1)}),g=-1}return h}function Xf(s){let h=s.trim();return/\btype\s/.test(h)||/:\s*\[/.test(h)||/=\s*\[/.test(h)||/\bas\s/.test(h)||/<[^>]*\[/.test(h)||/\bextends\s/.test(h)||/\bimplements\s/.test(h)}var em={name:"ts",rules:{"no-require-imports":U(Nf),"no-top-level-await":U(Wf),"no-ts-export-equal":U(Bf),"no-explicit-any":U(_f),"prefer-nullish-coalescing":U(Uf),"prefer-optional-chain":U(zf),"no-floating-promises":U(Df),"no-misused-promises":U(Ff),"no-unsafe-assignment":U(jf),"member-delimiter-style":U(Of),"type-annotation-spacing":U(Kf),"type-generic-spacing":U(Gf),"type-named-tuple-spacing":U(Qf)}};var tm={name:"unused-imports",rules:{"no-unused-vars":U(gt),"no-unused-imports":U(gt)}};function Ir(){return[Zo,sl,uc,cc,Af,dc,em,wa,Bc,jc,$a,gl,Da,tm,Pa]}var Mr=null;function rm(){if(!Mr)Mr=new wt("pickier",{showTags:!1});return Mr}function jt(...s){if(n.TRACE)rm().debug("[pickier:trace]",s)}async function sm(s,h,m){let g,R=new Promise((I,S)=>{g=setTimeout(()=>S(Error(`Timeout after ${h}ms at ${m}`)),h)});try{let I=await Promise.race([s,R]);return clearTimeout(g),I}catch(I){throw rm().error(`[pickier:error] ${m} failed:`,I?.message||I),jt("withTimeout error:",m,I),I}}function om(s){if(s.length===0)return"";let h=new Map;for(let g of s){let R=h.get(g.filePath)||[];R.push(g),h.set(g.filePath,R)}let m="";for(let[g,R]of h){m+=`
|
|
202
203
|
${e.bold(`\x1B[4m${g}\x1B[24m`)}
|
|
203
|
-
`;let I;try{I=
|
|
204
|
+
`;let I;try{I=im(g,"utf8")}catch{for(let L of R){let T=L.severity==="error"?e.red("error"):e.yellow("warn ");m+=` ${L.line}:${L.column} ${T} ${L.message} ${e.blue(L.ruleId)}
|
|
204
205
|
`}continue}let S=I.split(/\r?\n/);for(let L of R){let T=L.severity==="error"?e.red("!"):e.yellow("!"),A=e.blue(L.ruleId);m+=`
|
|
205
206
|
${T} ${A}: ${L.message}
|
|
206
207
|
`;let O=2,_=2,D=Math.max(1,L.line-O),F=Math.min(S.length,L.line+_),W=String(F).length;m+=` ${e.gray(" ,-")}${e.gray(`[:${L.line}:${L.column}]`)}
|
|
@@ -210,17 +211,17 @@ ${e.bold(`\x1B[4m${g}\x1B[24m`)}
|
|
|
210
211
|
`;else m+=` ${e.gray(j)} ${e.gray("| ")}${z}
|
|
211
212
|
`}if(m+=` ${e.gray(" `----")}
|
|
212
213
|
`,L.help)m+=` ${e.blue("help")}: ${L.help}
|
|
213
|
-
`}}return m}function
|
|
214
|
+
`}}return m}function lm(s){if(s.length===0)return"";let h=new Map;for(let g of s){let R=h.get(g.filePath)||[];R.push(g),h.set(g.filePath,R)}let m="";for(let[g,R]of h){m+=`
|
|
214
215
|
${e.bold(`\x1B[4m${g}\x1B[24m`)}
|
|
215
216
|
`;for(let I of R){let S=I.severity==="error"?e.red("error"):e.yellow("warn "),T=`${I.line}:${I.column}`.padStart(6),A=60,O=I.message.padEnd(60);m+=`${T} ${S} ${O} ${e.blue(I.ruleId)}
|
|
216
|
-
`}}return m}async function M(s,h){Bt("runFormat:start",{globs:s,options:h});let m=await u(h.config),g=s.length?s:["."],R=d(g);Bt("patterns",R);let I=new Set((h.ext||m.format.extensions.join(",")).split(",").map((B)=>{let j=B.trim();return j.startsWith(".")?j:`.${j}`})),S=n.TIMEOUT_MS,T=R.some((B)=>{let j=B.replace(/\/?\*\*(?:\/\*+)?$/,"");return!(ug(j)?j:fg(process.cwd(),j)).startsWith(process.cwd())})?l(o):l(m.ignores),A=c(T),O=[];if(R.length===1&&/\*\*\/\*$/.test(R[0])){let B=R[0].replace(/\/?\*\*\/\*$/,"");try{let{readdirSync:j,statSync:z}=await import("fs"),{join:K}=await import("path"),V=[B];while(V.length){let J=V.pop(),H=j(J);for(let Y of H){let se=K(J,Y),G=z(se);if(A(se))continue;if(G.isDirectory())V.push(se);else O.push(se)}}}catch{O=await Jf(r(R,{dot:!1,ignore:T,onlyFiles:!0,absolute:!0}),S,"glob")}}else O=await Jf(r(R,{dot:!1,ignore:T,onlyFiles:!0,absolute:!0}),S,"glob");Bt("globbed entries",O.length);let D=O.filter((B)=>{if(A(B))return!1;let j=B.lastIndexOf(".");if(j<0)return!0;let z=B.slice(j);return I.has(z)});Bt("filtered files",D.length);let F=0,N=[];for(let B of D){Bt("format start",Gf(process.cwd(),B));let j=Yf(B,"utf8"),z=f(j,m,B),K=z!==j;if(h.write){if(K)cg(B,z,"utf8")}if(K)N.push(Gf(process.cwd(),B));F++}let W=N.length;if(W>0){for(let B of N)console.log(e.gray(` ${B}`));console.log(h.write?e.gray(`Formatted ${W} of ${F} file(s).`):e.yellow(`${W} of ${F} file(s) need formatting. Run with --write to fix.`))}else if(h.verbose!==void 0?h.verbose:m.verbose)console.log(e.gray(`Checked ${F} files, all formatted.`));return h.check&&W>0?1:0}var $r=null;function $e(){if(!$r)$r=new wt("pickier:lint",{showTags:!1});return $r}function Ke(...s){if(n.TRACE)$e().error("[pickier:trace]",s)}async function C(s,h,m="untitled",g){if(g?.aborted)throw Error("AbortError");let R=$t(s),I=Pt(s),S=sn(m,s,h,R,I);if(g?.aborted)throw Error("AbortError");try{let L=await Mr(m,s,h);for(let T of L){if(g?.aborted)throw Error("AbortError");if(tt(T.ruleId,T.line,R))continue;if(I.has(T.line)&&vr(T.ruleId))continue;S.push({filePath:T.filePath,line:T.line,column:T.column,ruleId:T.ruleId,message:T.message,severity:T.severity,...T.help&&{help:T.help}})}}catch{}return S}function x(s,h,m="untitled"){let g=hm(m,s,h,$t(s),Pt(s));if(g=mm(m,g,h),dm(m,g,h))g=Rg(g,h,$t(g),Pt(g));return g}async function E(s,h,m){Ke("runLintProgrammatic:start",{globs:s,options:h});let g=await u(h.config);if(m?.aborted)throw Error("AbortError");let R=s.length?s:["."],I=d(R),S=h.ext||g.lint.extensions.join(","),L=new Set(S.split(",").map((te)=>{let ie=te.trim();return ie.startsWith(".")?ie:`.${ie}`})),T=n.TIMEOUT_MS,O=I.some((te)=>{let ie=te.replace(/\/?\*\*\/*\*\*$/,""),X=jt(ie)?ie:Ut(process.cwd(),ie),ne=process.cwd();return X!==ne&&!X.startsWith(ne+cm)})?l(o):l(g.ignores),_=c(O),D=[];if(I.length===1&&!/[*?[\]{}()!]/.test(I[0]))try{if(ni(I[0]).isFile())D=[jt(I[0])?I[0]:Ut(process.cwd(),I[0])]}catch{}let N=I.length===1&&/\*\*\/*\*$/.test(I[0]);if(!D.length&&N){let te=I[0].replace(/\/?\*\*\/*\*\*$/,""),ie=jt(te)?te:Ut(process.cwd(),te);try{let X=[ie];while(X.length){if(m?.aborted)throw Error("AbortError");let ne=X.pop(),oe=om(ne);for(let ee of oe){let q=am(ne,ee),Q=ni(q);if(_(q))continue;if(Q.isDirectory())X.push(q);else D.push(q)}}}catch{D=await nn(r(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob")}}else if(!D.length)D=await nn(r(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob");if(m?.aborted)throw Error("AbortError");let W=0,B=0,j=0,z=0,K=0,V=[];for(let te of D){if(W++,te.replace(/\\/g,"/").includes("/node_modules/")){j++;continue}if(_(te)){z++;continue}if(!w(te,L)){K++;continue}V.push(te),B++}Ke("filter:programmatic",{total:W,included:B,node_modules:j,ignored:z,wrongExt:K});let J=n.CONCURRENCY,se=(await um(V,J,async(te)=>{if(m?.aborted)throw Error("AbortError");let ie=lm(te,"utf8"),X=$t(ie),ne=Pt(ie),oe=sn(te,ie,g,X,ne);try{let ee=await Mr(te,ie,g);for(let q of ee){if(m?.aborted)throw Error("AbortError");if(tt(q.ruleId,q.line,X))continue;if(ne.has(q.line)&&vr(q.ruleId))continue;oe.push({filePath:q.filePath,line:q.line,column:q.column,ruleId:q.ruleId,message:q.message,severity:q.severity,...q.help&&{help:q.help}})}}catch{}{let ee=new Set;oe=oe.filter((q)=>{let Q=`${q.line}:${q.column}:${q.ruleId}`;if(ee.has(Q))return!1;return ee.add(Q),!0})}if(h.fix){let ee=hm(te,ie,g,X,ne);if(ee=mm(te,ee,g),ee!==ie){let q=$t(ee),Q=Pt(ee);if(oe=sn(te,ee,g,q,Q),!h.dryRun)Pr(te,ee,"utf8")}}return oe})).flat(),G=se.filter((te)=>te.severity==="error").length,le=se.filter((te)=>te.severity==="warning").length;return{errors:G,warnings:le,issues:se}}function mg(s){return s.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function hg(s){return s.replace(/-([a-z])/g,(h,m)=>m.toUpperCase())}function $t(s){let h=new Map,m=new Set,g=new Map,R=new Map,I=s.split(/\r?\n/),S=new Set;for(let A=0;A<I.length;A++){let O=I[A].trim(),_=A+1,D=O.match(/^\/\/\s*(?:eslint|pickier)-disable-next-line(?:\s+(\S.*))?$/);if(D){let j=D[1]?.replace(/\s+--\s.*$/,""),z=j?j.split(",").map((K)=>K.trim()).filter(Boolean):["*"];if(z.length>0){let K=_+1,V=h.get(K)||new Set;for(let J of z)V.add(J);h.set(K,V)}continue}let F=O.match(/^\/\*\s*(?:eslint|pickier)-disable(?:\s+([^*]+))?\s*\*\//);if(F){let j=F[1]?.trim().replace(/\s+--\s.*$/,"");if(!j||j==="")g.set(_,new Set(["*"])),S.add("*");else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=g.get(_)||new Set;for(let V of z)K.add(V),S.add(V);g.set(_,K)}if(A===0)if(!j||j==="")m.add("*");else{let z=j.split(",").map((K)=>K.trim()).filter(Boolean);for(let K of z)m.add(K)}continue}let N=O.match(/^\/\*\s*(?:eslint|pickier)-enable(?:\s+([^*]+))?\s*\*\//);if(N){let j=N[1]?.trim();if(!j||j==="")R.set(_,new Set(["*"])),S.clear();else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=R.get(_)||new Set;for(let V of z)K.add(V),S.delete(V);R.set(_,K)}continue}let W=O.match(/^\/\/\s*(?:eslint|pickier)-disable(?:\s+(\S.*))?$/);if(W){let j=W[1]?.trim().replace(/\s+--\s.*$/,"");if(!j||j==="")g.set(_,new Set(["*"])),S.add("*");else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=g.get(_)||new Set;for(let V of z)K.add(V),S.add(V);g.set(_,K)}continue}let B=O.match(/^\/\/\s*(?:eslint|pickier)-enable(?:\s+(\S.*))?$/);if(B){let j=B[1]?.trim();if(!j||j==="")R.set(_,new Set(["*"])),S.clear();else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=R.get(_)||new Set;for(let V of z)K.add(V),S.delete(V);R.set(_,K)}}}let L=Array.from(g.keys()).sort((A,O)=>A-O),T=Array.from(R.keys()).sort((A,O)=>A-O);return{nextLine:h,fileLevel:m,rangeDisable:g,rangeEnable:R,sortedDisableLines:L,sortedEnableLines:T}}function tt(s,h,m){if(m instanceof Map){let L=m.get(h);if(!L||L.size===0)return!1;return tn(s,L)}if(m.fileLevel.size>0){if(tn(s,m.fileLevel))return!0}let g=m.nextLine.get(h);if(g&&tn(s,g))return!0;let R=!1,I=0,S=0;while(!0){let L=I<m.sortedDisableLines.length?m.sortedDisableLines[I]:Number.POSITIVE_INFINITY,T=S<m.sortedEnableLines.length?m.sortedEnableLines[S]:Number.POSITIVE_INFINITY,A=Math.min(L,T);if(A>=h)break;if(L===A){let _=m.rangeDisable.get(L);if(tn(s,_))R=!0;I++;continue}let O=m.rangeEnable.get(T);if(O.has("*")||tn(s,O))R=!1;S++}return R}function tn(s,h){if(h.size===0)return!1;if(h.has("*"))return!0;if(h.has(s))return!0;let m=mg(s);if(h.has(m)||h.has(hg(s)))return!0;for(let g of h)if(!g.includes("/")){if(s.endsWith(`/${g}`))return!0}return!1}function vr(s){return s!=="spaced-comment"&&!s.endsWith("/spaced-comment")}function dg(s,h){if(s.help)return s;let m=h.includes("/")?h.split("/")[1]:h,g;if(m.startsWith("no-"))g=`Remove or refactor this ${m.replace("no-","").replace(/-/g," ")}. Check the rule documentation for more details or disable with: // eslint-disable-next-line ${h}`;else if(m.startsWith("prefer-"))g=`Consider using ${m.replace("prefer-","").replace(/-/g," ")} instead. This is a best practice recommendation. Disable with: // eslint-disable-next-line ${h} if needed`;else if(m.includes("sort")||m.includes("order"))g=`Reorder these items according to the rule requirements, or use --fix to auto-sort. Disable with: // eslint-disable-next-line ${h}`;else if(m.includes("indent")||m.includes("spacing")||m.includes("newline"))g=`Fix the formatting issue. Run with --fix to automatically format. Disable with: // eslint-disable-next-line ${h}`;else g=`Fix this issue or disable the rule with: // eslint-disable-next-line ${h}. Check the rule documentation for more details`;return{...s,help:g}}async function nn(s,h,m){let g,R=new Promise((I,S)=>{g=setTimeout(()=>S(Error(`Timeout after ${h}ms at ${m}`)),h)});try{let I=await Promise.race([s,R]);return clearTimeout(g),I}catch(I){throw $e().error(`[pickier:error] ${m} failed:`,I?.message||I),Ke("withTimeout error:",m,I),I}}async function um(s,h,m){let g=Array(s.length);if(s.length===0)return g;let R=0,I=Math.max(1,Math.min(Math.max(1,h),s.length));async function S(){while(R<s.length){let L=R++;g[L]=await m(s[L],L)}}return await Promise.all(Array.from({length:I},S)),g}var tm=new WeakMap;function pg(s){let h=Rr();if(s.plugins&&s.plugins.length>0){let m=new Set(["pickier","style","regexp","ts"]),g=s.plugins.filter((I)=>typeof I!=="string");h=g.some((I)=>m.has(I.name))?h:[];for(let I of g)h.push(I)}return h}function gg(s,h){let m={...s.pluginRules||{},...s.rules||{}};if(s.rules?.noUnusedCapturingGroup)m["regexp/no-unused-capturing-group"]=s.rules.noUnusedCapturingGroup;let g={"antfu/curly":"style/curly","antfu/if-newline":"style/if-newline","antfu/no-top-level-await":"ts/no-top-level-await"};for(let[R,I]of Object.entries(g))if(m[R])m[I]=m[R];for(let R of[s.pluginRules,s.rules])for(let I of Object.keys(R||{})){if(I.includes("/"))continue;for(let S of h)if(S.rules&&Object.prototype.hasOwnProperty.call(S.rules,I))m[`${S.name}/${I}`]=R[I]}return m}function Ir(s){let h=tm.get(s);if(h)return h;let m=pg(s),g=gg(s,m),R=[],I=[],S=new Set(["no-debugger"]),L=new Set(["no-debugger"]),T=new Set;for(let O of m)for(let _ in O.rules){let D=`${O.name}/${_}`,F=v(g,D);if(!F.enabled)continue;if(T.has(_))continue;T.add(_);let N=O.rules[_],W={pluginName:O.name,ruleName:_,fullRuleId:D,rule:N,severity:F.severity,options:F.options};if(typeof N?.check==="function")R.push(W);else if(F.severity==="error")R.push(W);if(typeof N?.fix==="function")I.push(W),S.add(D),L.add(_)}let A={checkRules:R,fixRules:I,fixableRuleIds:S,fixableBareRuleNames:L};return tm.set(s,A),A}function yg(s,h){return/\.(?:sh|bash|zsh|ksh|dash)$/.test(s)||/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/.test(h)}function bg(s){return/(?:^|[/\\])(?:bun\.lock|bun\.lockb|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|npm-shrinkwrap\.json)$/.test(s)}function fm(s,h,m){switch(s.pluginName){case"markdown":return h.endsWith(".md");case"shell":return yg(h,m);case"publint":return/(?:^|[/\\])package\.json$/.test(h);case"lockfile":return bg(h);case"node":case"ts":case"general":case"quality":case"eslint":case"regexp":case"unused-imports":case"perfectionist":return/\.(?:ts|js|tsx|jsx|mts|mjs|cts|cjs)$/.test(h);default:return!0}}async function Mr(s,h,m){let g=[],R=Ir(m),I={filePath:s,config:m};for(let S of R.checkRules){if(!fm(S,s,h))continue;let{fullRuleId:L,rule:T,severity:A}=S;if(!T||typeof T.check!=="function"){if(A==="error")g.push({filePath:s,line:1,column:1,ruleId:`${L}-internal`,message:"Rule missing implementation (check function is undefined)",severity:"error"});continue}try{Ke("rule:start",L);let O=n.RULE_TIMEOUT_MS,_={...I,options:S.options},D=performance.now(),F=await nn(Promise.resolve().then(()=>T.check(h,_)),O,`rule:${L}`),N=performance.now()-D;if(N>O)g.push({filePath:s,line:1,column:1,ruleId:`${L}-internal`,message:`Rule exceeded timeout budget: ${Math.round(N)}ms > ${O}ms`,severity:"error"});Ke("rule:end",L,Array.isArray(F)?F.length:0);for(let W of F){let B=dg(W,L);if(A)g.push({...B,severity:A});else g.push(B)}}catch(O){g.push({filePath:s,line:1,column:1,ruleId:`${L}-internal`,message:`Rule threw: ${O?.message||O}`,severity:"error"})}}return g}var xg=/\.(?:[cm]?[jt]sx?|vue|svelte|stx)$/i;function wg(s,h,m){if(!xg.test(m)||!s.includes("`"))return h;let g=s.split(/\r?\n/),R=h.split(/\r?\n/);if(g.length!==R.length)return h;let I=yt(s),S=0;for(let L=0;L<R.length;L++)if(I[L]&&R[L]!==g[L])R[L]=g[L],S++;return S>0?R.join(`
|
|
217
|
-
`):h}function
|
|
218
|
-
`):h}function
|
|
219
|
-
`):s}function
|
|
220
|
-
`){if(g==="line-comment")g="code";R++,S=T+1,I="";continue}if(L()&&g==="code")h.add(R);switch(g){case"single":case"double":if(A==="\\")T++;else if(g==="single"&&A==="'"||g==="double"&&A==='"')g="code";continue;case"line-comment":continue;case"block-comment":if(A==="*"&&O==="/")T++,g="code";continue;case"regex":if(A==="\\")T++;else if(A==="[")g="regex-class";else if(A==="/")g="code";continue;case"regex-class":if(A==="\\")T++;else if(A==="]")g="regex";continue}if(L()){if(A==="\\"){T++;continue}if(A==="`"){m.pop();continue}if(A==="$"&&O==="{"){m.push("interpolation"),T++;continue}continue}if(A==="`"){m.push("template"),h.add(R);continue}if(A==="'"){g="single";continue}if(A==='"'){g="double";continue}if(A==="/"&&O==="/"){g="line-comment",T++;continue}if(A==="/"&&O==="*"){g="block-comment",T++;continue}if(A==="/"&&
|
|
217
|
+
`}}return m}async function M(s,h){jt("runFormat:start",{globs:s,options:h});let m=await u(h.config),g=s.length?s:["."],R=d(g);jt("patterns",R);let I=new Set((h.ext||m.format.extensions.join(",")).split(",").map((B)=>{let j=B.trim();return j.startsWith(".")?j:`.${j}`})),S=n.TIMEOUT_MS,T=R.some((B)=>{let j=B.replace(/\/?\*\*(?:\/\*+)?$/,"");return!(gg(j)?j:yg(process.cwd(),j)).startsWith(process.cwd())})?l(o):l(m.ignores),A=c(T),O=[];if(R.length===1&&/\*\*\/\*$/.test(R[0])){let B=R[0].replace(/\/?\*\*\/\*$/,"");try{let{readdirSync:j,statSync:z}=await import("fs"),{join:K}=await import("path"),V=[B];while(V.length){let G=V.pop(),J=j(G);for(let Y of J){let se=K(G,Y),Z=z(se);if(A(se))continue;if(Z.isDirectory())V.push(se);else O.push(se)}}}catch{O=await sm(i(R,{dot:!1,ignore:T,onlyFiles:!0,absolute:!0}),S,"glob")}}else O=await sm(i(R,{dot:!1,ignore:T,onlyFiles:!0,absolute:!0}),S,"glob");jt("globbed entries",O.length);let D=O.filter((B)=>{if(A(B))return!1;let j=B.lastIndexOf(".");if(j<0)return!0;let z=B.slice(j);return I.has(z)});jt("filtered files",D.length);let F=0,N=[];for(let B of D){jt("format start",nm(process.cwd(),B));let j=im(B,"utf8"),z=f(j,m,B),K=z!==j;if(h.write){if(K)pg(B,z,"utf8")}if(K)N.push(nm(process.cwd(),B));F++}let W=N.length;if(W>0){for(let B of N)console.log(e.gray(` ${B}`));console.log(h.write?e.gray(`Formatted ${W} of ${F} file(s).`):e.yellow(`${W} of ${F} file(s) need formatting. Run with --write to fix.`))}else if(h.verbose!==void 0?h.verbose:m.verbose)console.log(e.gray(`Checked ${F} files, all formatted.`));return h.check&&W>0?1:0}var Cr=null;function ke(){if(!Cr)Cr=new wt("pickier:lint",{showTags:!1});return Cr}function Ke(...s){if(n.TRACE)ke().error("[pickier:trace]",s)}async function C(s,h,m="untitled",g){if(g?.aborted)throw Error("AbortError");let R=$t(s),I=Pt(s),S=on(m,s,h,R,I);if(g?.aborted)throw Error("AbortError");try{let L=await Tr(m,s,h);for(let T of L){if(g?.aborted)throw Error("AbortError");if(tt(T.ruleId,T.line,R))continue;if(I.has(T.line)&&Er(T.ruleId))continue;S.push({filePath:T.filePath,line:T.line,column:T.column,ruleId:T.ruleId,message:T.message,severity:T.severity,...T.help&&{help:T.help}})}}catch{}return S}function x(s,h,m="untitled"){let g=wm(m,s,h,$t(s),Pt(s));if(g=xm(m,g,h),Rm(m,g,h))g=Mg(g,h,$t(g),Pt(g));return g}async function E(s,h,m){Ke("runLintProgrammatic:start",{globs:s,options:h});let g=await u(h.config);if(m?.aborted)throw Error("AbortError");let R=s.length?s:["."],I=d(R),S=h.ext||g.lint.extensions.join(","),L=new Set(S.split(",").map((ee)=>{let oe=ee.trim();return oe.startsWith(".")?oe:`.${oe}`})),T=n.TIMEOUT_MS,O=I.some((ee)=>{let oe=ee.replace(/\/?\*\*\/*\*\*$/,""),X=Ut(oe)?oe:zt(process.cwd(),oe),te=process.cwd();return X!==te&&!X.startsWith(te+gm)})?l(o):l(g.ignores),_=c(O),D=[];if(I.length===1&&!/[*?[\]{}()!]/.test(I[0]))try{if(li(I[0]).isFile())D=[Ut(I[0])?I[0]:zt(process.cwd(),I[0])]}catch{}let N=I.length===1&&/\*\*\/*\*$/.test(I[0]);if(!D.length&&N){let ee=I[0].replace(/\/?\*\*\/*\*\*$/,""),oe=Ut(ee)?ee:zt(process.cwd(),ee);try{let X=[oe];while(X.length){if(m?.aborted)throw Error("AbortError");let te=X.pop(),le=hm(te);for(let ne of le){let q=pm(te,ne),Q=li(q);if(_(q))continue;if(Q.isDirectory())X.push(q);else D.push(q)}}}catch{D=await rn(i(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob")}}else if(!D.length)D=await rn(i(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob");if(m?.aborted)throw Error("AbortError");let W=0,B=0,j=0,z=0,K=0,V=[];for(let ee of D){if(W++,ee.replace(/\\/g,"/").includes("/node_modules/")){j++;continue}if(_(ee)){z++;continue}if(!w(ee,L)){K++;continue}V.push(ee),B++}Ke("filter:programmatic",{total:W,included:B,node_modules:j,ignored:z,wrongExt:K});let G=n.CONCURRENCY,se=(await ym(V,G,async(ee)=>{if(m?.aborted)throw Error("AbortError");let oe=dm(ee,"utf8"),X=$t(oe),te=Pt(oe),le=on(ee,oe,g,X,te);try{let ne=await Tr(ee,oe,g);for(let q of ne){if(m?.aborted)throw Error("AbortError");if(tt(q.ruleId,q.line,X))continue;if(te.has(q.line)&&Er(q.ruleId))continue;le.push({filePath:q.filePath,line:q.line,column:q.column,ruleId:q.ruleId,message:q.message,severity:q.severity,...q.help&&{help:q.help}})}}catch{}{let ne=new Set;le=le.filter((q)=>{let Q=`${q.line}:${q.column}:${q.ruleId}`;if(ne.has(Q))return!1;return ne.add(Q),!0})}if(h.fix){let ne=wm(ee,oe,g,X,te);if(ne=xm(ee,ne,g),ne!==oe){let q=$t(ne),Q=Pt(ne);if(le=on(ee,ne,g,q,Q),!h.dryRun)Sr(ee,ne,"utf8")}}return le})).flat(),Z=se.filter((ee)=>ee.severity==="error").length,re=se.filter((ee)=>ee.severity==="warning").length;return{errors:Z,warnings:re,issues:se}}function bg(s){return s.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function xg(s){return s.replace(/-([a-z])/g,(h,m)=>m.toUpperCase())}function $t(s){let h=new Map,m=new Set,g=new Map,R=new Map,I=s.split(/\r?\n/),S=new Set;for(let A=0;A<I.length;A++){let O=I[A].trim(),_=A+1,D=O.match(/^\/\/\s*(?:eslint|pickier)-disable-next-line(?:\s+(\S.*))?$/);if(D){let j=D[1]?.replace(/\s+--\s.*$/,""),z=j?j.split(",").map((K)=>K.trim()).filter(Boolean):["*"];if(z.length>0){let K=_+1,V=h.get(K)||new Set;for(let G of z)V.add(G);h.set(K,V)}continue}let F=O.match(/^\/\*\s*(?:eslint|pickier)-disable(?:\s+([^*]+))?\s*\*\//);if(F){let j=F[1]?.trim().replace(/\s+--\s.*$/,"");if(!j||j==="")g.set(_,new Set(["*"])),S.add("*");else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=g.get(_)||new Set;for(let V of z)K.add(V),S.add(V);g.set(_,K)}if(A===0)if(!j||j==="")m.add("*");else{let z=j.split(",").map((K)=>K.trim()).filter(Boolean);for(let K of z)m.add(K)}continue}let N=O.match(/^\/\*\s*(?:eslint|pickier)-enable(?:\s+([^*]+))?\s*\*\//);if(N){let j=N[1]?.trim();if(!j||j==="")R.set(_,new Set(["*"])),S.clear();else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=R.get(_)||new Set;for(let V of z)K.add(V),S.delete(V);R.set(_,K)}continue}let W=O.match(/^\/\/\s*(?:eslint|pickier)-disable(?:\s+(\S.*))?$/);if(W){let j=W[1]?.trim().replace(/\s+--\s.*$/,"");if(!j||j==="")g.set(_,new Set(["*"])),S.add("*");else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=g.get(_)||new Set;for(let V of z)K.add(V),S.add(V);g.set(_,K)}continue}let B=O.match(/^\/\/\s*(?:eslint|pickier)-enable(?:\s+(\S.*))?$/);if(B){let j=B[1]?.trim();if(!j||j==="")R.set(_,new Set(["*"])),S.clear();else{let z=j.split(",").map((V)=>V.trim()).filter(Boolean),K=R.get(_)||new Set;for(let V of z)K.add(V),S.delete(V);R.set(_,K)}}}let L=Array.from(g.keys()).sort((A,O)=>A-O),T=Array.from(R.keys()).sort((A,O)=>A-O);return{nextLine:h,fileLevel:m,rangeDisable:g,rangeEnable:R,sortedDisableLines:L,sortedEnableLines:T}}function tt(s,h,m){if(m instanceof Map){let L=m.get(h);if(!L||L.size===0)return!1;return sn(s,L)}if(m.fileLevel.size>0){if(sn(s,m.fileLevel))return!0}let g=m.nextLine.get(h);if(g&&sn(s,g))return!0;let R=!1,I=0,S=0;while(!0){let L=I<m.sortedDisableLines.length?m.sortedDisableLines[I]:Number.POSITIVE_INFINITY,T=S<m.sortedEnableLines.length?m.sortedEnableLines[S]:Number.POSITIVE_INFINITY,A=Math.min(L,T);if(A>=h)break;if(L===A){let _=m.rangeDisable.get(L);if(sn(s,_))R=!0;I++;continue}let O=m.rangeEnable.get(T);if(O.has("*")||sn(s,O))R=!1;S++}return R}function sn(s,h){if(h.size===0)return!1;if(h.has("*"))return!0;if(h.has(s))return!0;let m=bg(s);if(h.has(m)||h.has(xg(s)))return!0;for(let g of h)if(!g.includes("/")){if(s.endsWith(`/${g}`))return!0}return!1}function Er(s){return s!=="spaced-comment"&&!s.endsWith("/spaced-comment")}function wg(s,h){if(s.help)return s;let m=h.includes("/")?h.split("/")[1]:h,g;if(m.startsWith("no-"))g=`Remove or refactor this ${m.replace("no-","").replace(/-/g," ")}. Check the rule documentation for more details or disable with: // eslint-disable-next-line ${h}`;else if(m.startsWith("prefer-"))g=`Consider using ${m.replace("prefer-","").replace(/-/g," ")} instead. This is a best practice recommendation. Disable with: // eslint-disable-next-line ${h} if needed`;else if(m.includes("sort")||m.includes("order"))g=`Reorder these items according to the rule requirements, or use --fix to auto-sort. Disable with: // eslint-disable-next-line ${h}`;else if(m.includes("indent")||m.includes("spacing")||m.includes("newline"))g=`Fix the formatting issue. Run with --fix to automatically format. Disable with: // eslint-disable-next-line ${h}`;else g=`Fix this issue or disable the rule with: // eslint-disable-next-line ${h}. Check the rule documentation for more details`;return{...s,help:g}}async function rn(s,h,m){let g,R=new Promise((I,S)=>{g=setTimeout(()=>S(Error(`Timeout after ${h}ms at ${m}`)),h)});try{let I=await Promise.race([s,R]);return clearTimeout(g),I}catch(I){throw ke().error(`[pickier:error] ${m} failed:`,I?.message||I),Ke("withTimeout error:",m,I),I}}async function ym(s,h,m){let g=Array(s.length);if(s.length===0)return g;let R=0,I=Math.max(1,Math.min(Math.max(1,h),s.length));async function S(){while(R<s.length){let L=R++;g[L]=await m(s[L],L)}}return await Promise.all(Array.from({length:I},S)),g}var am=new WeakMap;function Rg(s){let h=Ir();if(s.plugins&&s.plugins.length>0){let m=new Set(["pickier","style","regexp","ts"]),g=s.plugins.filter((I)=>typeof I!=="string");h=g.some((I)=>m.has(I.name))?h:[];for(let I of g)h.push(I)}return h}function kg(s,h){let m={...s.pluginRules||{},...s.rules||{}};if(s.rules?.noUnusedCapturingGroup)m["regexp/no-unused-capturing-group"]=s.rules.noUnusedCapturingGroup;let g={"antfu/curly":"style/curly","antfu/if-newline":"style/if-newline","antfu/no-top-level-await":"ts/no-top-level-await"};for(let[R,I]of Object.entries(g))if(m[R])m[I]=m[R];for(let R of[s.pluginRules,s.rules])for(let I of Object.keys(R||{})){if(I.includes("/"))continue;for(let S of h)if(S.rules&&Object.prototype.hasOwnProperty.call(S.rules,I))m[`${S.name}/${I}`]=R[I]}return m}function Lr(s){let h=am.get(s);if(h)return h;let m=Rg(s),g=kg(s,m),R=[],I=[],S=new Set(["no-debugger"]),L=new Set(["no-debugger"]),T=new Set;for(let O of m)for(let _ in O.rules){let D=`${O.name}/${_}`,F=v(g,D);if(!F.enabled)continue;if(T.has(_))continue;T.add(_);let N=O.rules[_],W={pluginName:O.name,ruleName:_,fullRuleId:D,rule:N,severity:F.severity,options:F.options};if(typeof N?.check==="function")R.push(W);else if(F.severity==="error")R.push(W);if(typeof N?.fix==="function")I.push(W),S.add(D),L.add(_)}let A={checkRules:R,fixRules:I,fixableRuleIds:S,fixableBareRuleNames:L};return am.set(s,A),A}function $g(s,h){return/\.(?:sh|bash|zsh|ksh|dash)$/.test(s)||/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/.test(h)}function Pg(s){return/(?:^|[/\\])(?:bun\.lock|bun\.lockb|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|npm-shrinkwrap\.json)$/.test(s)}function bm(s,h,m){switch(s.pluginName){case"markdown":return h.endsWith(".md");case"shell":return $g(h,m);case"publint":return/(?:^|[/\\])package\.json$/.test(h);case"lockfile":return Pg(h);case"node":case"ts":case"general":case"quality":case"eslint":case"regexp":case"unused-imports":case"perfectionist":return/\.(?:ts|js|tsx|jsx|mts|mjs|cts|cjs)$/.test(h);default:return!0}}async function Tr(s,h,m){let g=[],R=Lr(m),I={filePath:s,config:m};for(let S of R.checkRules){if(!bm(S,s,h))continue;let{fullRuleId:L,rule:T,severity:A}=S;if(!T||typeof T.check!=="function"){if(A==="error")g.push({filePath:s,line:1,column:1,ruleId:`${L}-internal`,message:"Rule missing implementation (check function is undefined)",severity:"error"});continue}try{Ke("rule:start",L);let O=n.RULE_TIMEOUT_MS,_={...I,options:S.options},D=performance.now(),F=await rn(Promise.resolve().then(()=>T.check(h,_)),O,`rule:${L}`),N=performance.now()-D;if(N>O)g.push({filePath:s,line:1,column:1,ruleId:`${L}-internal`,message:`Rule exceeded timeout budget: ${Math.round(N)}ms > ${O}ms`,severity:"error"});Ke("rule:end",L,Array.isArray(F)?F.length:0);for(let W of F){let B=wg(W,L);if(A)g.push({...B,severity:A});else g.push(B)}}catch(O){g.push({filePath:s,line:1,column:1,ruleId:`${L}-internal`,message:`Rule threw: ${O?.message||O}`,severity:"error"})}}return g}var vg=/\.(?:[cm]?[jt]sx?|vue|svelte|stx)$/i;function Ig(s,h,m){if(!vg.test(m)||!s.includes("`"))return h;let g=s.split(/\r?\n/),R=h.split(/\r?\n/);if(g.length!==R.length)return h;let I=yt(s),S=0;for(let L=0;L<R.length;L++)if(I[L]&&R[L]!==g[L])R[L]=g[L],S++;return S>0?R.join(`
|
|
218
|
+
`):h}function xm(s,h,m){let g=Lr(m),R={filePath:s,config:m},I=h,S=!0,L=0;while(S&&L++<b){S=!1;for(let T of g.fixRules){if(!bm(T,s,I))continue;let A={...R,options:T.options},O=T.rule.fix(I,A),_=T.rule.meta?.editsStringContent?O:Ig(I,O,s);if(_!==I)I=_,S=!0}}return I}function wm(s,h,m,g,R){if(!a(m,"no-debugger",["noDebugger"])||!h.includes("debugger"))return h;let S=s.split(".").pop()?.toLowerCase()??"",L=S==="sh"||S==="bash"||S==="zsh"||S==="ksh"||S==="dash"||/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/.test(h);if(S==="md"||S==="yaml"||S==="yml"||S==="json"||S==="jsonc"||L)return h;let T=/^\s*debugger\b/,A=Ar(h),O=h.split(/\r?\n/),_=[],D=!1;for(let F=0;F<O.length;F++){let N=O[F],W=F+1;if(T.test(N)&&!R.has(W)&&!A.has(W)&&!tt("no-debugger",W,g)){D=!0;continue}_.push(N)}return D?_.join(`
|
|
219
|
+
`):h}function Rm(s,h,m){let g=a(m,"indent",["style/indent"],"warn");if(!g)return;let R=s.split(".").pop()?.toLowerCase()??"";if(R==="md")return;if(R==="stx"||R==="html"||R==="htm"||R==="vue")return;if(R==="yaml"||R==="yml")return;if(R==="sh"||R==="bash"||R==="zsh"||R==="ksh"||R==="dash"||/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/.test(h))return;return g}function Mg(s,h,m,g){let R=h.format.indent,I=h.format.indentStyle,S=Ar(s),L=s.split(/\r?\n/),T=!1;for(let A=0;A<L.length;A++){let O=L[A],_=A+1;if(g.has(_)||S.has(_)||tt("indent",_,m))continue;let D=0;while(D<O.length&&(O.charCodeAt(D)===32||O.charCodeAt(D)===9))D++;if(D===0)continue;let F=O.slice(0,D);if(!y(F,R,I,O))continue;let N;if(I==="tabs"){let W=0,B=0;for(let z=0;z<F.length;z++)if(F.charCodeAt(z)===9)B++;else W++;let j=Math.floor(W/R);N="\t".repeat(B+j)}else{let W=0;for(let j=0;j<F.length;j++)if(F.charCodeAt(j)===9)W+=R;else W++;let B=Math.floor(W/R)*R;N=" ".repeat(B)}if(N!==F)L[A]=N+O.slice(D),T=!0}return T?L.join(`
|
|
220
|
+
`):s}function Ar(s){let h=new Set;if(!s.includes("`"))return h;let m=[],g="code",R=1,I="",S=0,L=()=>m[m.length-1]==="template";for(let T=0;T<s.length;T++){let A=s[T],O=s[T+1];if(A===`
|
|
221
|
+
`){if(g==="line-comment")g="code";R++,S=T+1,I="";continue}if(L()&&g==="code")h.add(R);switch(g){case"single":case"double":if(A==="\\")T++;else if(g==="single"&&A==="'"||g==="double"&&A==='"')g="code";continue;case"line-comment":continue;case"block-comment":if(A==="*"&&O==="/")T++,g="code";continue;case"regex":if(A==="\\")T++;else if(A==="[")g="regex-class";else if(A==="/")g="code";continue;case"regex-class":if(A==="\\")T++;else if(A==="]")g="regex";continue}if(L()){if(A==="\\"){T++;continue}if(A==="`"){m.pop();continue}if(A==="$"&&O==="{"){m.push("interpolation"),T++;continue}continue}if(A==="`"){m.push("template"),h.add(R);continue}if(A==="'"){g="single";continue}if(A==='"'){g="double";continue}if(A==="/"&&O==="/"){g="line-comment",T++;continue}if(A==="/"&&O==="*"){g="block-comment",T++;continue}if(A==="/"&&Or(I,s.slice(S,T+1),T-S)){g="regex";continue}if(A==="}"&&m[m.length-1]==="interpolation"){m.pop();continue}if(!/\s/.test(A))I=A}return h}function cm(s,h){let m=s.match(h);if(!m||m.index===void 0)return null;let g=m.index+m[0].length-1,R=0;for(let I=g;I<s.length;I++)if(s[I]==="(")R++;else if(s[I]===")"){if(R--,R===0)return s.slice(g+1,I)}return null}function um(s){let h="",m=0;for(let g of s){if(g==="("){m++;continue}if(g===")"){m=Math.max(0,m-1);continue}if(m===0)h+=g}return h}function fm(s){let h="",m=0;while(m<s.length){if(s[m]==="/"){if(s[m+1]==="/"||s[m+1]==="*")return h+s.slice(m);let g=s.slice(0,m).trimEnd();if(Or(g[g.length-1]??"",s,m)){m++;let R=!1;while(m<s.length){if(s[m]==="\\"){m+=2;continue}if(s[m]==="[")R=!0;else if(s[m]==="]")R=!1;else if(s[m]==="/"&&!R){m++;while(m<s.length&&/[gimsuvy]/.test(s[m]))m++;break}m++}continue}}h+=s[m],m++}return h}function Or(s,h,m){if(s==="")return!0;if("([{,:;!?&|=<>~^+*%-".includes(s))return!0;if(/[A-Za-z_$]/.test(s)){let R=h.slice(0,m).trimEnd();if(/(?:^|[^A-Za-z0-9_$])(?:return|typeof|instanceof|new|delete|void|in|of|yield|await|throw|case)$/.test(R))return!0}return!1}function mm(s){let h="",m=0,g=null,R=!1;while(m<s.length){let I=s[m],S=s[m+1];if(R){h+=I,R=!1,m++;continue}if(I==="\\"&&g){R=!0,h+=I,m++;continue}if(!g){if(I==='"'){g="double",h+=I,m++;continue}if(I==="'"){g="single",h+=I,m++;continue}if(I==="`"){g="template",h+=I,m++;continue}if(I==="/"&&S==="/")break;if(I==="/"&&S==="*"){m+=2;while(m<s.length){if(s[m]==="*"&&s[m+1]==="/"){m+=2;break}m++}h+=" ";continue}h+=I,m++}else{if(g==="double"&&I==='"'||g==="single"&&I==="'"||g==="template"&&I==="`")g=null;h+=I,m++}}return h}function Pt(s){let h=new Set,m="code",g=1,R=!1,I=!1,S=!1,L=[];for(let T=0;T<s.length;T++){let A=s[T],O=s[T+1],_=T>0?s[T-1]:"";if(A===`
|
|
221
222
|
`){if(S&&m==="block-comment")h.add(g);else if(!R&&I&&m!=="block-comment")h.add(g);else if(!R&&m==="block-comment")h.add(g);if(g++,R=!1,I=!1,S=m==="block-comment",m==="line-comment")m="code";continue}switch(m){case"code":if(A==="/"&&O==="/")m="line-comment",I=!0,T++;else if(A==="/"&&O==="*"){let D=!1;if(T>0){let F=T-1;while(F>0&&(s[F]===" "||s[F]==="\t"))F--;let N=s[F];if("=([{,;!&|?:~^%+-".includes(N)&&N!==`
|
|
222
223
|
`)D=!0;else if(/[a-z]/.test(N)){let W=s.slice(Math.max(0,F-6),F+1);if(/\b(?:return|case|typeof|void|in|of|new|throw|delete)$/.test(W))D=!0}}if(D){R=!0,T++;while(T<s.length){if(s[T]==="\\"){T+=2;continue}if(s[T]==="/"){T++;break}if(s[T]===`
|
|
223
224
|
`)break;T++}while(T<s.length&&/[gimsuy]/.test(s[T]))T++;T--}else I=!0,m="block-comment",T++}else if(A==="/"&&O!==void 0){let D=!1;if(T>0){let F=T-1;while(F>0&&(s[F]===" "||s[F]==="\t"))F--;let N=s[F];if("=([{,;!&|?:~^%+-".includes(N)||N===`
|
|
224
225
|
`)D=!0;else if(/[a-z]/.test(N)){let W=s.slice(Math.max(0,F-6),F+1);if(/\b(?:return|case|typeof|void|in|of|new|throw|delete)$/.test(W))D=!0}}if(D){R=!0,T++;while(T<s.length){if(s[T]==="\\"){T+=2;continue}if(s[T]==="/"){T++;break}if(s[T]===`
|
|
225
|
-
`)break;T++}while(T<s.length&&/[gimsuy]/.test(s[T]))T++;T--}else R=!0}else if(A==="'")m="string-single",R=!0;else if(A==='"')m="string-double",R=!0;else if(A==="`")m="string-template",R=!0;else if(A==="{"){if(L.length)L[L.length-1]++;R=!0}else if(A==="}"){if(L.length)if(L[L.length-1]===0)L.pop(),m="string-template";else L[L.length-1]--;R=!0}else if(!/\s/.test(A))R=!0;break;case"string-single":if(A==="\\"){T++;break}if(A==="'")m="code";break;case"string-double":if(A==="\\"){T++;break}if(A==='"')m="code";break;case"string-template":if(A==="\\"){T++;break}if(A==="$"&&O==="{"){L.push(0),m="code",T++;break}if(A==="`")m="code";break;case"line-comment":break;case"block-comment":if(A==="*"&&O==="/")m="code",T++;break}}if(S&&m==="block-comment")h.add(g);else if(!R&&I&&m!=="block-comment")h.add(g);else if(!R&&m==="block-comment")h.add(g);return h}function sn(s,h,m,g,R){let I=[],S=h.split(/\r?\n/),L=m.format.quotes,T=s.split(".").pop()?.toLowerCase()??"",A=T==="md",O=T==="sh"||T==="bash"||T==="zsh"||T==="ksh"||T==="dash"||/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/.test(h),_=a(m,"quotes",["style/quotes"],"warn"),D=!_||T==="json"||T==="jsonc"||T==="lock"||A||T==="yaml"||T==="yml"||T==="stx"||T==="html"||T==="htm"||T==="vue"||O||s.endsWith("bun.lock"),F=A||T==="yaml"||T==="yml"||T==="json"||T==="jsonc"||O,N=dm(s,h,m),W=!1,B=a(m,"no-debugger",["noDebugger"]),j=a(m,"no-console",["noConsole"]),z=a(m,"no-template-curly-in-string",["noTemplateCurlyInString"]),K=a(m,"no-cond-assign",["noCondAssign"]),V=/\bconsole\.log\s*\(/,J=/^\s*debugger\b/,H=new Set;if(T==="md"){let se=!1;for(let G=0;G<S.length;G++){if(/^(?:`{3,}|~{3,})/.test(S[G].trim())){se=!se;continue}if(se)H.add(G+1)}}let Y=Cr(h);for(let se=0;se<S.length;se++){let G=S[se],le=se+1;if(R.has(le))continue;if(!D&&!Y.has(le)){let X=rm(im(G)),ne=k(X,L);if(ne.length>0&&!W){if(!tt("quotes",le,g))I.push({filePath:s,line:le,column:(ne[0]||0)+1,ruleId:"quotes",message:"Inconsistent quote style",severity:_,help:`Use ${L} quotes consistently throughout your code. You can change the preferred quote style in your config with format.quotes: '${L==="single"?"double":"single"}'`});W=!0}}let te=0;while(te<G.length&&(G.charCodeAt(te)===32||G.charCodeAt(te)===9))te++;let ie=te>0?G.slice(0,te):"";if(N&&ie.length>0&&!H.has(le)&&!Y.has(le)&&y(ie,m.format.indent,m.format.indentStyle,G)){if(!tt("indent",le,g))I.push({filePath:s,line:le,column:1,ruleId:"indent",message:"Incorrect indentation detected",severity:N,help:`Use ${m.format.indentStyle==="spaces"?`${m.format.indent} spaces`:"tabs"} for indentation. Configure with format.indent and format.indentStyle in your config`})}if(!F&&B&&!Y.has(le)&&J.test(G)){if(!tt("no-debugger",le,g))I.push({filePath:s,line:le,column:1,ruleId:"no-debugger",message:"Unexpected debugger statement",severity:B,help:"Remove debugger statements before committing code. Use breakpoints in your IDE instead, or run with --fix to auto-remove"})}if(!F&&j&&!Y.has(le)&&V.test(G)){let X=G.indexOf("//"),ne=G.indexOf("console.");if(X!==-1&&ne>X);else{let oe=null;for(let ee=0;ee<G.length;ee++){let q=G[ee];if(!oe){if(q==='"')oe="double";else if(q==="'")oe="single";else if(q==="`")oe="template";else if(G.slice(ee).startsWith("console.")){let Q=ee+1;if(!tt("no-console",le,g))I.push({filePath:s,line:le,column:Q,ruleId:"no-console",message:"Unexpected console call",severity:j,help:"Remove console statements before committing. Use a proper logging library or disable this rule if console output is intentional"});break}}else if(oe==="double"&&q==='"'||oe==="single"&&q==="'"||oe==="template"&&q==="`"){let Q=0;for(let Z=ee-1;Z>=0&&G[Z]==="\\";Z--)Q++;if(Q%2===0)oe=null}}}}if(z&&!Y.has(le)){let X=G,ne=null,oe=!1,ee=!1,q="",Q="";for(let Z=0;Z<X.length;Z++){let re=X[Z];if(oe){if(Q==="\\"){Q=re;continue}if(ee){if(re==="]")ee=!1}else if(re==="[")ee=!0;else if(re==="/"){oe=!1;while(Z+1<X.length&&/[a-z]/i.test(X[Z+1]))Z++;q="/"}Q=re;continue}if(!ne){if(re==='"'){ne="double",Q=re;continue}if(re==="'"){ne="single",Q=re;continue}if(re==="`"){ne="template",Q=re;continue}if(re==="/"&&X[Z+1]!=="/"&&X[Z+1]!=="*"&&Sr(q,X,Z)){oe=!0,ee=!1,Q=re;continue}if(re!==" "&&re!=="\t")q=re}else if(ne==="double"&&re==='"'||ne==="single"&&re==="'"||ne==="template"&&re==="`"){if(Q!=="\\")ne=null}else if(re==="$"&&X[Z+1]==="{"&&Q!=="\\"&&ne!=="template"){if(!tt("no-template-curly-in-string",le,g))I.push({filePath:s,line:le,column:Z+1,ruleId:"no-template-curly-in-string",message:"Unexpected template string expression in normal string",severity:z,help:"Change the string quotes from ' or \" to backticks (`) to use template literal interpolation, or escape the $ if you meant to use it literally"});break}Q=re}}if(!F&&K&&!Y.has(le)){let ne=rm(im(G)).replace(/'[^']*'|"[^"]*"/g,'""'),oe=(Z)=>/[^=!<>]=(?![=>])/.test(Z),ee=(Z)=>{let re=G.match(Z);if(re&&re.index!==void 0)return re.index+re[0].length;return Math.max(1,G.indexOf("(")+1)},q=nm(ne,/\b(?:if|while)\s*\(/);if(q){let Z=sm(q);if(oe(Z)){if(!tt("no-cond-assign",le,g))I.push({filePath:s,line:le,column:ee(/\b(?:if|while)\s*\(/),ruleId:"no-cond-assign",message:"Unexpected assignment within a conditional expression",severity:K,help:"Use === or == for comparison instead of = (assignment). Wrap intentional assignments in extra parentheses."})}}let Q=nm(ne,/\bfor\s*\(/);if(Q){let Z=Q.split(";");if(Z.length>=2){let re=sm(Z[1]);if(oe(re)){if(!tt("no-cond-assign",le,g))I.push({filePath:s,line:le,column:ee(/\bfor\s*\(/),ruleId:"no-cond-assign",message:"Unexpected assignment within a conditional expression",severity:K,help:"Use === or == for comparison instead of = (assignment). Wrap intentional assignments in extra parentheses."})}}}}}return I}async function P(s,h){Ke("runLint:start",{globs:s,options:h});let m=n.DIAGNOSTICS;if(m)$e().info("[pickier:diagnostics] Starting lint process...");try{if(m)$e().info("[pickier:diagnostics] Loading config...");let g=await u(h.config);Ke("config:loaded",{reporter:g.lint.reporter,ext:g.lint.extensions.join(",")});let R=s.length?s:["."],I=d(R);if(Ke("patterns",I),m)$e().info(`[pickier:diagnostics] Patterns to search: ${I.join(", ")}`);let S=h.ext||g.lint.extensions.join(","),L=new Set(S.split(",").map((q)=>{let Q=q.trim();return Q.startsWith(".")?Q:`.${Q}`}));if(m)$e().info(`[pickier:diagnostics] File extensions: ${Array.from(L).join(", ")}`);let T=n.TIMEOUT_MS;if(m)$e().info(`[pickier:diagnostics] Glob timeout: ${T}ms`);let A=I.some((q)=>{let Q=q.replace(/\/?\*\*\/*\*\*$/,""),Z=jt(Q)?Q:Ut(process.cwd(),Q),re=process.cwd();return Z!==re&&!Z.startsWith(re+cm)}),O=A?l(o):l(g.ignores),_=c(O);if(m){if($e().info(`[pickier:diagnostics] Globbing outside project: ${A}, ignore patterns: ${O.length}`),A)$e().info(`[pickier:diagnostics] Using universal ignores: ${o.slice(0,5).join(", ")}... (${o.length} total)`)}let D=[],F=I.length===1&&!/[*?[\]{}()!]/.test(I[0]);if(m)$e().info(`[pickier:diagnostics] Starting file discovery... (nonGlobSingle: ${F})`);if(F)try{if(ni(I[0]).isFile())D=[jt(I[0])?I[0]:Ut(process.cwd(),I[0])]}catch{}let N=I.length===1&&/\*\*\/*\*$/.test(I[0]);if(!D.length&&N){let q=I[0].replace(/\/?\*\*\/*\*\*$/,"");if(m)$e().info(`[pickier:diagnostics] Using fast directory scan for: ${q}`);try{let Z=[jt(q)?q:Ut(process.cwd(),q)],re=0;while(Z.length){let we=Z.pop();if(re++,m&&re%100===0)$e().info(`[pickier:diagnostics] Scanned ${re} directories, ${D.length} files found so far...`);let pe=om(we);for(let ue of pe){let ae=am(we,ue),xe=ni(ae);if(_(ae))continue;if(xe.isDirectory())Z.push(ae);else D.push(ae)}}if(m)$e().info(`[pickier:diagnostics] Fast scan complete: ${re} directories, ${D.length} total files`)}catch(Q){if(m)$e().info(`[pickier:diagnostics] Fast scan failed: ${Q?.message}, falling back to glob`);D=await nn(r(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob")}}else if(!D.length){if(m)$e().info(`[pickier:diagnostics] Using glob with timeout ${T}ms...`);if(D=await nn(r(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob"),m)$e().info(`[pickier:diagnostics] glob found ${D.length} files`)}if(Ke("globbed entries",D.length),m)$e().info(`[pickier:diagnostics] File discovery complete: ${D.length} files found`);if(D.length>1e4){if($e().warn(`[pickier:warn] Found ${D.length} files. This seems unusually high and may cause memory issues.`),$e().warn("[pickier:warn] Consider checking your ignore patterns or being more specific with your glob pattern."),$e().warn("[pickier:warn] Common culprits: node_modules, build directories, cache folders, or vendor dependencies."),D.length>1e5)return $e().error(`[pickier:error] File count exceeds 100,000 (${D.length}). This will likely cause out-of-memory errors.`),$e().error("[pickier:error] Aborting to prevent crash. Please refine your glob pattern or ignore patterns."),1}if(m)$e().info(`[pickier:diagnostics] Filtering ${D.length} files by extension and ignore patterns...`);let W=0,B=0,j=0,z=0,K=0,V=[];for(let q of D){if(W++,m&&W%1000===0)$e().info(`[pickier:diagnostics] Filtering progress: ${W}/${D.length} files checked, ${B} included...`);if(q.replace(/\\/g,"/").includes("/node_modules/")){j++;continue}if(_(q)){z++;continue}if(!w(q,L)){K++;continue}V.push(q),B++}if(Ke("filter:cli",{total:W,included:B,node_modules:j,ignored:z,wrongExt:K}),Ke("filtered files",V.length),m)$e().info("[pickier:diagnostics] Filtering complete:"),$e().info(`[pickier:diagnostics] Total files found: ${W}`),$e().info(`[pickier:diagnostics] Files to lint: ${B}`),$e().info(`[pickier:diagnostics] Excluded (node_modules): ${j}`),$e().info(`[pickier:diagnostics] Excluded (ignored): ${z}`),$e().info(`[pickier:diagnostics] Excluded (wrong extension): ${K}`);if(V.length>5000){if($e().warn(`[pickier:warn] After filtering, ${V.length} files will be linted. This may take a while and use significant memory.`),V.length>50000)return $e().error(`[pickier:error] ${V.length} files to lint exceeds safe limit (50,000). This will likely cause out-of-memory errors.`),$e().error("[pickier:error] Aborting to prevent crash. Please be more specific with your glob pattern."),$e().error("[pickier:error] Example: Instead of '../stx', try '../stx/src' or '../stx/packages/core'"),1}let J=n.CONCURRENCY;if(m)$e().info(`[pickier:diagnostics] Starting to process ${V.length} files with concurrency ${J}...`);let H=0,Y=!!h._formatOnly,le=(await um(V,J,async(q)=>{if(m){if(H++,H===1||H%10===0||H===V.length)$e().info(`[pickier:diagnostics] Processing file ${H}/${V.length}: ${ti(process.cwd(),q)}`)}let Q=lm(q,"utf8");if(Y){let ue=f(Q,g,q);if(ue!==Q)if(!h.dryRun)Pr(q,ue,"utf8");else return[{filePath:q,line:1,column:1,ruleId:"format",message:"File is not formatted",severity:"error",help:"Run pickier format with --write to apply formatting."}];return[]}let Z=$t(Q),we=/\.(?:ts|js|tsx|jsx|mts|mjs|cts|cjs)$/.test(q)?Pt(Q):new Set,pe=sn(q,Q,g,Z,we);try{let ue=await Mr(q,Q,g);for(let ae of ue){if(tt(ae.ruleId,ae.line,Z))continue;if(we.has(ae.line)&&vr(ae.ruleId))continue;pe.push({filePath:ae.filePath,line:ae.line,column:ae.column,ruleId:ae.ruleId,message:ae.message,severity:ae.severity,...ae.help&&{help:ae.help}})}}catch{}{let ue=new Set;pe=pe.filter((ae)=>{let xe=`${ae.line}:${ae.column}:${ae.ruleId}`;if(ue.has(xe))return!1;return ue.add(xe),!0})}if(h.fix){let ue=x(Q,g,q);if(ue!==Q){let ae=$t(ue),xe=Pt(ue);if(pe=sn(q,ue,g,ae,xe),!h.dryRun)Pr(q,ue,"utf8");if(h.dryRun&&(h.verbose!==void 0?h.verbose:g.verbose))$e().debug(e.gray(`dry-run: would apply fixes in ${ti(process.cwd(),q)}`))}}return Ke("scan done",ti(process.cwd(),q),pe.length),pe})).flat();if(m)$e().info(`[pickier:diagnostics] Processing complete! Found ${le.length} issues total`);let te=le.filter((q)=>q.severity==="error").length,ie=le.filter((q)=>q.severity==="warning").length;if(Ke("issues:summary",{errors:te,warnings:ie}),m)$e().info(`[pickier:diagnostics] Errors: ${te}, Warnings: ${ie}`);let X=h.reporter||g.lint.reporter,ne=h.verbose!==void 0?h.verbose:g.verbose;if(X==="json")console.log(JSON.stringify({errors:te,warnings:ie,issues:le},null,2));else if(X==="compact")for(let q of le)console.log(`${ti(process.cwd(),q.filePath)}:${q.line}:${q.column} ${q.severity} ${q.ruleId} ${q.message}`);else if(le.length>0)console.log(ne?Qf(le):em(le));if(le.length>0&&X!=="json"){let q=te+ie,Q=q===1?"problem":"problems",Z=te===1?"error":"errors",re=ie===1?"warning":"warnings",we=Ir(g),pe=0,ue=0;for(let ae of le){let xe=ae.ruleId;if(we.fixableRuleIds.has(xe)||we.fixableBareRuleNames.has(xe)){if(ae.severity==="error")pe++;else if(ae.severity==="warning")ue++}}if(console.log(),console.log(e.red(`\u2716 ${q} ${Q} (${te} ${Z}, ${ie} ${re})`)),pe>0||ue>0){let ae=pe===1?"error":"errors",xe=ue===1?"warning":"warnings";console.log(e.gray(` ${pe} ${ae} and ${ue} ${xe} potentially fixable with the \`--fix\` option.`))}}if(ne&&X!=="json")console.log(e.gray(`Scanned ${V.length} files, found ${te} errors and ${ie} warnings.`));let oe=h.maxWarnings??g.lint.maxWarnings,ee=n.FAIL_ON_WARNINGS;if(te>0)return Ke("runLint:end",1),1;if(ee&&ie>0)return Ke("runLint:end",1),1;if(oe>=0&&ie>oe)return Ke("runLint:end",1),1;return Ke("runLint:end",0),0}catch(g){return $e().error("[pickier:error] runLint failed:",g?.message||g),Ke("runLint:exception",g),1}}
|
|
226
|
+
`)break;T++}while(T<s.length&&/[gimsuy]/.test(s[T]))T++;T--}else R=!0}else if(A==="'")m="string-single",R=!0;else if(A==='"')m="string-double",R=!0;else if(A==="`")m="string-template",R=!0;else if(A==="{"){if(L.length)L[L.length-1]++;R=!0}else if(A==="}"){if(L.length)if(L[L.length-1]===0)L.pop(),m="string-template";else L[L.length-1]--;R=!0}else if(!/\s/.test(A))R=!0;break;case"string-single":if(A==="\\"){T++;break}if(A==="'")m="code";break;case"string-double":if(A==="\\"){T++;break}if(A==='"')m="code";break;case"string-template":if(A==="\\"){T++;break}if(A==="$"&&O==="{"){L.push(0),m="code",T++;break}if(A==="`")m="code";break;case"line-comment":break;case"block-comment":if(A==="*"&&O==="/")m="code",T++;break}}if(S&&m==="block-comment")h.add(g);else if(!R&&I&&m!=="block-comment")h.add(g);else if(!R&&m==="block-comment")h.add(g);return h}function on(s,h,m,g,R){let I=[],S=h.split(/\r?\n/),L=m.format.quotes,T=s.split(".").pop()?.toLowerCase()??"",A=T==="md",O=T==="sh"||T==="bash"||T==="zsh"||T==="ksh"||T==="dash"||/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/.test(h),_=a(m,"quotes",["style/quotes"],"warn"),D=!_||T==="json"||T==="jsonc"||T==="lock"||A||T==="yaml"||T==="yml"||T==="stx"||T==="html"||T==="htm"||T==="vue"||O||s.endsWith("bun.lock"),F=A||T==="yaml"||T==="yml"||T==="json"||T==="jsonc"||O,N=Rm(s,h,m),W=!1,B=a(m,"no-debugger",["noDebugger"]),j=a(m,"no-console",["noConsole"]),z=a(m,"no-template-curly-in-string",["noTemplateCurlyInString"]),K=a(m,"no-cond-assign",["noCondAssign"]),V=/\bconsole\.log\s*\(/,G=/^\s*debugger\b/,J=new Set;if(T==="md"){let se=!1;for(let Z=0;Z<S.length;Z++){if(/^(?:`{3,}|~{3,})/.test(S[Z].trim())){se=!se;continue}if(se)J.add(Z+1)}}let Y=Ar(h);for(let se=0;se<S.length;se++){let Z=S[se],re=se+1;if(R.has(re))continue;if(!D&&!Y.has(re)){let X=mm(fm(Z)),te=k(X,L);if(te.length>0&&!W){if(!tt("quotes",re,g))I.push({filePath:s,line:re,column:(te[0]||0)+1,ruleId:"quotes",message:"Inconsistent quote style",severity:_,help:`Use ${L} quotes consistently throughout your code. You can change the preferred quote style in your config with format.quotes: '${L==="single"?"double":"single"}'`});W=!0}}let ee=0;while(ee<Z.length&&(Z.charCodeAt(ee)===32||Z.charCodeAt(ee)===9))ee++;let oe=ee>0?Z.slice(0,ee):"";if(N&&oe.length>0&&!J.has(re)&&!Y.has(re)&&y(oe,m.format.indent,m.format.indentStyle,Z)){if(!tt("indent",re,g))I.push({filePath:s,line:re,column:1,ruleId:"indent",message:"Incorrect indentation detected",severity:N,help:`Use ${m.format.indentStyle==="spaces"?`${m.format.indent} spaces`:"tabs"} for indentation. Configure with format.indent and format.indentStyle in your config`})}if(!F&&B&&!Y.has(re)&&G.test(Z)){if(!tt("no-debugger",re,g))I.push({filePath:s,line:re,column:1,ruleId:"no-debugger",message:"Unexpected debugger statement",severity:B,help:"Remove debugger statements before committing code. Use breakpoints in your IDE instead, or run with --fix to auto-remove"})}if(!F&&j&&!Y.has(re)&&V.test(Z)){let X=Z.indexOf("//"),te=Z.indexOf("console.");if(X!==-1&&te>X);else{let le=null;for(let ne=0;ne<Z.length;ne++){let q=Z[ne];if(!le){if(q==='"')le="double";else if(q==="'")le="single";else if(q==="`")le="template";else if(Z.slice(ne).startsWith("console.")){let Q=ne+1;if(!tt("no-console",re,g))I.push({filePath:s,line:re,column:Q,ruleId:"no-console",message:"Unexpected console call",severity:j,help:"Remove console statements before committing. Use a proper logging library or disable this rule if console output is intentional"});break}}else if(le==="double"&&q==='"'||le==="single"&&q==="'"||le==="template"&&q==="`"){let Q=0;for(let H=ne-1;H>=0&&Z[H]==="\\";H--)Q++;if(Q%2===0)le=null}}}}if(z&&!Y.has(re)){let X=Z,te=null,le=!1,ne=!1,q="",Q="";for(let H=0;H<X.length;H++){let ie=X[H];if(le){if(Q==="\\"){Q=ie;continue}if(ne){if(ie==="]")ne=!1}else if(ie==="[")ne=!0;else if(ie==="/"){le=!1;while(H+1<X.length&&/[a-z]/i.test(X[H+1]))H++;q="/"}Q=ie;continue}if(!te){if(ie==='"'){te="double",Q=ie;continue}if(ie==="'"){te="single",Q=ie;continue}if(ie==="`"){te="template",Q=ie;continue}if(ie==="/"&&X[H+1]!=="/"&&X[H+1]!=="*"&&Or(q,X,H)){le=!0,ne=!1,Q=ie;continue}if(ie!==" "&&ie!=="\t")q=ie}else if(te==="double"&&ie==='"'||te==="single"&&ie==="'"||te==="template"&&ie==="`"){if(Q!=="\\")te=null}else if(ie==="$"&&X[H+1]==="{"&&Q!=="\\"&&te!=="template"){if(!tt("no-template-curly-in-string",re,g))I.push({filePath:s,line:re,column:H+1,ruleId:"no-template-curly-in-string",message:"Unexpected template string expression in normal string",severity:z,help:"Change the string quotes from ' or \" to backticks (`) to use template literal interpolation, or escape the $ if you meant to use it literally"});break}Q=ie}}if(!F&&K&&!Y.has(re)){let te=mm(fm(Z)).replace(/'[^']*'|"[^"]*"/g,'""'),le=(H)=>/[^=!<>]=(?![=>])/.test(H),ne=(H)=>{let ie=Z.match(H);if(ie&&ie.index!==void 0)return ie.index+ie[0].length;return Math.max(1,Z.indexOf("(")+1)},q=cm(te,/\b(?:if|while)\s*\(/);if(q){let H=um(q);if(le(H)){if(!tt("no-cond-assign",re,g))I.push({filePath:s,line:re,column:ne(/\b(?:if|while)\s*\(/),ruleId:"no-cond-assign",message:"Unexpected assignment within a conditional expression",severity:K,help:"Use === or == for comparison instead of = (assignment). Wrap intentional assignments in extra parentheses."})}}let Q=cm(te,/\bfor\s*\(/);if(Q){let H=Q.split(";");if(H.length>=2){let ie=um(H[1]);if(le(ie)){if(!tt("no-cond-assign",re,g))I.push({filePath:s,line:re,column:ne(/\bfor\s*\(/),ruleId:"no-cond-assign",message:"Unexpected assignment within a conditional expression",severity:K,help:"Use === or == for comparison instead of = (assignment). Wrap intentional assignments in extra parentheses."})}}}}}return I}async function P(s,h){Ke("runLint:start",{globs:s,options:h});let m=n.DIAGNOSTICS;if(m)ke().info("[pickier:diagnostics] Starting lint process...");try{if(m)ke().info("[pickier:diagnostics] Loading config...");let g=await u(h.config);Ke("config:loaded",{reporter:g.lint.reporter,ext:g.lint.extensions.join(",")});let R=s.length?s:["."],I=d(R);if(Ke("patterns",I),m)ke().info(`[pickier:diagnostics] Patterns to search: ${I.join(", ")}`);let S=h.ext||g.lint.extensions.join(","),L=new Set(S.split(",").map((q)=>{let Q=q.trim();return Q.startsWith(".")?Q:`.${Q}`}));if(m)ke().info(`[pickier:diagnostics] File extensions: ${Array.from(L).join(", ")}`);let T=n.TIMEOUT_MS;if(m)ke().info(`[pickier:diagnostics] Glob timeout: ${T}ms`);let A=I.some((q)=>{let Q=q.replace(/\/?\*\*\/*\*\*$/,""),H=Ut(Q)?Q:zt(process.cwd(),Q),ie=process.cwd();return H!==ie&&!H.startsWith(ie+gm)}),O=A?l(o):l(g.ignores),_=c(O);if(m){if(ke().info(`[pickier:diagnostics] Globbing outside project: ${A}, ignore patterns: ${O.length}`),A)ke().info(`[pickier:diagnostics] Using universal ignores: ${o.slice(0,5).join(", ")}... (${o.length} total)`)}let D=[],F=I.length===1&&!/[*?[\]{}()!]/.test(I[0]);if(m)ke().info(`[pickier:diagnostics] Starting file discovery... (nonGlobSingle: ${F})`);if(F)try{if(li(I[0]).isFile())D=[Ut(I[0])?I[0]:zt(process.cwd(),I[0])]}catch{}let N=I.length===1&&/\*\*\/*\*$/.test(I[0]);if(!D.length&&N){let q=I[0].replace(/\/?\*\*\/*\*\*$/,"");if(m)ke().info(`[pickier:diagnostics] Using fast directory scan for: ${q}`);try{let H=[Ut(q)?q:zt(process.cwd(),q)],ie=0;while(H.length){let ve=H.pop();if(ie++,m&&ie%100===0)ke().info(`[pickier:diagnostics] Scanned ${ie} directories, ${D.length} files found so far...`);let ge=hm(ve);for(let ue of ge){let ae=pm(ve,ue),xe=li(ae);if(_(ae))continue;if(xe.isDirectory())H.push(ae);else D.push(ae)}}if(m)ke().info(`[pickier:diagnostics] Fast scan complete: ${ie} directories, ${D.length} total files`)}catch(Q){if(m)ke().info(`[pickier:diagnostics] Fast scan failed: ${Q?.message}, falling back to glob`);D=await rn(i(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob")}}else if(!D.length){if(m)ke().info(`[pickier:diagnostics] Using glob with timeout ${T}ms...`);if(D=await rn(i(I,{dot:!1,ignore:O,onlyFiles:!0,absolute:!0}),T,"glob"),m)ke().info(`[pickier:diagnostics] glob found ${D.length} files`)}if(Ke("globbed entries",D.length),m)ke().info(`[pickier:diagnostics] File discovery complete: ${D.length} files found`);if(D.length>1e4){if(ke().warn(`[pickier:warn] Found ${D.length} files. This seems unusually high and may cause memory issues.`),ke().warn("[pickier:warn] Consider checking your ignore patterns or being more specific with your glob pattern."),ke().warn("[pickier:warn] Common culprits: node_modules, build directories, cache folders, or vendor dependencies."),D.length>1e5)return ke().error(`[pickier:error] File count exceeds 100,000 (${D.length}). This will likely cause out-of-memory errors.`),ke().error("[pickier:error] Aborting to prevent crash. Please refine your glob pattern or ignore patterns."),1}if(m)ke().info(`[pickier:diagnostics] Filtering ${D.length} files by extension and ignore patterns...`);let W=0,B=0,j=0,z=0,K=0,V=[];for(let q of D){if(W++,m&&W%1000===0)ke().info(`[pickier:diagnostics] Filtering progress: ${W}/${D.length} files checked, ${B} included...`);if(q.replace(/\\/g,"/").includes("/node_modules/")){j++;continue}if(_(q)){z++;continue}if(!w(q,L)){K++;continue}V.push(q),B++}if(Ke("filter:cli",{total:W,included:B,node_modules:j,ignored:z,wrongExt:K}),Ke("filtered files",V.length),m)ke().info("[pickier:diagnostics] Filtering complete:"),ke().info(`[pickier:diagnostics] Total files found: ${W}`),ke().info(`[pickier:diagnostics] Files to lint: ${B}`),ke().info(`[pickier:diagnostics] Excluded (node_modules): ${j}`),ke().info(`[pickier:diagnostics] Excluded (ignored): ${z}`),ke().info(`[pickier:diagnostics] Excluded (wrong extension): ${K}`);if(V.length>5000){if(ke().warn(`[pickier:warn] After filtering, ${V.length} files will be linted. This may take a while and use significant memory.`),V.length>50000)return ke().error(`[pickier:error] ${V.length} files to lint exceeds safe limit (50,000). This will likely cause out-of-memory errors.`),ke().error("[pickier:error] Aborting to prevent crash. Please be more specific with your glob pattern."),ke().error("[pickier:error] Example: Instead of '../stx', try '../stx/src' or '../stx/packages/core'"),1}let G=n.CONCURRENCY;if(m)ke().info(`[pickier:diagnostics] Starting to process ${V.length} files with concurrency ${G}...`);let J=0,Y=!!h._formatOnly,re=(await ym(V,G,async(q)=>{if(m){if(J++,J===1||J%10===0||J===V.length)ke().info(`[pickier:diagnostics] Processing file ${J}/${V.length}: ${oi(process.cwd(),q)}`)}let Q=dm(q,"utf8");if(Y){let ue=f(Q,g,q);if(ue!==Q)if(!h.dryRun)Sr(q,ue,"utf8");else return[{filePath:q,line:1,column:1,ruleId:"format",message:"File is not formatted",severity:"error",help:"Run pickier format with --write to apply formatting."}];return[]}let H=$t(Q),ve=/\.(?:ts|js|tsx|jsx|mts|mjs|cts|cjs)$/.test(q)?Pt(Q):new Set,ge=on(q,Q,g,H,ve);try{let ue=await Tr(q,Q,g);for(let ae of ue){if(tt(ae.ruleId,ae.line,H))continue;if(ve.has(ae.line)&&Er(ae.ruleId))continue;ge.push({filePath:ae.filePath,line:ae.line,column:ae.column,ruleId:ae.ruleId,message:ae.message,severity:ae.severity,...ae.help&&{help:ae.help}})}}catch{}{let ue=new Set;ge=ge.filter((ae)=>{let xe=`${ae.line}:${ae.column}:${ae.ruleId}`;if(ue.has(xe))return!1;return ue.add(xe),!0})}if(h.fix){let ue=x(Q,g,q);if(ue!==Q){let ae=$t(ue),xe=Pt(ue);if(ge=on(q,ue,g,ae,xe),!h.dryRun)Sr(q,ue,"utf8");if(h.dryRun&&(h.verbose!==void 0?h.verbose:g.verbose))ke().debug(e.gray(`dry-run: would apply fixes in ${oi(process.cwd(),q)}`))}}return Ke("scan done",oi(process.cwd(),q),ge.length),ge})).flat();if(m)ke().info(`[pickier:diagnostics] Processing complete! Found ${re.length} issues total`);let ee=re.filter((q)=>q.severity==="error").length,oe=re.filter((q)=>q.severity==="warning").length;if(Ke("issues:summary",{errors:ee,warnings:oe}),m)ke().info(`[pickier:diagnostics] Errors: ${ee}, Warnings: ${oe}`);let X=h.reporter||g.lint.reporter,te=h.verbose!==void 0?h.verbose:g.verbose;if(X==="json")console.log(JSON.stringify({errors:ee,warnings:oe,issues:re},null,2));else if(X==="compact")for(let q of re)console.log(`${oi(process.cwd(),q.filePath)}:${q.line}:${q.column} ${q.severity} ${q.ruleId} ${q.message}`);else if(re.length>0)console.log(te?om(re):lm(re));if(re.length>0&&X!=="json"){let q=ee+oe,Q=q===1?"problem":"problems",H=ee===1?"error":"errors",ie=oe===1?"warning":"warnings",ve=Lr(g),ge=0,ue=0;for(let ae of re){let xe=ae.ruleId;if(ve.fixableRuleIds.has(xe)||ve.fixableBareRuleNames.has(xe)){if(ae.severity==="error")ge++;else if(ae.severity==="warning")ue++}}if(console.log(),console.log(e.red(`\u2716 ${q} ${Q} (${ee} ${H}, ${oe} ${ie})`)),ge>0||ue>0){let ae=ge===1?"error":"errors",xe=ue===1?"warning":"warnings";console.log(e.gray(` ${ge} ${ae} and ${ue} ${xe} potentially fixable with the \`--fix\` option.`))}}if(te&&X!=="json")console.log(e.gray(`Scanned ${V.length} files, found ${ee} errors and ${oe} warnings.`));let le=h.maxWarnings??g.lint.maxWarnings,ne=n.FAIL_ON_WARNINGS;if(ee>0)return Ke("runLint:end",1),1;if(ne&&oe>0)return Ke("runLint:end",1),1;if(le>=0&&oe>le)return Ke("runLint:end",1),1;return Ke("runLint:end",0),0}catch(g){return ke().error("[pickier:error] runLint failed:",g?.message||g),Ke("runLint:exception",g),1}}
|
|
226
227
|
export{M,C,x,E,P};
|