@stacksjs/rpx
Version:
A modern and smart reverse proxy.
13 lines • 440 kB
JavaScript
import{Ab as Hl,Bb as I$,Db as Rt,Eb as Y,Fb as G$,Jb as ah,Kb as hl,Mb as Gf,Nb as Jh,Pb as f$,Qb as Fh,zb as L}from"./chunk-35444zrq.js";import D$ from"node:dgram";import*as b$ from"node:fs/promises";import*as P$ from"node:path";import*as Yt from"node:process";import{spawn as H$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as q$}from"node:os";import*as Zi from"node:path";import*as U from"node:process";var S={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as wl}from"node:child_process";import Z from"node:fs/promises";import*as ul from"node:os";import{homedir as Cn}from"node:os";import*as Ih from"node:path";import{join as D}from"node:path";import*as xi from"node:process";import{createRequire as l1}from"node:module";import{Resolver as l0}from"node:dns/promises";import{createHash as w1,sign as u1}from"node:crypto";import{createHash as h1}from"node:crypto";import{sign as $1}from"node:crypto";import{generateKeyPairSync as rw,X509Certificate as U1}from"node:crypto";import y0 from"node:os";import w0 from"node:path";import{existsSync as pl,statSync as iy}from"fs";import{existsSync as N1,mkdirSync as dC,readdirSync as DC,readFileSync as R1,writeFileSync as bC}from"fs";import{homedir as xt}from"os";import{dirname as vC,resolve as Ji}from"path";import Vr from"process";import{existsSync as ty,statSync as ny}from"fs";import{existsSync as _0,mkdirSync as X1,readdirSync as W1,writeFileSync as S1}from"fs";import{homedir as kt}from"os";import{dirname as ry,resolve as Yi}from"path";import _t from"process";import{join as a1,relative as J1,resolve as fy}from"path";import Jr from"process";import{existsSync as fw,mkdirSync as ym,readdirSync as wm,writeFileSync as um}from"fs";import{homedir as u0}from"os";import{dirname as Am,resolve as Ei}from"path";import In from"process";import{join as F1,relative as I1,resolve as cy}from"path";import Fr from"process";import{existsSync as cw,mkdirSync as em,readdirSync as Cm,writeFileSync as mm}from"fs";import{dirname as jm,resolve as Ir}from"path";import z0 from"process";import{Buffer as et}from"buffer";import{createCipheriv as K1,createDecipheriv as _1,randomBytes as h0}from"crypto";import{closeSync as $0,createReadStream as ly,createWriteStream as z1,existsSync as A0,fsyncSync as yy,openSync as wy,writeFileSync as Q1}from"fs";import{access as M1,constants as uy,mkdir as O1,readdir as cr,rename as hy,stat as Vt,unlink as lr,writeFile as T0}from"fs/promises";import{join as dt}from"path";import yi from"process";import{pipeline as G1}from"stream/promises";import{createGzip as $y}from"zlib";import Dt from"process";import tt from"process";import{Buffer as oi}from"buffer";import{createCipheriv as H1,createDecipheriv as q1,randomBytes as E0}from"crypto";import{closeSync as Y0,createReadStream as Ay,createWriteStream as g1,existsSync as yr,fsyncSync as Ty,openSync as Ey,writeFileSync as L1}from"fs";import{access as s1,constants as Yy,mkdir as x1,readdir as wr,rename as By,stat as bt,unlink as ur,writeFile as B0}from"fs/promises";import{isAbsolute as k1,join as Pt,resolve as V1}from"path";import H from"process";import{pipeline as d1}from"stream/promises";import{createGzip as ey}from"zlib";import Zt from"process";import nt from"process";import hr from"process";import{existsSync as $r}from"fs";import{resolve as e0}from"path";import{existsSync as D1}from"fs";import{existsSync as b1,readdirSync as P1}from"fs";import{extname as C0,resolve as Cy}from"path";import Z1 from"process";import{join as v1,relative as o1,resolve as my}from"path";import Kr from"process";import{Buffer as pi}from"buffer";import{createCipheriv as p1,createDecipheriv as iA,randomBytes as m0}from"crypto";import{closeSync as U0,createReadStream as Uy,createWriteStream as tA,existsSync as Ar,fsyncSync as jy,openSync as Ny,writeFileSync as nA}from"fs";import{access as rA,constants as Ry,mkdir as fA,readdir as Tr,rename as Xy,stat as vt,unlink as Er,writeFile as j0}from"fs/promises";import{isAbsolute as cA,join as ot,resolve as lA}from"path";import q from"process";import{pipeline as yA}from"stream/promises";import{createGzip as Wy}from"zlib";import pt from"process";import rt from"process";import Yr from"process";import{existsSync as Br}from"fs";import{resolve as N0}from"path";import{existsSync as wA}from"fs";import{exec as IT}from"node:child_process";import k0 from"node:fs";import KT from"node:os";import Oi from"node:path";import Lw from"node:process";import{promisify as _T}from"node:util";import fn from"node:crypto";import ft from"node:fs";import D0 from"node:path";import tE from"node:crypto";import nE from"node:fs";import rE from"node:tls";import{execSync as lE}from"node:child_process";import xr from"node:os";var y1=l1(import.meta.url),xy=30000;async function mr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function ky(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new l0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new l0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new l0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Fn{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Fn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Fn.PATH_PREFIX.length);return this.get(n)}}var kr=new Fn;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function J0(i){return Buffer.from(i,"base64url")}function Vy(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function dy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return w1("sha256").update(t).digest("base64url")}function Dy(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),c=n===""?"":Ur(JSON.stringify(n)),l=`${f}.${c}`,y=u1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Ur(y)}}var by="https://acme-staging-v02.api.letsencrypt.org/directory",Py="https://acme-v02.api.letsencrypt.org/directory";class Sr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class ar{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=Vy(i.accountPublicKey),this.thumbprint=dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??xy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await mr(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await mr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=Dy({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await mr(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Sr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return h1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Sr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Zy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
`,chainPem:""};let r=`${n.trim()}
`,f=t.slice(1).map((c)=>c.trim()).join(`
`);return{certPem:r,chainPem:f?`${f}
`:""}}function vy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function ol(i){return new Promise((t)=>setTimeout(t,i))}function A1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Ut(i,t){return Buffer.concat([Buffer.from([i]),A1(t.length),t])}function oy(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ut(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return Ut(6,Buffer.from(n))}function ai(...i){return Ut(48,Buffer.concat(i))}function F0(...i){return Ut(49,Buffer.concat(i))}function I0(i){return Ut(3,Buffer.concat([Buffer.from([0]),i]))}function py(i){return Ut(4,i)}function iw(i){return Ut(12,Buffer.from(i,"utf8"))}function K0(i,t,n){let r=128|(n?32:0)|i;return Ut(r,t)}var T1="1.2.840.10045.2.1",E1="1.2.840.10045.3.1.7",Y1="1.2.840.10045.4.3.2",B1="2.5.4.3",e1="1.2.840.113549.1.9.14",C1="2.5.29.17";function m1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=J0(t.x),r=J0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function tw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(F0(ai(Kt(B1),iw(t[0])))),c=ai(ai(Kt(T1),Kt(E1)),I0(m1(n))),l=t.map((E)=>K0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(C1),py(y)),u=ai(w),h=ai(Kt(e1),F0(u)),$=K0(0,h,!0),A=ai(oy(0),f,c,$),T=$1("sha256",A,r),e=ai(Kt(Y1));return ai(A,e,I0(T))}function nw(i){return tw(i).toString("base64url")}function j1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=y1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=rw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function b0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Py:by),f=j1(i.accountKeyPem),c=new ar({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??kr,u=[],h=[];try{for(let F of l.authorizations){let a=await c.getAuthorization(F);if(a.status==="valid")continue;let J=ar.selectChallenge(a,n);if(n==="dns-01"){let v=vy(a.identifier.value),Mi=c.dns01TxtValue(J.token);await i.dnsProvider.setTxt(v,Mi),u.push({name:v,value:Mi}),await ky(v,Mi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(J.token,c.keyAuthorization(J.token)),h.push(J.token);await c.notifyChallengeReady(J.url),await c.pollAuthorization(F,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=rw("ec",{namedCurve:"P-256"}),T=nw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let e=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(e),{certPem:B,chainPem:C}=Zy(E),j=C?`${B}${C}`:B,X=$.export({format:"pem",type:"pkcs8"}).toString(),W=new Date(new U1(B).validTo);return{certPem:B,keyPem:X,chainPem:C,fullChainPem:j,accountKeyPem:f.pem,notAfter:W}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class lw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!pl(i))return!0;return iy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=pl(n)?iy(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,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:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class yw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new lw,P0=new yw,uA=Object.defineProperty,hA=(i)=>i;function $A(i,t){this[i]=hA.bind(null,t)}var AA=(i,t)=>{for(var n in t)uA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:$A.bind(t,n)})},TA=(i,t)=>()=>(i&&(t=i(i=0)),t),ww={};AA(ww,{withErrorRecovery:()=>$w,tryLoadConfig:()=>OA,loadConfigWithResult:()=>QA,loadConfig:()=>Bw,isRetryableError:()=>JA,isConfigNotFoundError:()=>aA,isBunfigError:()=>Aw,globalPerformanceMonitor:()=>Qn,globalCache:()=>nn,getEnvOrDefault:()=>FA,generateConfigTypes:()=>GA,defaultGeneratedDir:()=>Xw,defaultConfigDir:()=>Rw,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>Tw,createLibraryConfig:()=>HA,config:()=>MA,bunfigPlugin:()=>qA,applyEnvVarsToConfig:()=>an,TypeGenerationError:()=>g0,SchemaValidationError:()=>_n,PluginError:()=>s0,PerformanceMonitor:()=>v0,FileSystemError:()=>q0,ErrorFactory:()=>mt,EnvVarError:()=>Hr,EnvProcessor:()=>dr,ConfigValidator:()=>tc,ConfigValidationError:()=>G0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>H0,ConfigLoader:()=>nc,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>Dr,ConfigCache:()=>Z0,CacheUtils:()=>Cw,BunfigError:()=>Ri,BrowserConfigError:()=>L0,ArrayMergeStrategies:()=>jw});class Z0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ty(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ty(n)?ny(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,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:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class v0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function EA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function YA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function BA(i){return i.getStats().size*2}function o0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>zr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=o0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>zr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function zr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function eA(i,t){if(!cw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return o0(t,r)}catch{return null}}catch{return null}}async function CA({name:i="",cwd:t,defaultConfig:n}){let r=t||z0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Ir(r,`${l}${y}`),u=await eA(w,n);if(u!==null)return u}try{let l=Ir(r,"package.json");if(cw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(n,y)}catch{}}}catch{}return n}function mA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=cy(n,"..");let r=cy(n,i||"");if(t?.relative)return I1(Fr.cwd(),r);return r}async function UA(){try{let i=await CA({name:"clarity",defaultConfig:Nr,cwd:Fr.cwd(),endpoint:"",headers:{}});return{...Nr,...i}}catch{return Nr}}function b(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class uw{async format(i){let t=await jA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qr{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(i,t={}){this.name=i,this.config={...M0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rr};return{...Rr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:M0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await M1(this.config.logDirectory,uy.F_OK|uy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await O1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:et.from(i);try{if(!A0(this.currentLogFile))await T0(this.currentLogFile,"",{mode:420});if(r=wy(this.currentLogFile,"a",420),Q1(r,y,{flag:"a"}),yy(r),r!==void 0)$0(r),r=void 0;if((await Vt(this.currentLogFile)).size===0){if(await T0(this.currentLogFile,y,{flag:"w",mode:420}),(await Vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{$0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,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 dt(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 dt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return dt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return h0(16).toString("hex")}generateKey(){return h0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=h0(16),r=K1("aes-256-gcm",t,n),f=et.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:et.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=$y(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(et.from(et.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await Vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Vt(n).catch(()=>null))try{if(await hy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await lr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await T0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Vt(n).catch(()=>null))await hy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await cr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await lr(dt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=ly(i),r=z1(t),f=$y();await G1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),A0(this.currentLogFile))try{let i=wy(this.currentLogFile,"r+");yy(i),$0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await lr(dt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=mw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
`);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:x.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let w=`${c} ${this.environment}.${i.toUpperCase()}: ${l}
`;if(y)w+=`${y}
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!b()){let n=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:x.blue("◐"),tag:n,message:`${x.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
`,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:x.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Qr(t,{...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(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!A0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ly(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=et.isBuffer(i)?i:et.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=_1("aes-256-gcm",n,f);return y.setAuthTag(c),et.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}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(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!b()){let c=i.split(`
`),l=Math.max(...c.map((h)=>h.length))+2,y=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,u=c.map((h)=>{let $=" ".repeat(l-h.length-2);return`│ ${h}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(w),showTimestamp:!1}))}else if(!b())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(b())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();yi.stdin.removeListener("data",n);try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!1)}catch{}yi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!0)}catch{}yi.stdin.resume(),yi.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,c=0;if(n=i.replace(f,(l,y)=>{if(y==="%")return"%";if(c>=t.length)return l;let w=t[c++];switch(y){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),c<t.length)n+=` ${t.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!b()){let f=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",c=x.blue("◐");console.error(`${c} ${f} ${x.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=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 n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,r)),f!==void 0)this.activeProgressBar.message=f;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;yi.stdout.write(`${"\r".padEnd(yi.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=x.green("━".repeat(r)),l=x.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?x.green("✓"):x.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=yi.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,yi.stdout.write(i.lastRenderedLine),t)yi.stdout.write(`
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=dt(this.config.logDirectory,r);if(i.before)try{if((await Vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await lr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let r=[...t];for(let f of i)if(g(f)&&"name"in f){if(!r.find((c)=>g(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(g(f)&&"path"in f){if(!r.find((c)=>g(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!