@stacksjs/rpx 0.11.20 → 0.11.21

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.
@@ -0,0 +1,224 @@
1
+ import{fb as g,ib as Or,jb as a,kb as tw,ob as cy,pb as bc,rb as Nf,sb as $y,ub as Iy,vb as uy}from"./chunk-cqkz06bg.js";import ww from"node:dgram";import*as ew from"node:fs/promises";import*as Aw from"node:path";import*as yt from"node:process";import{spawn as rw}from"node:child_process";import*as Ai from"node:fs/promises";import{homedir as nw}from"node:os";import*as Di from"node:path";import*as Y from"node:process";var j={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 Vc}from"node:child_process";import P from"node:fs/promises";import*as Dc from"node:os";import{homedir as Ar}from"node:os";import*as hy from"node:path";import{join as b}from"node:path";import*as qi from"node:process";import{createRequire as Rw}from"node:module";import{Resolver as xf}from"node:dns/promises";import{createHash as jw,sign as Fw}from"node:crypto";import{createHash as Nw}from"node:crypto";import{sign as Ww}from"node:crypto";import{generateKeyPairSync as M$,X509Certificate as Gw}from"node:crypto";import kf from"node:os";import Vf from"node:path";import{existsSync as K0,statSync as z0}from"fs";import{existsSync as dw,mkdirSync as DE,readdirSync as bE,readFileSync as gw,writeFileSync as oE}from"fs";import{homedir as dt}from"os";import{dirname as vE,resolve as Ni}from"path";import On from"process";import{existsSync as O0,statSync as M0}from"fs";import{existsSync as al,mkdirSync as qw,readdirSync as Lw,writeFileSync as xw}from"fs";import{homedir as gt}from"os";import{dirname as G0,resolve as ai}from"path";import Xt from"process";import{join as kw,relative as Vw,resolve as H0}from"path";import Tn from"process";import{existsSync as G$,mkdirSync as $T,readdirSync as uT,writeFileSync as hT}from"fs";import{homedir as Df}from"os";import{dirname as eT,resolve as si}from"path";import jr from"process";import{join as Dw,relative as bw,resolve as d0}from"path";import Yn from"process";import{existsSync as H$,mkdirSync as ET,readdirSync as TT,writeFileSync as YT}from"fs";import{dirname as CT,resolve as Bn}from"path";import ml from"process";import{Buffer as At}from"buffer";import{createCipheriv as ow,createDecipheriv as Qw,randomBytes as bf}from"crypto";import{closeSync as of,createReadStream as g0,createWriteStream as Pw,existsSync as Qf,fsyncSync as q0,openSync as L0,writeFileSync as vw}from"fs";import{access as Zw,constants as x0,mkdir as pw,readdir as Qr,rename as k0,stat as qt,unlink as Pr,writeFile as Pf}from"fs/promises";import{join as Lt}from"path";import $i from"process";import{pipeline as ie}from"stream/promises";import{createGzip as V0}from"zlib";import xt from"process";import vi from"process";import{Buffer as oi}from"buffer";import{createCipheriv as te,createDecipheriv as re,randomBytes as vf}from"crypto";import{closeSync as Zf,createReadStream as D0,createWriteStream as ne,existsSync as vr,fsyncSync as b0,openSync as o0,writeFileSync as fe}from"fs";import{access as le,constants as Q0,mkdir as ce,readdir as Zr,rename as P0,stat as kt,unlink as pr,writeFile as pf}from"fs/promises";import{isAbsolute as $e,join as Vt,resolve as ue}from"path";import G from"process";import{pipeline as he}from"stream/promises";import{createGzip as v0}from"zlib";import Dt from"process";import Zi from"process";import tn from"process";import{existsSync as rn}from"fs";import{resolve as il}from"path";import{existsSync as ye}from"fs";import{existsSync as we,readdirSync as ee}from"fs";import{extname as tl,resolve as Z0}from"path";import Ae from"process";import{join as se,relative as ae,resolve as p0}from"path";import Cn from"process";import{Buffer as Qi}from"buffer";import{createCipheriv as me,createDecipheriv as Ee,randomBytes as rl}from"crypto";import{closeSync as nl,createReadStream as i$,createWriteStream as Te,existsSync as nn,fsyncSync as t$,openSync as r$,writeFileSync as Ye}from"fs";import{access as Be,constants as n$,mkdir as Ce,readdir as fn,rename as f$,stat as bt,unlink as ln,writeFile as fl}from"fs/promises";import{isAbsolute as Ue,join as ot,resolve as Re}from"path";import H from"process";import{pipeline as Se}from"stream/promises";import{createGzip as l$}from"zlib";import Qt from"process";import pi from"process";import cn from"process";import{existsSync as $n}from"fs";import{resolve as ll}from"path";import{existsSync as je}from"fs";import{exec as b1}from"node:child_process";import Nl from"node:fs";import o1 from"node:os";import zi from"node:path";import Bu from"node:process";import{promisify as Q1}from"node:util";import pt from"node:crypto";import it from"node:fs";import Jl from"node:path";import TA from"node:crypto";import YA from"node:fs";import BA from"node:tls";import{execSync as RA}from"node:child_process";import Kn from"node:os";var Sw=Rw(import.meta.url);async function R$(i,t,r={}){let n=r.timeoutMs??120000,f=r.intervalMs??3000,l=i.split(".").slice(-2).join("."),c;try{let h=new xf,y=await h.resolveNs(l),w=(await Promise.all(y.map((e)=>h.resolve4(e).catch(()=>[])))).flat();if(w.length>0)c=new xf,c.setServers(w)}catch{}let $=Date.now()+n,u=c??new xf;for(;;){try{if((await u.resolveTxt(i)).some((h)=>h.join("")===t))return!0}catch{}if(Date.now()>=$)return!1;await new Promise((h)=>setTimeout(h,f))}}class Sr{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(Sr.PATH_PREFIX);if(t===-1)return;let r=i.slice(t+Sr.PATH_PREFIX.length);return this.get(r)}}var zn=new Sr;function yn(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function wl(i){return Buffer.from(i,"base64url")}function S$(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 j$(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return jw("sha256").update(t).digest("base64url")}function F$(i){let{protectedHeader:t,payload:r,privateKey:n}=i,f=yn(JSON.stringify(t)),l=r===""?"":yn(JSON.stringify(r)),c=`${f}.${l}`,$=Fw("sha256",Buffer.from(c),{key:n,dsaEncoding:"ieee-p1363"});return{protected:f,payload:l,signature:yn($)}}var N$="https://acme-staging-v02.api.letsencrypt.org/directory",W$="https://acme-v02.api.letsencrypt.org/directory";class mn extends Error{problem;httpStatus;constructor(i,t,r){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class En{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=S$(i.accountPublicKey),this.thumbprint=j$(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await fetch(this.directoryUrl);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 fetch(i.newNonce,{method:"HEAD"})).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:r,useJwk:n}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)f.jwk=this.jwk;else f.kid=this.requireKid();let l=F$({protectedHeader:f,payload:r,privateKey:this.accountKey}),c=await fetch(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(l)}),$=c.headers.get("replay-nonce");if($)this.nonce=$;let u=c.headers.get("content-type")??"",h;if(u.includes("application/pem-certificate-chain")||u.startsWith("text/"))h=await c.text();else{let y=await c.text();h=y?JSON.parse(y):{}}if(c.status>=400){let y=h??{};throw new mn(`ACME request to ${t} failed (HTTP ${c.status}): ${y.type??""} ${y.detail??""}`.trim(),y,c.status)}return{status:c.status,headers:c.headers,body:h,location:c.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(),r={termsOfServiceAgreed:!0};if(i.email)r.contact=[`mailto:${i.email}`];let n=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(i){let t=await this.directory(),r={identifiers:i.map((f)=>({type:"dns",value:f}))},n=await this.signedPost({url:t.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return Nw("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let l=await this.getAuthorization(i);if(l.status==="valid")return;if(l.status==="invalid"){let c=l.challenges.find(($)=>$.status==="invalid");throw new mn(`Authorization for ${l.identifier.value} became invalid: ${c?.error?.detail??"unknown reason"}`,c?.error??{},0)}await I0(n),n=Math.min(n*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 r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let l=await this.getOrder(i);if(l.status==="valid"){if(!l.certificate)throw Error("ACME order is valid but has no certificate URL");return l.certificate}if(l.status==="invalid")throw Error(`ACME order ${i} became invalid`);await I0(n),n=Math.min(n*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 r=i.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return r}}function X$(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${i.trim()}
2
+ `,chainPem:""};let n=`${r.trim()}
3
+ `,f=t.slice(1).map((l)=>l.trim()).join(`
4
+ `);return{certPem:n,chainPem:f?`${f}
5
+ `:""}}function J$(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function I0(i){return new Promise((t)=>setTimeout(t,i))}function Xw(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function mt(i,t){return Buffer.concat([Buffer.from([i]),Xw(t.length),t])}function _$(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=[],n=i;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return mt(2,t)}function Wt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let f=t[n],l=[f&127];f=Math.floor(f/128);while(f>0)l.unshift(f&127|128),f=Math.floor(f/128);r.push(...l)}return mt(6,Buffer.from(r))}function Fi(...i){return mt(48,Buffer.concat(i))}function el(...i){return mt(49,Buffer.concat(i))}function Al(i){return mt(3,Buffer.concat([Buffer.from([0]),i]))}function I$(i){return mt(4,i)}function K$(i){return mt(12,Buffer.from(i,"utf8"))}function sl(i,t,r){let n=128|(r?32:0)|i;return mt(n,t)}var Jw="1.2.840.10045.2.1",_w="1.2.840.10045.3.1.7",Iw="1.2.840.10045.4.3.2",Kw="2.5.4.3",zw="1.2.840.113549.1.9.14",Ow="2.5.29.17";function Mw(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=wl(t.x),n=wl(t.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function z$(i){let{domains:t,publicKey:r,privateKey:n}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Fi(el(Fi(Wt(Kw),K$(t[0])))),l=Fi(Fi(Wt(Jw),Wt(_w)),Al(Mw(r))),c=t.map((s)=>sl(2,Buffer.from(s,"ascii"),!1)),$=Fi(...c),u=Fi(Wt(Ow),I$($)),h=Fi(u),y=Fi(Wt(zw),el(h)),w=sl(0,y,!0),e=Fi(_$(0),f,l,w),A=Ww("sha256",e,n),m=Fi(Wt(Iw));return Fi(e,m,Al(A))}function O$(i){return z$(i).toString("base64url")}function Hw(i){if(i){let{createPrivateKey:f,createPublicKey:l}=Sw("node:crypto"),c=f(i),$=l(c);return{privateKey:c,publicKey:$,pem:i}}let{privateKey:t,publicKey:r}=M$("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function _l(i){let{domains:t,method:r}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((w)=>w.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=i.directoryUrl??(i.staging===!1?W$:N$),f=Hw(i.accountKeyPem),l=new En({directoryUrl:n,accountKey:f.privateKey,accountPublicKey:f.publicKey});await l.newAccount({email:i.email});let{order:c,orderUrl:$}=await l.newOrder(t),u=i.http01Store??zn,h=[],y=[];try{for(let R of c.authorizations){let W=await l.getAuthorization(R);if(W.status==="valid")continue;let k=En.selectChallenge(W,r);if(r==="dns-01"){let fi=J$(W.identifier.value),ki=l.dns01TxtValue(k.token);await i.dnsProvider.setTxt(fi,ki),h.push({name:fi,value:ki}),await R$(fi,ki,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else u.add(k.token,l.keyAuthorization(k.token)),y.push(k.token);await l.notifyChallengeReady(k.url),await l.pollAuthorization(R,{timeoutMs:i.timeoutMs})}let{privateKey:w,publicKey:e}=M$("ec",{namedCurve:"P-256"}),A=O$({domains:t,publicKey:e,privateKey:w});await l.finalizeOrder(c.finalize,A);let m=await l.pollOrder($,{timeoutMs:i.timeoutMs}),s=await l.downloadCertificate(m),{certPem:E,chainPem:T}=X$(s),B=T?`${E}${T}`:E,F=w.export({format:"pem",type:"pkcs8"}).toString(),N=new Date(new Gw(E).validTo);return{certPem:E,keyPem:F,chainPem:T,fullChainPem:B,accountKeyPem:f.pem,notAfter:N}}finally{for(let{name:w,value:e}of h)await i.dnsProvider?.removeTxt(w,e).catch(()=>{});for(let w of y)u.remove(w)}}class d${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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!K0(i))return!0;return z0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=K0(r)?z0(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class g${metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}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 r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var Un=new d$,Il=new g$,Fe=Object.defineProperty,Ne=(i)=>i;function We(i,t){this[i]=Ne.bind(null,t)}var Xe=(i,t)=>{for(var r in t)Fe(i,r,{get:t[r],enumerable:!0,configurable:!0,set:We.bind(t,r)})},Je=(i,t)=>()=>(i&&(t=i(i=0)),t),q$={};Xe(q$,{withErrorRecovery:()=>k$,tryLoadConfig:()=>pe,loadConfigWithResult:()=>ve,loadConfig:()=>Q$,isRetryableError:()=>Ve,isConfigNotFoundError:()=>ke,isBunfigError:()=>V$,globalPerformanceMonitor:()=>Xr,globalCache:()=>vt,getEnvOrDefault:()=>De,generateConfigTypes:()=>i1,defaultGeneratedDir:()=>nu,defaultConfigDir:()=>ru,deepMergeWithArrayStrategy:()=>Gl,deepMerge:()=>D$,createLibraryConfig:()=>t1,config:()=>Ze,bunfigPlugin:()=>r1,applyEnvVarsToConfig:()=>Ur,TypeGenerationError:()=>Rl,SchemaValidationError:()=>Nr,PluginError:()=>jl,PerformanceMonitor:()=>zl,FileSystemError:()=>Ul,ErrorFactory:()=>at,EnvVarError:()=>Wn,EnvProcessor:()=>Mn,ConfigValidator:()=>Hl,ConfigValidationError:()=>Bl,ConfigNotFoundError:()=>Nn,ConfigMergeError:()=>Cl,ConfigLoader:()=>dl,ConfigLoadError:()=>Fr,ConfigFileLoader:()=>Gn,ConfigCache:()=>Kl,CacheUtils:()=>v$,BunfigError:()=>Ui,BrowserConfigError:()=>Sl,ArrayMergeStrategies:()=>iu});class Kl{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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!O0(i))return!0;return M0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=O0(r)?M0(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class zl{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}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 r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function _e(i,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${i}:${r}`:i}function Ie(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function Ke(i){return i.getStats().size*2}function Ol(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 n=[...t];for(let f of i)if(V(f)&&"name"in f){if(!n.find((l)=>V(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(V(f)&&"path"in f){if(!n.find((l)=>V(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((l)=>Rn(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!V(t)||!V(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(V(f)&&V(r[n]))r[n]=Ol(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&V(f[0])&&V(r[n][0])){let l=[...f];for(let c of r[n])if(V(c)&&"name"in c){if(!l.find(($)=>V($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(V(c)&&"path"in c){if(!l.find(($)=>V($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some(($)=>Rn($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Rn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Rn(i[r],t[r]))return!1;return!0}if(V(i)&&V(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Rn(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function ze(i,t){if(!H$(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ol(t,n)}catch{return null}}catch{return null}}async function Oe({name:i="",cwd:t,defaultConfig:r}){let n=t||ml.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let $ of f){let u=Bn(n,`${c}${$}`),h=await ze(u,r);if(h!==null)return h}try{let c=Bn(n,"package.json");if(H$(c)){let $=(await import(c))[i];if($&&typeof $==="object"&&!Array.isArray($))try{return Ol(r,$)}catch{}}}catch{}return r}function Me(i,t={}){let r=Yn.cwd();while(r.includes("storage"))r=d0(r,"..");let n=d0(r,i||"");if(t?.relative)return bw(Yn.cwd(),n);return n}async function Ge(){try{let i=await Oe({name:"clarity",defaultConfig:en,cwd:Yn.cwd(),endpoint:"",headers:{}});return{...en,...i}}catch{return en}}function o(){if(vi.env.NODE_ENV==="test"||vi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function He(){if(vi.env.NODE_ENV==="test"||vi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vi<"u"){let i=vi.type;if(i==="renderer"||i==="worker")return!1;return!!(vi.versions&&(vi.versions.node||vi.versions.bun))}return!1}class L${async format(i){let t=await He(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:xt.pid,hostname:t(),environment:xt.env.NODE_ENV||"development",platform:xt.platform,version:xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xt.env.NODE_ENV||xt.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;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={...Tl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new L$,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??$i.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...An,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...An};return{...An,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Tl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await Zw(this.config.logDirectory,x0.F_OK|x0.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await pw(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:At.from(i);try{if(!Qf(this.currentLogFile))await Pf(this.currentLogFile,"",{mode:420});if(n=L0(this.currentLogFile,"a",420),vw(n,$,{flag:"a"}),q0(n),n!==void 0)of(n),n=void 0;if((await qt(this.currentLogFile)).size===0){if(await Pf(this.currentLogFile,$,{flag:"w",mode:420}),(await qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(f<l-1){let y=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,y);let w=c*2**f;await new Promise((e)=>setTimeout(e,w)),f++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{of(n)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch($){if(f===l-1){let h=$,y=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",y),$}f++;let u=c*2**(f-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Lt(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 Lt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Lt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(o())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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return bf(16).toString("hex")}generateKey(){return bf(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(),r=bf(16),n=ow("aes-256-gcm",t,r),f=At.concat([n.update(i,"utf8"),n.final()]),l=n.getAuthTag();return{encrypted:At.concat([r,f,l]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=V0(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(At.from(At.concat(f)))),n.on("error",r),n.write(i),n.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(o())return;let i=await qt(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Qr(this.config.logDirectory),l=f.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,h)=>{let y=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await qt(r).catch(()=>null))try{if(await k0(r,$),t.compress)try{let u=`${$}.gz`;await this.compressLogFile($,u),await Pr($)}catch(u){console.error("Error compressing rotated file:",u)}if(l.length===0&&!f.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await Pf(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await qt(r).catch(()=>null))await k0(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await Qr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await Pr(Lt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=g0(i),n=Pw(t),f=V0();await ie(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}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 r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}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()})),Qf(this.currentLogFile))try{let i=L0(this.currentLogFile,"r+");q0(i),of(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(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Qr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Pr(Lt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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?L.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let u=$i.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${r} ${f}`;else if(l==="info"||l==="success")h=`${r} ${n} ${f}`;else h=`${r} ${n} ${L.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,w=$(t).length,e=Math.max(1,u-2-y-w);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);if(this.fancy&&!o()){let h=Z$[i],y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",w;switch(i){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:L.gray(c),level:i}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:L.green(c),level:i}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(w),$){let e=$.split(`
6
+ `);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:L.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!o()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let u=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
7
+ `;if($)u+=`${$}
8
+ `;u=u.replace(this.ANSI_PATTERN,""),await this.writeToFile(u)}time(i){let t=performance.now();if(this.fancy&&!o()){let r=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:L.blue("◐"),tag:r,message:`${L.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),u=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)u+=` ${JSON.stringify(r)}`;if(u+=`
9
+ `,u=u.replace(this.ANSI_PATTERN,""),this.fancy&&!o()){let h=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:L.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!o())console.error(u.trim());await this.writeToFile(u)}}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}`,r=new Sn(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(r),r}createReadStream(){if(o())throw Error("createReadStream is not supported in browser environments");if(!Qf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return g0(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 r=this.keys.get(this.currentKeyId);try{let n=At.isBuffer(i)?i:At.from(i,"base64"),f=n.slice(0,16),l=n.slice(-16),c=n.slice(16,-16),$=Qw("aes-256-gcm",r,f);return $.setAuthTag(l),At.concat([$.update(c),$.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return o()}isServerMode(){return!o()}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,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!o()){let l=i.split(`
10
+ `),c=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(c)}┐`,u=`└${"─".repeat(c)}┘`,h=l.map((y)=>{let w=" ".repeat(c-y.length-2);return`│ ${y}${w} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:L.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan($)})),h.forEach((y)=>console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(y),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(u),showTimestamp:!1}))}else if(!o())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
11
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(o())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${L.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();$i.stdin.removeListener("data",r);try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!1)}catch{}$i.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!0)}catch{}$i.stdin.resume(),$i.stdin.once("data",r)})}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 r=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,l=0;if(r=i.replace(f,(c,$)=>{if($==="%")return"%";if(l>=t.length)return c;let u=t[l++];switch($){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),l<t.length)r+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!o()){let f=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",l=L.blue("◐");console.error(`${l} ${f} ${L.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
12
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(i,t=""){if(!this.enabled||!this.fancy||o()||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 r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,n)),f!==void 0)this.activeProgressBar.message=f;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;$i.stdout.write(`${"\r".padEnd($i.stdout.columns||80)}\r`),this.log(f,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||o()||!$i.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=L.green("━".repeat(n)),c=L.gray("━".repeat(f)),$=`[${l}${c}]`,u=`${r}%`.padStart(4),h=i.message?` ${i.message}`:"",y=t||r===100?L.green("✓"):L.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",e=`\r${y}${w} ${$} ${u}${h}`,A=$i.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,$i.stdout.write(i.lastRenderedLine),t)$i.stdout.write(`
13
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||o()||!$i.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(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Qr(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Lt(this.config.logDirectory,n);if(i.before)try{if((await qt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Pr(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function wn(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&d(t[0])&&"id"in t[0]&&t[0].id===3&&d(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(d(t)&&d(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(d(i)&&"arr"in i&&Array.isArray(i.arr)&&d(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&d(t[0])&&d(i[0])){let n=[...t];for(let f of i)if(d(f)&&"name"in f){if(!n.find((l)=>d(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(d(f)&&"path"in f){if(!n.find((l)=>d(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((l)=>jn(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!d(t)||!d(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(d(f)&&d(r[n]))r[n]=wn(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&d(f[0])&&d(r[n][0])){let l=[...f];for(let c of r[n])if(d(c)&&"name"in c){if(!l.find(($)=>d($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(d(c)&&"path"in c){if(!l.find(($)=>d($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some(($)=>jn($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Ml(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:wn(i,t);if(Array.isArray(i))return r==="replace"?t:wn(i,t);if(!d(t)||!d(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=n[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(r==="replace")n[f]=l;else n[f]=wn(c,l);else if(d(l)&&d(c))n[f]=Ml(c,l,r);else n[f]=l}return n}function jn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!jn(i[r],t[r]))return!1;return!0}if(d(i)&&d(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!jn(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function un(i,t,r="replace"){if(!G$(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Ml(t,f,r)}catch{return null}}catch{return null}}function de(i,t,r=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,$=[]){let u={...c};for(let[h,y]of Object.entries(c)){let w=[...$,h],e=(s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${n}_${w.map(e).join("_")}`,m=`${n}_${w.map((s)=>s.toUpperCase()).join("_")}`;if(r)hi.info(`Checking environment variable ${A} for config ${i}.${w.join(".")}`);if(typeof y==="object"&&y!==null&&!Array.isArray(y))u[h]=l(y,w);else{let s=jr.env[A]||jr.env[m];if(s!==void 0){if(r)hi.info(`Using environment variable ${s?A:m} for config ${i}.${w.join(".")}`);if(typeof y==="number")u[h]=Number(s);else if(typeof y==="boolean")u[h]=s.toLowerCase()==="true";else if(Array.isArray(y))try{let E=JSON.parse(s);if(Array.isArray(E))u[h]=E;else u[h]=s.split(",").map((T)=>T.trim())}catch{u[h]=s.split(",").map((E)=>E.trim())}else u[h]=s}}}return u}return l(f)}async function ge({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:$="replace"}){let u=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?de(i,f,l):f,h=r||jr.cwd(),y=[".ts",".js",".mjs",".cjs",".json"];if(l)hi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${h}`);let w=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],s=Array.from(new Set([h,si(h,"config"),si(h,".config"),n?si(h,n):void 0].filter(Boolean)));for(let E of s){if(l)hi.info(`Searching for configuration in: ${E}`);let T=[si(h,"config"),si(h,".config")].concat(n?[si(h,n)]:[]).includes(E)?[...w,...e,...A,...m]:[...e,...w,...m,...A];for(let B of T)for(let F of y){let N=si(E,`${B}${F}`),R=await un(N,u,$);if(R!==null){if(l)hi.success(`Configuration loaded from: ${N}`);return R}}}if(i){let E=si(Df(),".config",i),T=["config",`${i}.config`];if(t)T.push(`${t}.config`);if(l)hi.info(`Checking user config directory: ${E}`);for(let B of T)for(let F of y){let N=si(E,`${B}${F}`),R=await un(N,u,$);if(R!==null){if(l)hi.success(`Configuration loaded from user config directory: ${N}`);return R}}}if(i){let E=si(Df(),".config"),T=[`.${i}.config`];if(t)T.push(`.${t}.config`);if(l)hi.info(`Checking user config directory for dotfile configs: ${E}`);for(let B of T)for(let F of y){let N=si(E,`${B}${F}`),R=await un(N,u,$);if(R!==null){if(l)hi.success(`Configuration loaded from user config directory dotfile: ${N}`);return R}}}if(i){let E=Df(),T=[`.${i}.config`,`.${i}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(l)hi.info(`Checking user home directory for dotfile configs: ${E}`);for(let B of T)for(let F of y){let N=si(E,`${B}${F}`),R=await un(N,u,$);if(R!==null){if(l)hi.success(`Configuration loaded from user home directory: ${N}`);return R}}}try{let E=si(h,"package.json");if(G$(E)){let T=await import(E),B=T[i];if(!B&&t){if(B=T[t],B&&l)hi.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(l)hi.success(`Configuration loaded from package.json: ${B===T[i]?i:t}`);return Ml(u,B,$)}catch(F){if(l)hi.warn("Failed to merge package.json config:",F)}}}catch(E){if(l)hi.warn("Failed to load package.json:",E)}if(l)hi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return u}function qe(i,t={}){let r=Tn.cwd();while(r.includes("storage"))r=H0(r,"..");let n=H0(r,i||"");if(t?.relative)return Vw(Tn.cwd(),n);return n}async function Le(){try{let i=await ge({name:"clarity",alias:"logging",defaultConfig:sn,cwd:Tn.cwd()});return{...sn,...i||{}}}catch{return sn}}function Z(){if(Zi.env.NODE_ENV==="test"||Zi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xe(){if(Zi.env.NODE_ENV==="test"||Zi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zi<"u"){let i=Zi.type;if(i==="renderer"||i==="worker")return!1;return!!(Zi.versions&&(Zi.versions.node||Zi.versions.bun))}return!1}class x${async format(i){let t=await xe(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}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 Fn{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(i,t={}){this.name=i,this.config={...Yl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new x$,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??G.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...an,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...an};return{...an,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Yl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Z()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await le(this.config.logDirectory,Q0.F_OK|Q0.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await ce(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:oi.from(i);try{if(!vr(this.currentLogFile))await pf(this.currentLogFile,"",{mode:420});if(n=o0(this.currentLogFile,"a",420),fe(n,$,{flag:"a"}),b0(n),n!==void 0)Zf(n),n=void 0;if((await kt(this.currentLogFile)).size===0){if(await pf(this.currentLogFile,$,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(f<l-1){let y=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,y);let w=c*2**f;await new Promise((e)=>setTimeout(e,w)),f++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Zf(n)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch($){if(f===l-1){let h=$,y=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",y),$}f++;let u=c*2**(f-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Vt(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 Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Z())return;if(!this.shouldWriteToFile())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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return vf(16).toString("hex")}generateKey(){return vf(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(),r=vf(16),n=te("aes-256-gcm",t,r),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,u=n.getAuthTag(),h=oi.allocUnsafe(16+$+16);return r.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),u.copy(h,16+$),{encrypted:h,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=v0(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(oi.from(oi.concat(f)))),n.on("error",r),n.write(i),n.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(Z())return;if(!this.shouldWriteToFile())return;let i=await kt(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Zr(this.config.logDirectory),l=f.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,h)=>{let y=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await kt(r).catch(()=>null))try{if(await P0(r,$),t.compress)try{let u=`${$}.gz`;await this.compressLogFile($,u),await pr($)}catch(u){console.error("Error compressing rotated file:",u)}if(l.length===0&&!f.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await pf(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await kt(r).catch(()=>null))await P0(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await Zr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await pr(Vt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=D0(i),n=ne(t),f=v0();await he(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),vr(this.currentLogFile))try{let i=o0(this.currentLogFile,"r+");b0(i),Zf(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(!Z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await pr(Vt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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.shouldStyleConsole()?K.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z())return!1;let i=typeof G.env.NO_COLOR<"u",t=G.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof G.stderr<"u"&&G.stderr.isTTY||typeof G.stdout<"u"&&G.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let u=G.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${r} ${f}`;else if(l==="info"||l==="success")h=`${r} ${n} ${f}`;else h=`${r} ${n} ${K.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,w=$(t).length,e=Math.max(1,u-2-y-w);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=K.underline(K.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,u="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>K.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>K.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>K.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>K.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>K.strikethrough(n)),t}supportsHyperlinks(){if(Z())return!1;let i=G.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=G.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if($e(t)||t.startsWith("./")||t.startsWith("../"))t=ue(t);else return null;return vr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:u,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":p$[i],e=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:K.gray(u),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:K.green(u),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.error(A),$){let m=$.split(`
14
+ `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!Z()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
15
+ `;if($)y+=`${$}
16
+ `;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let r={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Z()&&G.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!Z()&&G.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!Z()&&G.stdout.isTTY)G.stdout.write(`
17
+ `);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!Z()&&G.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:r,message:`${K.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),u=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)u+=` ${JSON.stringify(r)}`;if(u+=`
18
+ `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":K.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Z())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}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}`,r=new Fn(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(r),r}createReadStream(){if(Z())throw Error("createReadStream is not supported in browser environments");if(!vr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return D0(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 r=this.keys.get(this.currentKeyId);try{let n=oi.isBuffer(i)?i:oi.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=re("aes-256-gcm",r,f);$.setAuthTag(l);let u=$.update(c),h=$.final(),y=u.length+h.length,w=oi.allocUnsafe(y);return u.copy(w,0),h.copy(w,u.length),w.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Z()}isServerMode(){return!Z()}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,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
19
+ `),u=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(u)}┐`,y=`└${"─".repeat(u)}┘`,w=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:K.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(h),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(y),showTimestamp:!1}))}else if(!Z())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(Z())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();G.stdin.removeListener("data",r);try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!1)}catch{}G.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!0)}catch{}G.stdin.resume(),G.stdin.once("data",r)})}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 r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(r=i.replace(c,(u,h)=>{if(h==="%")return"%";if($>=t.length)return u;let y=t[$++];switch(h){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 u}}),$<t.length)r+=` ${t.slice($).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${$}${c} ${K.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
21
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!G.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=K.green("━".repeat(n)),c=K.gray("━".repeat(f)),$=`[${l}${c}]`,u=`${r}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||r===100?K.green("✓"):K.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",e=`\r${y}${w} ${$} ${u}${h}`,A=G.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,G.stdout.write(i.lastRenderedLine),t)G.stdout.write(`
22
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||Z()||!G.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(Z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zr(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,n);if(i.before)try{if((await kt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await pr(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function k$(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(u){if(c=u instanceof Error?u:Error(String(u)),$===r||!f(c))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function V$(i){return i instanceof Ui}function ke(i){return i instanceof Nn}function Ve(i){if(V$(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class Mn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:u=!0}=r,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(u)return Xr.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,n.useCamelCase)),u=`${r}_${$.join("_")}`,h=n.useBackwardCompatibility?`${r}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let y=tn.env[u]||(h?tn.env[h]:void 0);if(y!==void 0){if(n.verbose){let w=tn.env[u]?u:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,u,n.customParsers,n.configName)}catch(w){if(w instanceof Wn)throw w;throw at.envVar(u,y,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw at.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(tn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((u)=>this.formatEnvKey(u,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
23
+
24
+ `;for(let n of i)r+=`${n.key}
25
+ `,r+=` Type: ${n.type}
26
+ `,r+=` Description: ${n.description}
27
+ `,r+=` Example: ${n.example}
28
+
29
+ `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
30
+
31
+ `;r+=`| Variable | Type | Description | Example |
32
+ `,r+=`|----------|------|-------------|----------|
33
+ `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
34
+ `;return r}}function De(i,t){let r=P$("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function D$(i,t,r={}){return b$(i,t,r,new WeakMap)}function b$(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return o$(i,t,f,n);if(!Wi(t)||!Wi(i))return t;return Pe(i,t,r,n)}function o$(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return be(i,t);case"smart":return oe(i,t,n);default:return t}return t}function be(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>El(f,n)))r.push(n);return r}function oe(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Wi(t[0])&&Wi(i[0]))return Qe(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function Qe(i,t,r){let n=[...t];for(let f of i){if(!Wi(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((u)=>Wi(u)&&($ in u)&&u[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function Pe(i,t,r,n){let f=t;if(Wi(f)&&n.has(f))return n.get(f);let l={...i};if(Wi(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],u=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Wi($)&&Wi(u))l[c]=b$(u,$,r,n);else if(Array.isArray($)||Array.isArray(u))l[c]=o$(u,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function Gl(i,t,r="replace"){return D$(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function El(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!El(i[r],t[r]))return!1;return!0}if(Wi(i)&&Wi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!El(i[f],t[f]))return!1}return!0}return!1}function Wi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Gn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let h=vt.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let u=async()=>{if(!rn(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),w=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new Fr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Fr(i,Error("Configuration must export a valid object"),"unknown");let m={config:Gl(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)vt.setWithFileCheck("file",m,i,l);return m}catch(h){throw h instanceof Error?at.configLoad(i,h):at.configLoad(i,Error(String(h)))}};if(c)return Xr.track("loadFromPath",u,{path:i});return u()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(il(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return k$(async()=>{return rn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!rn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=il(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=il(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){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((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!rn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class Hl{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:u=!1}=r,h=async()=>{let y=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:w}}};if($)return await Xr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,r){try{if(!ye(t))throw new Nr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Nr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,u]of Object.entries(t.properties))if($ in c){let h=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],u,h,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(c))if(!$.has(u))f.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.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:tu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class dl{fileLoader=new Gn;envProcessor=new Mn;validator=new Hl;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let u=this.checkCache(c.name||"",c);if(u)return u}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(u){let h=c.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(h)throw u;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let y=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),w=!y&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),e=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw u;if(w&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)Oi.warn(`Slow configuration loading detected: ${u.duration}ms for ${c.name}`);$.metrics=u}return $}catch($){let u=Date.now()-t;throw Oi.error(`Configuration loading failed after ${u}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:u=!0,arrayStrategy:h="replace",verbose:y=!1}=i,w=l||Xt.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,$,h,y,u,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,u,n,y);let m=await this.loadHomeConfiguration(n,f,$,h,y,u);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,u,n,y);let s=await this.loadPackageJsonConfiguration(n,f,w,$,h,y,u);if(s)return e.push(ai(w,"package.json")),this.finalizeResult(s,e,u,n,y);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw at.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,u,y),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,u){let h=$?Ur(i,f,c):f,y=this.getLocalDirectories(r,n);for(let w of y){if(c)Oi.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(A){if(c)Oi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?Ur(i,r,f):r,$=[ai(gt(),".config",i),ai(gt(),".config"),gt()];for(let u of $){if(f)Oi.info(`Checking home directory: ${u}`);let h=this.fileLoader.generateConfigPaths(i,u,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:n,verbose:f});if(y){if(f)Oi.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?Ur(i,n,l):n;try{let u=ai(r,"package.json");if(!al(u))return null;let h=await import(u),y=h[i],w=i;if(!y&&t)y=h[t],w=t;if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)Oi.success(`Configuration loaded from package.json: ${w}`);return{config:Gl($,y,f),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(l)Oi.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ur(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw at.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return vt.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);vt.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,ai(i,"config"),ai(i,".config"),t?ai(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(ai(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[ai(gt(),".config",i),ai(gt(),".config"),gt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function c$(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||r}async function ve(i){return tt.loadConfig({...i,__strictErrorHandling:!0})}async function Q$(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await tt.loadConfig(i);else n=await tt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",l=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)Oi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await tt.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Ze(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await tt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&c$(r)))return(await tt.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await tt.loadConfig({...i,cwd:i.cwd||Xt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&c$(t)))return(await tt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function pe(i,t,r="replace"){let n=new Gn;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Ur(i,t,r=!1){let n=new Mn,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let u={...c};for(let[h,y]of Object.entries(c)){let w=[...$,h],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=Xt.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof y==="boolean")u[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let s=Number(A);if(!Number.isNaN(s))u[h]=s}else if(Array.isArray(y))try{u[h]=JSON.parse(A)}catch{u[h]=A.split(",").map((s)=>s.trim())}else u[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))u[h]=l(y,w)}return u}return l(t)}function i1(i){let t=ai(Xt.cwd(),i.configDir),r=ai(Xt.cwd(),i.generatedDir),n=ai(r,"config-types.ts");if(!al(G0(n)))qw(G0(n),{recursive:!0,mode:511});let f=al(t)?Lw(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${X1}
35
+ export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
36
+ `;xw(n,l,{mode:438})}function t1(i){let t=null,r=null,n=()=>{if(!r)r=Q$(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)Oi.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(l,c){if(t)return t[c];let $=f[c];return n(),$},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,$){if(!t)t={...f};return t[c]=$,!0}})}function r1(i){let t=Z0(Ae.cwd(),i?.configDir||"./config");function r(){if(!we(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=ee(t).filter((u)=>f.has(tl(u))).map((u)=>({base:u.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:u})),$=new Map;for(let{base:u,file:h}of c){let y=tl(h).toLowerCase(),w=$.get(u);if(!w){$.set(u,h);continue}let e=tl(w).toLowerCase();if(l.indexOf(y)<l.indexOf(e))$.set(u,h)}return Array.from($.entries()).map(([u,h])=>({base:u,file:h})).sort((u,h)=>u.base.localeCompare(h.base))}function n(){let f=r(),l=f.map((u)=>u.base),c=l.length?l.map((u)=>`'${u}'`).join(" | "):"string",$=f.length?`{
37
+ ${f.map((u)=>{let h=Z0(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
38
+ `)}
39
+ }`:"Record<string, any>";return`export type ConfigNames = ${c}
40
+ export type ConfigByName = ${$}
41
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
42
+ export type ConfigOf = Config
43
+ `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var P$,vt,Xr,v$,n1,f1,$$,en,Tl,ui,L,l1,u$,c1,h$,$1,u1,cl,h1,y$,w$,$l,y1,w1,e1,A1,An,Z$,s1,hi,a1,m1,e$,sn,Yl,p,K,E1,A$,T1,s$,Y1,B1,ul,C1,a$,m$,U1,hl,R1,S1,j1,F1,N1,an,p$,W1,X1="0.15.6",Ui,Nn,Fr,Bl,Cl,Wn,Ul,Rl,Nr,Sl,jl,at,iu,tu,Oi,tt,ru,nu,J1=Je(async()=>{P$=import.meta.require,vt=new Kl,Xr=new zl,v$={createKey:_e,isEquivalent:Ie,estimateMemoryUsage:Ke},n1=Bn(ml.cwd(),"config"),f1=Bn(ml.cwd(),"src/generated"),$$=Yn.env.CLARITY_LOG_DIR||Dw(Me(),"logs"),en={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Tl=await Ge(),ui={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},L=ui,l1=ui.red,u$=ui.green,c1=ui.yellow,h$=ui.blue,$1=ui.magenta,u1=ui.cyan,cl=ui.white,h1=ui.gray,y$=ui.bgRed,w$=ui.bgYellow,$l=ui.bold,y1=ui.dim,w1=ui.italic,e1=ui.underline,A1=ui.reset,An={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Z$={debug:"\uD83D\uDD0D",info:h$("ℹ"),success:u$("✓"),warning:w$(cl($l(" WARN "))),error:y$(cl($l(" ERROR ")))},s1=new Sn("stacks"),hi=new Sn("bunfig",{showTags:!0}),a1=si(jr.cwd(),"config"),m1=si(jr.cwd(),"src/generated"),e$=Tn.env.CLARITY_LOG_DIR||kw(qe(),"logs"),sn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:e$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Yl=await Le(),p={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},K=p,E1=p.red,A$=p.green,T1=p.yellow,s$=p.blue,Y1=p.magenta,B1=p.cyan,ul=p.white,C1=p.gray,a$=p.bgRed,m$=p.bgYellow,U1=p.bgGray,hl=p.bold,R1=p.dim,S1=p.italic,j1=p.underline,F1=p.strikethrough,N1=p.reset,an={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},p$={debug:"\uD83D\uDD0D",info:s$("ℹ"),success:A$("✓"),warning:m$(ul(hl(" WARN "))),error:a$(ul(hl(" ERROR ")))},W1=new Fn("stacks"),Ui=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Nn=class extends Ui{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${i}"${n} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}},Fr=class extends Ui{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Bl=class extends Ui{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}},Cl=class extends Ui{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Wn=class extends Ui{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}},Ul=class extends Ui{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Rl=class extends Ui{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Nr=class extends Ui{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}},Sl=class extends Ui{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}},jl=class extends Ui{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},at={configNotFound(i,t,r){return new Nn(i,t,r)},configLoad(i,t,r){return new Fr(i,t,r)},configValidation(i,t,r){return new Bl(i,t,r)},configMerge(i,t,r,n){return new Cl(i,t,r,n)},envVar(i,t,r,n){return new Wn(i,t,r,n)},fileSystem(i,t,r){return new Ul(i,t,r)},typeGeneration(i,t,r){return new Rl(i,t,r)},schemaValidation(i,t,r){return new Nr(i,t,r)},browserConfig(i,t,r,n){return new Sl(i,t,r,n)},plugin(i,t,r){return new jl(i,t,r)}},iu={replace:"replace",concat:"concat",smart:"smart"},tu=/^https?:\/\//,Oi=new Fn("bunfig",{showTags:!0}),tt=new dl,ru=ai(Xt.cwd(),"config"),nu=ai(Xt.cwd(),"src/generated")});function _1(i,t={}){let r=Cn.cwd();while(r.includes("storage"))r=p0(r,"..");let n=p0(r,i||"");if(t?.relative)return ae(Cn.cwd(),n);return n}var I1=Cn.env.CLARITY_LOG_DIR||se(_1(),"logs"),fu={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I1,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xn={...fu},eY=(async()=>{try{let{loadConfig:i}=await J1().then(()=>q$),t=await i({name:"clarity",alias:"logging",defaultConfig:fu,cwd:Cn.cwd()});if(t)Object.assign(Xn,t)}catch{}return Xn})();function ii(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function K1(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pi<"u"){let i=pi.type;if(i==="renderer"||i==="worker")return!1;return!!(pi.versions&&(pi.versions.node||pi.versions.bun))}return!1}class lu{async format(i){let t=await K1(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=li,AY=li.red,z1=li.green,sY=li.yellow,O1=li.blue,aY=li.magenta,mY=li.cyan,E$=li.white,EY=li.gray,M1=li.bgRed,G1=li.bgYellow,TY=li.bgGray,T$=li.bold,YY=li.dim,BY=li.italic,CY=li.underline,UY=li.strikethrough,RY=li.reset,yl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},H1={debug:"\uD83D\uDD0D",info:O1("ℹ"),success:z1("✓"),warning:G1(E$(T$(" WARN "))),error:M1(E$(T$(" ERROR ")))};class Hn{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(i,t={}){this.name=i,this.config={...Xn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new lu,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??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...yl,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...yl};return{...yl,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Xn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ii()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await Be(this.config.logDirectory,n$.F_OK|n$.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await Ce(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Qi.from(i);try{if(!nn(this.currentLogFile))await fl(this.currentLogFile,"",{mode:420});if(n=r$(this.currentLogFile,"a",420),Ye(n,$,{flag:"a"}),t$(n),n!==void 0)nl(n),n=void 0;if((await bt(this.currentLogFile)).size===0){if(await fl(this.currentLogFile,$,{flag:"w",mode:420}),(await bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(f<l-1){let y=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,y);let w=c*2**f;await new Promise((e)=>setTimeout(e,w)),f++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{nl(n)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch($){if(f===l-1){let h=$,y=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",y),$}f++;let u=c*2**(f-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 ot(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 ot(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ot(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ii())return;if(!this.shouldWriteToFile())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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return rl(16).toString("hex")}generateKey(){return rl(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(),r=rl(16),n=me("aes-256-gcm",t,r),f=Qi.isBuffer(i)?i:Qi.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,u=n.getAuthTag(),h=Qi.allocUnsafe(16+$+16);return r.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),u.copy(h,16+$),{encrypted:h,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=l$(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(Qi.from(Qi.concat(f)))),n.on("error",r),n.write(i),n.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(ii())return;if(!this.shouldWriteToFile())return;let i=await bt(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await fn(this.config.logDirectory),l=f.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,h)=>{let y=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await bt(r).catch(()=>null))try{if(await f$(r,$),t.compress)try{let u=`${$}.gz`;await this.compressLogFile($,u),await ln($)}catch(u){console.error("Error compressing rotated file:",u)}if(l.length===0&&!f.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await fl(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await bt(r).catch(()=>null))await f$(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await fn(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await ln(ot(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=i$(i),n=Te(t),f=l$();await Se(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),nn(this.currentLogFile))try{let i=r$(this.currentLogFile,"r+");t$(i),nl(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(!ii()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await fn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await ln(ot(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ii())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let u=H.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${r} ${f}`;else if(l==="info"||l==="success")h=`${r} ${n} ${f}`;else h=`${r} ${n} ${O.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,w=$(t).length,e=Math.max(1,u-2-y-w);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=O.underline(O.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,u="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>O.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>O.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>O.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>O.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>O.strikethrough(n)),t}supportsHyperlinks(){if(ii())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=H.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Ue(t)||t.startsWith("./")||t.startsWith("../"))t=Re(t);else return null;return nn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:u,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":H1[i],e=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:O.gray(u),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:O.green(u),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.error(A),$){let m=$.split(`
44
+ `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!ii()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
45
+ `;if($)y+=`${$}
46
+ `;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let r={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ii()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!ii()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!ii()&&H.stdout.isTTY)H.stdout.write(`
47
+ `);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ii()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:r,message:`${O.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),u=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)u+=` ${JSON.stringify(r)}`;if(u+=`
48
+ `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":O.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ii())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}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}`,r=new Hn(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(r),r}createReadStream(){if(ii())throw Error("createReadStream is not supported in browser environments");if(!nn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return i$(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 r=this.keys.get(this.currentKeyId);try{let n=Qi.isBuffer(i)?i:Qi.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=Ee("aes-256-gcm",r,f);$.setAuthTag(l);let u=$.update(c),h=$.final(),y=u.length+h.length,w=Qi.allocUnsafe(y);return u.copy(w,0),h.copy(w,u.length),w.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ii()}isServerMode(){return!ii()}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,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
49
+ `),u=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(u)}┐`,y=`└${"─".repeat(u)}┘`,w=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:O.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(h),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(y),showTimestamp:!1}))}else if(!ii())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ii())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();H.stdin.removeListener("data",r);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",r)})}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 r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(r=i.replace(c,(u,h)=>{if(h==="%")return"%";if($>=t.length)return u;let y=t[$++];switch(h){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 u}}),$<t.length)r+=` ${t.slice($).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${$}${c} ${O.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
51
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=O.green("━".repeat(n)),c=O.gray("━".repeat(f)),$=`[${l}${c}]`,u=`${r}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||r===100?O.green("✓"):O.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",e=`\r${y}${w} ${$} ${u}${h}`,A=H.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
52
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ii()||!H.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(ii()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await fn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=ot(this.config.logDirectory,n);if(i.before)try{if((await bt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ln(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var SY=new Hn("stacks");class Hi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class cu extends Hi{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class Jn extends Hi{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class $u extends Hi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class uu extends Hi{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class gl extends Hi{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class hu extends Hi{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class yu extends Hi{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class _n extends Hi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class wu extends Hi{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class eu extends Hi{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Zt={configNotFound(i,t,r){return new cu(i,t,r)},configLoad(i,t,r){return new Jn(i,t,r)},configValidation(i,t,r){return new $u(i,t,r)},configMerge(i,t,r,n){return new uu(i,t,r,n)},envVar(i,t,r,n){return new gl(i,t,r,n)},fileSystem(i,t,r){return new hu(i,t,r)},typeGeneration(i,t,r){return new yu(i,t,r)},schemaValidation(i,t,r){return new _n(i,t,r)},browserConfig(i,t,r,n){return new wu(i,t,r,n)},plugin(i,t,r){return new eu(i,t,r)}};async function d1(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(u){if(c=u instanceof Error?u:Error(String(u)),$===r||!f(c))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class ql{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:u=!0}=r,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(u)return Il.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,n.useCamelCase)),u=`${r}_${$.join("_")}`,h=n.useBackwardCompatibility?`${r}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let y=cn.env[u]||(h?cn.env[h]:void 0);if(y!==void 0){if(n.verbose){let w=cn.env[u]?u:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,u,n.customParsers,n.configName)}catch(w){if(w instanceof gl)throw w;throw Zt.envVar(u,y,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Zt.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(cn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((u)=>this.formatEnvKey(u,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
53
+
54
+ `;for(let n of i)r+=`${n.key}
55
+ `,r+=` Type: ${n.type}
56
+ `,r+=` Description: ${n.description}
57
+ `,r+=` Example: ${n.example}
58
+
59
+ `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
60
+
61
+ `;r+=`| Variable | Type | Description | Example |
62
+ `,r+=`|----------|------|-------------|----------|
63
+ `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
64
+ `;return r}}function g1(i,t,r={}){return Au(i,t,r,new WeakMap)}function Au(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return su(i,t,f,n);if(!Xi(t)||!Xi(i))return t;return k1(i,t,r,n)}function su(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return q1(i,t);case"smart":return L1(i,t,n);default:return t}return t}function q1(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Fl(f,n)))r.push(n);return r}function L1(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Xi(t[0])&&Xi(i[0]))return x1(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function x1(i,t,r){let n=[...t];for(let f of i){if(!Xi(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((u)=>Xi(u)&&($ in u)&&u[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function k1(i,t,r,n){let f=t;if(Xi(f)&&n.has(f))return n.get(f);let l={...i};if(Xi(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],u=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Xi($)&&Xi(u))l[c]=Au(u,$,r,n);else if(Array.isArray($)||Array.isArray(u))l[c]=su(u,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function au(i,t,r="replace"){return g1(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Fl(i[r],t[r]))return!1;return!0}if(Xi(i)&&Xi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Fl(i[f],t[f]))return!1}return!0}return!1}function Xi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class mu{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let h=Un.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let u=async()=>{if(!$n(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),w=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new Jn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Jn(i,Error("Configuration must export a valid object"),"unknown");let m={config:au(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Un.setWithFileCheck("file",m,i,l);return m}catch(h){throw h instanceof Error?Zt.configLoad(i,h):Zt.configLoad(i,Error(String(h)))}};if(c)return Il.track("loadFromPath",u,{path:i});return u()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(ll(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of n){if(!l)continue;if(r.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)r.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return r.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return d1(async()=>{return $n(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!$n(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=ll(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=ll(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){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((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!$n(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var V1=/^https?:\/\//;class Eu{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:u=!1}=r,h=async()=>{let y=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:w}}};if($)return await Il.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,r){try{if(!je(t))throw new _n(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new _n(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,u]of Object.entries(t.properties))if($ in c){let h=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],u,h,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(c))if(!$.has(u))f.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.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:V1},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Pi=new Hn("bunfig",{showTags:!0});function D1(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Tu{fileLoader=new mu;envProcessor=new ql;validator=new Eu;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let u=this.checkCache(c.name||"",c);if(u)return u}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(u){let h=c.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(h)throw u;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let y=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),w=!y&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),e=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw u;if(w&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)Pi.warn(`Slow configuration loading detected: ${u.duration}ms for ${c.name}`);$.metrics=u}return $}catch($){if($ instanceof Error&&$.name==="ConfigNotFoundError")throw $;let u=Date.now()-t;throw Pi.error(`Configuration loading failed after ${u}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:u=!0,arrayStrategy:h="replace",verbose:y=!1}=i,w=l||On.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,$,h,y,u,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,u,n,y);let m=await this.loadHomeConfiguration(n,f,$,h,y,u);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,u,n,y);let s=await this.loadPackageJsonConfiguration(n,f,w,$,h,y,u);if(s)return e.push(Ni(w,"package.json")),this.finalizeResult(s,e,u,n,y);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw Zt.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,u,y),warnings:[`No configuration file found for "${n}"${D1(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,u){let h=$?hn(i,f,c):f,y=this.getLocalDirectories(r,n);for(let w of y){if(c)Pi.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(A){if(c)Pi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?hn(i,r,f):r,$=[Ni(dt(),".config",i),Ni(dt(),".config"),dt()];for(let u of $){if(f)Pi.info(`Checking home directory: ${u}`);let h=this.fileLoader.generateConfigPaths(i,u,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:n,verbose:f});if(y){if(f)Pi.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?hn(i,n,l):n;try{let u=Ni(r,"package.json");if(!dw(u))return null;let h={};try{h=JSON.parse(gw(u,"utf8"))}catch(e){if(l)Pi.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let y=h[i],w=i;if(!y&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(h[A]){y=h[A],w=A;break}}}if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)Pi.success(`Configuration loaded from package.json: ${w}`);return{config:au($,y,f),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(l)Pi.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:hn(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Zt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return Un.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);Un.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ni(i,"config"),Ni(i,".config"),t?Ni(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ni(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ni(dt(),".config",i),Ni(dt(),".config"),dt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var jY=new Tu;function hn(i,t,r=!1){let n=new ql,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let u={...c};for(let[h,y]of Object.entries(c)){let w=[...$,h],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=On.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof y==="boolean")u[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let s=Number(A);if(!Number.isNaN(s))u[h]=s}else if(Array.isArray(y))try{u[h]=JSON.parse(A)}catch{u[h]=A.split(",").map((s)=>s.trim())}else u[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))u[h]=l(y,w)}return u}return l(t)}var FY=Ni(On.cwd(),"config"),NY=Ni(On.cwd(),"src/generated"),Yu={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:Vf.join(kf.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Vf.join(kf.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Vf.join(kf.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},v=Yu,Mi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Pt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function Cu(i){return Nl.readFileSync(i,"utf8")}function Wl(i,t){let r=[];function n(f){let l;try{l=Nl.readdirSync(f)}catch{return}for(let c of l){let $=zi.join(f,c);try{if(Nl.statSync($).isDirectory())n($);else if(c===t)r.push(f)}catch{continue}}}return n(i),r}function U(i,t,r){if(r||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var P1=Q1(b1);function Uu(){return Bu.env.SUDO_PASSWORD}var Y$="[redacted]",v1=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Z1=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function p1(i){let t=i.toLowerCase();return v1.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function In(i){if(Array.isArray(i))return i.map((r)=>In(r));if(typeof i==="string")return Z1.test(i)?Y$:i;if(!i||typeof i!=="object")return i;let t={};for(let[r,n]of Object.entries(i)){if(p1(r)){t[r]=Y$;continue}t[r]=In(n)}return t}function dn(i){return JSON.stringify(In(i))}function iA(i){let t=Uu();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let r=t.replace(/'/g,"'\\''"),n=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function st(i,t={}){let r=iA(i);try{let{stdout:n,stderr:f}=await P1(r,{cwd:t.cwd||Bu.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:f.trim()}}catch(n){let f=Error(`Failed to execute command: ${i}
65
+ Error: ${n.message}`);throw f.stack=n.stack,f}}function Ru(i){if(i.domain)return i.domain;if(i.domains?.length)return i.domains[0];throw Error("Either domain or domains must be specified")}function Ll(i){let t=zi.join(o1.homedir(),".stacks","ssl"),r=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,n=i.certPath?zi.isAbsolute(i.certPath)?i.certPath:zi.join(r,i.certPath):zi.join(r,v.certPath),f=i.keyPath?zi.isAbsolute(i.keyPath)?i.keyPath:zi.join(r,i.keyPath):zi.join(r,v.keyPath),l=i.caCertPath?zi.isAbsolute(i.caCertPath)?i.caCertPath:zi.join(r,i.caCertPath):zi.join(r,v.caCertPath);return{certPath:n,keyPath:f,caCertPath:l,basePath:r}}function Su(i){let t=[],r=new Set;if(i.domain)r.add(i.domain);if(i.domains?.length)i.domains.forEach((n)=>r.add(n));for(let n of r)t.push({type:2,value:n});if(i.altNameIPs?.length)for(let n of i.altNameIPs)t.push({type:7,ip:n});if(i.altNameURIs?.length)for(let n of i.altNameURIs)t.push({type:6,value:n});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return U(S.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function xl(i){let t=i.notBeforeDays??Mi.DEFAULT_NOT_BEFORE_DAYS,r=i.validityDays??(i.validityYears?i.validityYears*365:Mi.DEFAULT_VALIDITY_DAYS);U(S.CERT,"Calculating certificate validity dates",i.verbose);let n=new Date(Date.now()-86400*t*1000),f=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),U(S.CERT,`Validity period: ${n.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:n,notAfter:f}}var Gi={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},mi={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function Rr(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Si(i,t){let r=Rr(t.length);return Buffer.concat([Buffer.from([i]),r,t])}function Wr(i){let t=i.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let f=t[n],l=[];l.unshift(f&127),f>>=7;while(f>0)l.unshift(f&127|128),f>>=7;r.push(...l)}return Si(Gi.OID,Buffer.from(r))}function Xl(i){let t;if(typeof i==="bigint"){let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Si(Gi.INTEGER,t)}function ju(i,t=0){return Si(Gi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Fu(i){return Si(Gi.OCTET_STRING,i)}function Ri(...i){return Si(Gi.SEQUENCE,Buffer.concat(i))}function tA(...i){return Si(Gi.SET,Buffer.concat(i))}function rA(i){return Si(Gi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function nA(i){return Si(Gi.UTF8_STRING,Buffer.from(i,"utf8"))}function fA(){return Buffer.from([Gi.NULL,0])}function B$(i,t,r=!0){let n=160|i|(r?0:0),f=Rr(t.length);return Buffer.concat([Buffer.from([n]),f,t])}function C$(i){let t=i.getUTCFullYear();if(t>=2050){let r=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Si(Gi.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),n=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),c=i.getUTCMinutes().toString().padStart(2,"0"),$=i.getUTCSeconds().toString().padStart(2,"0"),u=`${r}${n}${f}${l}${c}${$}Z`;return Si(Gi.UTC_TIME,Buffer.from(u,"ascii"))}}function lA(i,t){return Ri(C$(i),C$(t))}function U$(i){let t=[];for(let r of i){let n;switch(r.shortName){case"CN":n=mi.COMMON_NAME;break;case"C":n=mi.COUNTRY;break;case"L":n=mi.LOCALITY;break;case"ST":n=mi.STATE;break;case"O":n=mi.ORGANIZATION;break;case"OU":n=mi.ORGANIZATIONAL_UNIT;break;default:continue}let f=r.shortName==="C"?rA(r.value):nA(r.value),l=Ri(Wr(n),f);t.push(tA(l))}return Ri(...t)}function Nu(i){return Ri(Wr(i),fA())}function cA(i){return i.export({type:"spki",format:"der"})}function $A(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),l=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],$=8-l.length-c.length,u=Array.from({length:$},()=>"0");t=[...l,...u,...c].join(":")}let r=t.split(":"),n=Buffer.alloc(16);for(let f=0;f<8;f++){let l=Number.parseInt(r[f]||"0",16);n.writeUInt16BE(l,f*2)}return n}else{let t=i.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function uA(i){let t=[];for(let r of i)if(r.type===2&&r.value){let n=Rr(r.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=$A(r.ip),f=Rr(n.length);t.push(Buffer.concat([Buffer.from([135]),f,n]))}else if(r.type===6&&r.value){let n=Rr(r.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return Ri(...t)}function hA(i,t){if(i){if(t!==void 0)return Ri(Si(1,Buffer.from([255])),Xl(t));return Ri(Si(1,Buffer.from([255])))}return Ri()}function yA(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let r=0,n=t;while(n>0&&(n&1)===0)r++,n>>=1;if(t===0)r=7;return ju(Buffer.from([t]),r)}function wA(i){let t=[];if(i.serverAuth)t.push(Wr(mi.SERVER_AUTH));if(i.clientAuth)t.push(Wr(mi.CLIENT_AUTH));return Ri(...t)}function Cr(i,t,r){let n=[Wr(i)];if(t)n.push(Si(1,Buffer.from([255])));return n.push(Fu(r)),Ri(...n)}function eA(i){let t=[];if(t.push(B$(0,Xl(2))),t.push(Xl(i.serialNumber)),t.push(Nu(mi.SHA256_WITH_RSA)),t.push(U$(i.issuer)),t.push(lA(i.notBefore,i.notAfter)),t.push(U$(i.subject)),t.push(cA(i.publicKey)),i.extensions){let r=[];if(i.extensions.basicConstraints)r.push(Cr(mi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,hA(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)r.push(Cr(mi.KEY_USAGE,i.extensions.keyUsage.critical??!0,yA(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)r.push(Cr(mi.EXTENDED_KEY_USAGE,!1,wA(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)r.push(Cr(mi.SUBJECT_ALT_NAME,!1,uA(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)r.push(Cr(mi.SUBJECT_KEY_IDENTIFIER,!1,Fu(i.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(B$(3,Ri(...r)))}return Ri(...t)}function AA(i,t){let r=pt.createSign("SHA256");r.update(i);let n=r.sign(t);return Ri(i,Nu(mi.SHA256_WITH_RSA),ju(n))}function sA(i,t){let r=i.toString("base64"),n=[];for(let f=0;f<r.length;f+=64)n.push(r.slice(f,f+64));return`-----BEGIN ${t}-----
66
+ ${n.join(`
67
+ `)}
68
+ -----END ${t}-----
69
+ `}function kl(){let i=pt.randomBytes(20);return i[0]=i[0]&127||1,i}function Wu(i=2048){let{privateKey:t,publicKey:r}=pt.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:r}}function aA(i){let t=i.export({type:"spki",format:"der"});return pt.createHash("sha1").update(t).digest()}function Xu(i){let t={serialNumber:i.serialNumber||kl(),notBefore:i.notBefore,notAfter:i.notAfter,subject:i.subject,issuer:i.issuer||i.subject,publicKey:i.publicKey,extensions:{basicConstraints:{isCA:i.isCA??!1,critical:!0,pathLenConstraint:i.pathLenConstraint},subjectKeyIdentifier:aA(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let r=eA(t),n=AA(r,i.signingKey);return{certificate:sA(n,"CERTIFICATE"),certificateDer:n}}function Ju(i){return i.export({type:"pkcs8",format:"pem"})}function mA(i){return pt.createPrivateKey(i)}function EA(i){let t=new pt.X509Certificate(i),r=t.publicKey,n=[],f=t.subject.split(`
70
+ `);for(let l of f){let[c,...$]=l.split("="),u=$.join("=");if(c&&u)n.push({shortName:c.trim(),value:u.trim()})}return{publicKey:r,subject:n}}async function Vl(i={}){U("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Mi.DEFAULT_KEY_SIZE;U("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:r,publicKey:n}=Wu(t),f=[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:l,notAfter:c}=xl({validityYears:i.validityYears||Mi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:$}=Xu({serialNumber:kl(),notBefore:l,notAfter:c,subject:f,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:$,privateKey:Ju(r),notBefore:l,notAfter:c}}async function Dl(i){if(U("ca","Generating new certificate",i.verbose),U("ca",`Options: ${dn(i)}`,i.verbose),!i.domain&&!i.domains?.length)throw Error("Either domain or domains must be specified");if(!i.rootCA?.certificate||!i.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=EA(i.rootCA.certificate),r=mA(i.rootCA.privateKey);U("ca",`Generating ${Mi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let n=Mi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:l}=Wu(n),c=i.commonName||Ru(i),$=i.certificateAttributes||[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organizationName||v.organizationName},{shortName:"CN",value:c}],{notBefore:u,notAfter:h}=xl({validityDays:i.validityDays||Mi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),y=Su(i),w=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},e=i.extKeyUsage||{serverAuth:!0},{certificate:A}=Xu({serialNumber:kl(),notBefore:u,notAfter:h,subject:$,issuer:t,publicKey:l,signingKey:r,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:w,extendedKeyUsage:e,subjectAltName:y});return{certificate:A,privateKey:Ju(f),notBefore:u,notAfter:h}}function _u(i,t){U(S.STORAGE,`Storing certificate and private key with options: ${dn(t)}`,t?.verbose);let{certPath:r,keyPath:n}=Ll({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});U(S.STORAGE,`Certificate path: ${r}`,t?.verbose),U(S.STORAGE,`Private key path: ${n}`,t?.verbose);let f=Jl.dirname(r);if(!it.existsSync(f))U(S.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),it.mkdirSync(f,{recursive:!0});U(S.STORAGE,"Writing certificate file",t?.verbose),it.writeFileSync(r,i.certificate);let l=Jl.dirname(n);if(!it.existsSync(l))U(S.STORAGE,`Creating private key directory: ${l}`,t?.verbose),it.mkdirSync(l,{recursive:!0});return U(S.STORAGE,"Writing private key file",t?.verbose),it.writeFileSync(n,i.privateKey),U(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function Iu(i,t){U(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=Ll({basePath:t?.basePath,caCertPath:t?.caCertPath});U(S.STORAGE,`CA certificate path: ${r}`,t?.verbose);let n=Jl.dirname(r);if(!it.existsSync(n))U(S.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),it.mkdirSync(n,{recursive:!0});return U(S.STORAGE,"Writing CA certificate file",t?.verbose),it.writeFileSync(r,i),U(S.STORAGE,"CA certificate stored successfully",t?.verbose),r}function gn(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=Cu(i);return new TA.X509Certificate(t)}function qn(i){return gn(i).fingerprint256.replace(/:/g,"").toUpperCase()}function bl(i){return Ku(gn(i).subject)}function ol(i,t,r=443,n=4000){let f;try{f=t.includes("-----BEGIN")?t:YA.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((l)=>{let c=!1,$=(h)=>{if(c)return;c=!0,l(h)},u=BA.connect({host:i,port:r,servername:i,ca:f,rejectUnauthorized:!0},()=>{$(u.authorized),u.end()});u.setTimeout(n,()=>{u.destroy(),$(!1)}),u.on("error",()=>$(!1))})}function CA(i){let t=[],r=i.split(`
71
+ `);for(let n of r){let[f,...l]=n.split("="),c=l.join("=");if(f&&c)t.push({shortName:f.trim(),value:c.trim()})}return t}function Ku(i){return CA(i).find((t)=>t.shortName==="CN")?.value||""}function UA(i){let t=[],r=Ku(i.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let n=i.subjectAltName;if(n){let f=n.split(", ");for(let l of f)if(l.startsWith("DNS:"))t.push(l.slice(4))}return[...new Set(t)]}function Ql(i,t){let r=gn(i),n=UA(r);for(let f of n){if(f===t)return!0;if(f.startsWith("*.")){let l=f.slice(2);if(t.endsWith(l)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function SA(i,t){if(Kn.platform()!=="darwin")return!1;try{let r=qn(i);if(!r)return U(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(RA("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
72
+ `).some((n)=>{let f=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===r}))return U(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return U(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return U(S.TRUST,`Error checking certificate trust: ${r}`,t),!1}}var jA={platform:"darwin",async addCertificate(i,t){if(await SA(i,t?.verbose)){U(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),Pt.success("Certificate is already trusted in system keychain");return}U(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await st(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,r){let n=r||v.commonName;U(S.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await st(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),U(S.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},FA={platform:"win32",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await st(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,r){let n=r||v.commonName;U(S.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await st(`certutil -delstore -enterprise Root "${n}"`),U(S.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},NA={platform:"linux",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=Kn.homedir(),n=Mi.LINUX_CERT_DB_FILENAME,f=Mi.LINUX_TRUST_ARGS;U(S.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let l=Wl(r,n);if(l.length===0){Pt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of l){U(S.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{U(S.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await st(`certutil -d sql:${c} -D -n ${v.commonName}`)}catch($){U(S.TRUST,`Warning: Error deleting existing cert: ${$}`,t?.verbose),console.warn(`Error deleting existing cert: ${$}`)}U(S.TRUST,`Adding new certificate to ${c}`,t?.verbose),await st(`certutil -d sql:${c} -A -t ${f} -n ${v.commonName} -i ${i}`),Pt.info(`Cert added to ${c}`)}},async removeCertificate(i,t,r){let n=r||v.commonName;U(S.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let f=Kn.homedir(),l=Mi.LINUX_CERT_DB_FILENAME;U(S.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let c=Wl(f,l);if(c.length===0){Pt.warn("No certificate databases found. Cannot remove certificate.");return}for(let $ of c){U(S.TRUST,`Processing certificate database in ${$}`,t?.verbose);try{await st(`certutil -d sql:${$} -D -n "${n}"`),Pt.info(`Cert removed from ${$}`)}catch(u){U(S.TRUST,`Error removing cert from ${$}: ${u}`,t?.verbose),console.warn(`Error removing cert from ${$}: ${u}`)}}}},WA={darwin:jA,win32:FA,linux:NA};async function Pl(i,t,r){U(S.TRUST,`Adding certificate to system trust store with options: ${dn(r)}`,r?.verbose),U(S.TRUST,"Storing certificate and private key",r?.verbose);let n=_u(i,r);U(S.TRUST,"Storing CA certificate",r?.verbose);let f=Iu(t,r),l=Kn.platform();U(S.TRUST,`Detected platform: ${l}`,r?.verbose);let c=WA[l];if(!c){let $=`Unsupported platform: ${l}`;throw U(S.TRUST,`Error: ${$}`,r?.verbose),Error($)}return await c.addCertificate(f,r),U(S.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as Hc}from"node:os";import{join as dc,resolve as yU}from"node:path";import{existsSync as zu,statSync as Ou}from"fs";import{existsSync as XA,mkdirSync as SB,readdirSync as jB,readFileSync as JA,writeFileSync as FB}from"fs";import{homedir as ir}from"os";import{dirname as XB,resolve as Ji}from"path";import Uf from"process";import{existsSync as Mu,statSync as Gu}from"fs";import{existsSync as mc,mkdirSync as _A,readdirSync as IA,writeFileSync as KA}from"fs";import{homedir as tr}from"os";import{dirname as Hu,resolve as Ti}from"path";import Jt from"process";import{join as zA,relative as OA,resolve as du}from"path";import hf from"process";import{existsSync as Uh,mkdirSync as dB,readdirSync as gB,writeFileSync as qB}from"fs";import{homedir as vl}from"os";import{dirname as kB,resolve as Ei}from"path";import _r from"process";import{join as MA,relative as GA,resolve as gu}from"path";import yf from"process";import{existsSync as Rh,mkdirSync as QB,readdirSync as PB,writeFileSync as vB}from"fs";import{dirname as pB,resolve as wf}from"path";import Ec from"process";import{Buffer as Et}from"buffer";import{createCipheriv as HA,createDecipheriv as dA,randomBytes as Zl}from"crypto";import{closeSync as pl,createReadStream as qu,createWriteStream as gA,existsSync as ic,fsyncSync as Lu,openSync as xu,writeFileSync as qA}from"fs";import{access as LA,constants as ku,mkdir as xA,readdir as Ln,rename as Vu,stat as rr,unlink as xn,writeFile as tc}from"fs/promises";import{join as nr}from"path";import yi from"process";import{pipeline as kA}from"stream/promises";import{createGzip as Du}from"zlib";import fr from"process";import lt from"process";import{Buffer as rt}from"buffer";import{createCipheriv as VA,createDecipheriv as DA,randomBytes as rc}from"crypto";import{closeSync as nc,createReadStream as bu,createWriteStream as bA,existsSync as kn,fsyncSync as ou,openSync as Qu,writeFileSync as oA}from"fs";import{access as QA,constants as Pu,mkdir as PA,readdir as Vn,rename as vu,stat as lr,unlink as Dn,writeFile as fc}from"fs/promises";import{isAbsolute as vA,join as cr,resolve as ZA}from"path";import _ from"process";import{pipeline as pA}from"stream/promises";import{createGzip as Zu}from"zlib";import $r from"process";import ct from"process";import bn from"process";import{existsSync as on}from"fs";import{resolve as lc}from"path";import{existsSync as is}from"fs";import{existsSync as ts,readdirSync as rs}from"fs";import{extname as cc,resolve as pu}from"path";import ns from"process";import{join as fs,relative as ls,resolve as ih}from"path";import ef from"process";import{Buffer as nt}from"buffer";import{createCipheriv as cs,createDecipheriv as $s,randomBytes as $c}from"crypto";import{closeSync as uc,createReadStream as th,createWriteStream as us,existsSync as Qn,fsyncSync as rh,openSync as nh,writeFileSync as hs}from"fs";import{access as ys,constants as fh,mkdir as ws,readdir as Pn,rename as lh,stat as ur,unlink as vn,writeFile as hc}from"fs/promises";import{isAbsolute as es,join as hr,resolve as As}from"path";import I from"process";import{pipeline as ss}from"stream/promises";import{createGzip as ch}from"zlib";import yr from"process";import $t from"process";import pn from"process";import{existsSync as tf}from"fs";import{resolve as ac}from"path";import{existsSync as za}from"fs";class Bh{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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!zu(i))return!0;return Ou(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=zu(r)?Ou(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Ch{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}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 r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var uf=new Bh,Wc=new Ch;var as=Object.defineProperty,ms=(i)=>i;function Es(i,t){this[i]=ms.bind(null,t)}var Ts=(i,t)=>{for(var r in t)as(i,r,{get:t[r],enumerable:!0,configurable:!0,set:Es.bind(t,r)})},Ys=(i,t)=>()=>(i&&(t=i(i=0)),t),Sh={};Ts(Sh,{withErrorRecovery:()=>Nh,tryLoadConfig:()=>Ls,loadConfigWithResult:()=>gs,loadConfig:()=>Ih,isRetryableError:()=>zs,isConfigNotFoundError:()=>Ks,isBunfigError:()=>Wh,globalPerformanceMonitor:()=>zr,globalCache:()=>wr,getEnvOrDefault:()=>Os,generateConfigTypes:()=>xs,defaultGeneratedDir:()=>gh,defaultConfigDir:()=>dh,deepMergeWithArrayStrategy:()=>Kc,deepMerge:()=>Xh,createLibraryConfig:()=>ks,config:()=>qs,bunfigPlugin:()=>Vs,applyEnvVarsToConfig:()=>Jr,TypeGenerationError:()=>Sc,SchemaValidationError:()=>Kr,PluginError:()=>Fc,PerformanceMonitor:()=>Jc,FileSystemError:()=>Rc,ErrorFactory:()=>Tt,EnvVarError:()=>Tf,EnvProcessor:()=>Rf,ConfigValidator:()=>zc,ConfigValidationError:()=>Cc,ConfigNotFoundError:()=>Ef,ConfigMergeError:()=>Uc,ConfigLoader:()=>Oc,ConfigLoadError:()=>Ir,ConfigFileLoader:()=>Sf,ConfigCache:()=>Xc,CacheUtils:()=>zh,BunfigError:()=>ji,BrowserConfigError:()=>jc,ArrayMergeStrategies:()=>Gh});class Xc{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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!Mu(i))return!0;return Gu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=Mu(r)?Gu(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Jc{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}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 r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function Bs(i,t={}){let n=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return n?`${i}:${n}`:i}function Cs(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function Us(i){return i.getStats().size*2}function _c(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&D(t[0])&&"id"in t[0]&&t[0].id===3&&D(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(D(t)&&D(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(D(i)&&"arr"in i&&Array.isArray(i.arr)&&D(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&D(t[0])&&D(i[0])){let n=[...t];for(let f of i)if(D(f)&&"name"in f){if(!n.find((c)=>D(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(D(f)&&"path"in f){if(!n.find((c)=>D(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((l)=>Af(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!D(t)||!D(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(D(f)&&D(r[n]))r[n]=_c(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&D(f[0])&&D(r[n][0])){let l=[...f];for(let c of r[n])if(D(c)&&"name"in c){if(!l.find((u)=>D(u)&&("name"in u)&&u.name===c.name))l.push(c)}else if(D(c)&&"path"in c){if(!l.find((u)=>D(u)&&("path"in u)&&u.path===c.path))l.push(c)}else if(!l.some(($)=>Af($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Af(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Af(i[r],t[r]))return!1;return!0}if(D(i)&&D(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Af(i[f],t[f]))return!1}return!0}return!1}function D(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Rs(i,t){if(!Rh(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return _c(t,n)}catch{return null}}catch{return null}}async function Ss({name:i="",cwd:t,defaultConfig:r}){let n=t||Ec.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let $ of f){let u=wf(n,`${c}${$}`),h=await Rs(u,r);if(h!==null)return h}try{let c=wf(n,"package.json");if(Rh(c)){let u=(await import(c))[i];if(u&&typeof u==="object"&&!Array.isArray(u))try{return _c(r,u)}catch{}}}catch{}return r}function js(i,t={}){let r=yf.cwd();while(r.includes("storage"))r=gu(r,"..");let n=gu(r,i||"");if(t?.relative)return GA(yf.cwd(),n);return n}async function Fs(){try{let i=await Ss({name:"clarity",defaultConfig:ff,cwd:yf.cwd(),endpoint:"",headers:{}});return{...ff,...i}}catch{return ff}}function Q(){if(lt.env.NODE_ENV==="test"||lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ns(){if(lt.env.NODE_ENV==="test"||lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lt<"u"){let i=lt.type;if(i==="renderer"||i==="worker")return!1;return!!(lt.versions&&(lt.versions.node||lt.versions.bun))}return!1}class jh{async format(i){let t=await Ns(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:fr.pid,hostname:t(),environment:fr.env.NODE_ENV||"development",platform:fr.platform,version:fr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fr.env.NODE_ENV||fr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sf{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={...Yc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new jh,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 r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...lf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...lf};return{...lf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Yc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await LA(this.config.logDirectory,ku.F_OK|ku.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await xA(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let u=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Et.from(i);try{if(!ic(this.currentLogFile))await tc(this.currentLogFile,"",{mode:420});if(f=xu(this.currentLogFile,"a",420),qA(f,u,{flag:"a"}),Lu(f),f!==void 0)pl(f),f=void 0;if((await rr(this.currentLogFile)).size===0){if(await tc(this.currentLogFile,u,{flag:"w",mode:420}),(await rr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let y=h;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(l<c-1){let w=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,w);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(f!==void 0)try{pl(f)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(u){if(l===c-1){let y=u,w=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),u}l++;let h=$*2**(l-1);await new Promise((y)=>setTimeout(y,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 nr(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 nr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,u])=>u.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return Zl(16).toString("hex")}generateKey(){return Zl(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(),r=Zl(16),n=HA("aes-256-gcm",t,r),f=Et.concat([n.update(i,"utf8"),n.final()]),l=n.getAuthTag();return{encrypted:Et.concat([r,f,l]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Du(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(Et.from(Et.concat(f)))),n.on("error",r),n.write(i),n.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(Q())return;let i=await rr(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ln(this.config.logDirectory),l=f.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,h)=>{let y=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await rr(r).catch(()=>null))try{if(await Vu(r,$),t.compress)try{let u=`${$}.gz`;await this.compressLogFile($,u),await xn($)}catch(u){console.error("Error compressing rotated file:",u)}if(l.length===0&&!f.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await tc(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await rr(r).catch(()=>null))await Vu(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Ln(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await xn(nr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=qu(i),n=gA(t),f=Du();await kA(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}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 r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}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()})),ic(this.currentLogFile))try{let i=xu(this.currentLogFile,"r+");Lu(i),pl(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(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ln(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await xn(nr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,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:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let u=yi.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${r} ${f}`;else if(l==="info"||l==="success")h=`${r} ${n} ${f}`;else h=`${r} ${n} ${x.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,w=$(t).length,e=Math.max(1,u-2-y-w);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);if(this.fancy&&!Q()){let h=Oh[i],y=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",w;switch(i){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:x.gray(c),level:i}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:x.green(c),level:i}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(w),$){let e=$.split(`
73
+ `);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:x.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let u=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
74
+ `;if($)u+=`${$}
75
+ `;u=u.replace(this.ANSI_PATTERN,""),await this.writeToFile(u)}time(i){let t=performance.now();if(this.fancy&&!Q()){let r=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:x.blue("◐"),tag:r,message:`${x.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
76
+ `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!Q()){let y=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:x.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Q())console.error(h.trim());await this.writeToFile(h)}}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}`,r=new sf(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(r),r}createReadStream(){if(Q())throw Error("createReadStream is not supported in browser environments");if(!ic(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return qu(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 r=this.keys.get(this.currentKeyId);try{let n=Et.isBuffer(i)?i:Et.from(i,"base64"),f=n.slice(0,16),l=n.slice(-16),c=n.slice(16,-16),$=dA("aes-256-gcm",r,f);return $.setAuthTag(l),Et.concat([$.update(c),$.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q()}isServerMode(){return!Q()}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,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!Q()){let l=i.split(`
77
+ `),c=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(c)}┐`,u=`└${"─".repeat(c)}┘`,h=l.map((y)=>{let w=" ".repeat(c-y.length-2);return`│ ${y}${w} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan($)})),h.forEach((y)=>console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(y),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(u),showTimestamp:!1}))}else if(!Q())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
78
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();yi.stdin.removeListener("data",r);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",r)})}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 r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(r=i.replace(c,(u,h)=>{if(h==="%")return"%";if($>=t.length)return u;let y=t[$++];switch(h){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 u}}),$<t.length)r+=` ${t.slice($).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}if(this.fancy&&!Q()){let c=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$=x.blue("◐");console.error(`${$} ${c} ${x.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
79
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(l)}progress(i,t=""){if(!this.enabled||!this.fancy||Q()||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 r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,$)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,c)),$!==void 0)this.activeProgressBar.message=$;let u=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,u)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,$="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;yi.stdout.write(`${"\r".padEnd(yi.stdout.columns||80)}\r`),this.log($,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||Q()||!yi.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=x.green("━".repeat(n)),c=x.gray("━".repeat(f)),$=`[${l}${c}]`,u=`${r}%`.padStart(4),h=i.message?` ${i.message}`:"",y=t||r===100?x.green("✓"):x.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",e=`\r${y}${w} ${$} ${u}${h}`,A=yi.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,yi.stdout.write(i.lastRenderedLine),t)yi.stdout.write(`
80
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||Q()||!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(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ln(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=nr(this.config.logDirectory,n);if(i.before)try{if((await rr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await xn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function nf(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&q(t[0])&&"id"in t[0]&&t[0].id===3&&q(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(q(t)&&q(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(q(i)&&"arr"in i&&Array.isArray(i.arr)&&q(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&q(t[0])&&q(i[0])){let n=[...t];for(let f of i)if(q(f)&&"name"in f){if(!n.find((c)=>q(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(q(f)&&"path"in f){if(!n.find((c)=>q(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((l)=>af(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!q(t)||!q(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(q(f)&&q(r[n]))r[n]=nf(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&q(f[0])&&q(r[n][0])){let l=[...f];for(let c of r[n])if(q(c)&&"name"in c){if(!l.find((u)=>q(u)&&("name"in u)&&u.name===c.name))l.push(c)}else if(q(c)&&"path"in c){if(!l.find((u)=>q(u)&&("path"in u)&&u.path===c.path))l.push(c)}else if(!l.some(($)=>af($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Ic(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:nf(i,t);if(Array.isArray(i))return r==="replace"?t:nf(i,t);if(!q(t)||!q(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=n[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(r==="replace")n[f]=l;else n[f]=nf(c,l);else if(q(l)&&q(c))n[f]=Ic(c,l,r);else n[f]=l}return n}function af(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!af(i[r],t[r]))return!1;return!0}if(q(i)&&q(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!af(i[f],t[f]))return!1}return!0}return!1}function q(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Zn(i,t,r="replace"){if(!Uh(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Ic(t,f,r)}catch{return null}}catch{return null}}function Ws(i,t,r=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,$=[]){let u={...c};for(let[h,y]of Object.entries(c)){let w=[...$,h],e=(s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${n}_${w.map(e).join("_")}`,m=`${n}_${w.map((s)=>s.toUpperCase()).join("_")}`;if(r)ei.info(`Checking environment variable ${A} for config ${i}.${w.join(".")}`);if(typeof y==="object"&&y!==null&&!Array.isArray(y))u[h]=l(y,w);else{let s=_r.env[A]||_r.env[m];if(s!==void 0){if(r)ei.info(`Using environment variable ${s?A:m} for config ${i}.${w.join(".")}`);if(typeof y==="number")u[h]=Number(s);else if(typeof y==="boolean")u[h]=s.toLowerCase()==="true";else if(Array.isArray(y))try{let E=JSON.parse(s);if(Array.isArray(E))u[h]=E;else u[h]=s.split(",").map((T)=>T.trim())}catch{u[h]=s.split(",").map((E)=>E.trim())}else u[h]=s}}}return u}return l(f)}async function Xs({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:$="replace"}){let u=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?Ws(i,f,l):f,h=r||_r.cwd(),y=[".ts",".js",".mjs",".cjs",".json"];if(l)ei.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${h}`);let w=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],s=Array.from(new Set([h,Ei(h,"config"),Ei(h,".config"),n?Ei(h,n):void 0].filter(Boolean)));for(let E of s){if(l)ei.info(`Searching for configuration in: ${E}`);let B=[Ei(h,"config"),Ei(h,".config")].concat(n?[Ei(h,n)]:[]).includes(E)?[...w,...e,...A,...m]:[...e,...w,...m,...A];for(let F of B)for(let N of y){let R=Ei(E,`${F}${N}`),W=await Zn(R,u,$);if(W!==null){if(l)ei.success(`Configuration loaded from: ${R}`);return W}}}if(i){let E=Ei(vl(),".config",i),T=["config",`${i}.config`];if(t)T.push(`${t}.config`);if(l)ei.info(`Checking user config directory: ${E}`);for(let B of T)for(let F of y){let N=Ei(E,`${B}${F}`),R=await Zn(N,u,$);if(R!==null){if(l)ei.success(`Configuration loaded from user config directory: ${N}`);return R}}}if(i){let E=Ei(vl(),".config"),T=[`.${i}.config`];if(t)T.push(`.${t}.config`);if(l)ei.info(`Checking user config directory for dotfile configs: ${E}`);for(let B of T)for(let F of y){let N=Ei(E,`${B}${F}`),R=await Zn(N,u,$);if(R!==null){if(l)ei.success(`Configuration loaded from user config directory dotfile: ${N}`);return R}}}if(i){let E=vl(),T=[`.${i}.config`,`.${i}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(l)ei.info(`Checking user home directory for dotfile configs: ${E}`);for(let B of T)for(let F of y){let N=Ei(E,`${B}${F}`),R=await Zn(N,u,$);if(R!==null){if(l)ei.success(`Configuration loaded from user home directory: ${N}`);return R}}}try{let E=Ei(h,"package.json");if(Uh(E)){let T=await import(E),B=T[i];if(!B&&t){if(B=T[t],B&&l)ei.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(l)ei.success(`Configuration loaded from package.json: ${B===T[i]?i:t}`);return Ic(u,B,$)}catch(F){if(l)ei.warn("Failed to merge package.json config:",F)}}}catch(E){if(l)ei.warn("Failed to load package.json:",E)}if(l)ei.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return u}function Js(i,t={}){let r=hf.cwd();while(r.includes("storage"))r=du(r,"..");let n=du(r,i||"");if(t?.relative)return OA(hf.cwd(),n);return n}async function _s(){try{let i=await Xs({name:"clarity",alias:"logging",defaultConfig:cf,cwd:hf.cwd()});return{...cf,...i||{}}}catch{return cf}}function ti(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Is(){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 i=ct.type;if(i==="renderer"||i==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class Fh{async format(i){let t=await Is(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$r.pid,hostname:t(),environment:$r.env.NODE_ENV||"development",platform:$r.platform,version:$r.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$r.env.NODE_ENV||$r.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mf{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(i,t={}){this.name=i,this.config={...Bc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fh,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??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...$f,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...$f};return{...$f,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Bc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await QA(this.config.logDirectory,Pu.F_OK|Pu.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await PA(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let u=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:rt.from(i);try{if(!kn(this.currentLogFile))await fc(this.currentLogFile,"",{mode:420});if(f=Qu(this.currentLogFile,"a",420),oA(f,u,{flag:"a"}),ou(f),f!==void 0)nc(f),f=void 0;if((await lr(this.currentLogFile)).size===0){if(await fc(this.currentLogFile,u,{flag:"w",mode:420}),(await lr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let y=h;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(l<c-1){let w=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,w);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(f!==void 0)try{nc(f)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(u){if(l===c-1){let y=u,w=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),u}l++;let h=$*2**(l-1);await new Promise((y)=>setTimeout(y,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 cr(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 cr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return cr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,u])=>u.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return rc(16).toString("hex")}generateKey(){return rc(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(),r=rc(16),n=VA("aes-256-gcm",t,r),f=rt.isBuffer(i)?i:rt.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,u=n.getAuthTag(),h=rt.allocUnsafe(16+$+16);return r.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),u.copy(h,16+$),{encrypted:h,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Zu(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(rt.from(rt.concat(f)))),n.on("error",r),n.write(i),n.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(ti())return;if(!this.shouldWriteToFile())return;let i=await lr(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Vn(this.config.logDirectory),l=f.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,h)=>{let y=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await lr(r).catch(()=>null))try{if(await vu(r,$),t.compress)try{let u=`${$}.gz`;await this.compressLogFile($,u),await Dn($)}catch(u){console.error("Error compressing rotated file:",u)}if(l.length===0&&!f.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await fc(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await lr(r).catch(()=>null))await vu(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Vn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await Dn(cr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=bu(i),n=bA(t),f=Zu();await pA(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),kn(this.currentLogFile))try{let i=Qu(this.currentLogFile,"r+");ou(i),nc(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(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Vn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dn(cr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,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.shouldStyleConsole()?z.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let u=_.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${r} ${f}`;else if(l==="info"||l==="success")h=`${r} ${n} ${f}`;else h=`${r} ${n} ${z.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,w=$(t).length,e=Math.max(1,u-2-y-w);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=z.underline(z.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,u="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>z.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>z.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>z.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>z.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>z.strikethrough(n)),t}supportsHyperlinks(){if(ti())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(vA(t)||t.startsWith("./")||t.startsWith("../"))t=ZA(t);else return null;return kn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:u,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":Mh[i],e=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:z.gray(u),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:z.green(u),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.error(A),$){let m=$.split(`
81
+ `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:z.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
82
+ `;if($)y+=`${$}
83
+ `;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let r={update:($,u)=>{},finish:($)=>{},interrupt:($,u)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:($,u)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,$),this.activeProgressBar.total),u!==void 0)this.activeProgressBar.message=u;if(this.shouldStyleConsole()&&!ti()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:($)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,$)},interrupt:($,u="info")=>{if(!ti()&&_.stdout.isTTY)_.stdout.write(`
84
+ `);if(this[u==="warning"?"warn":u]($),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":z.blue("◐"),tag:r,message:`${z.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
85
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":z.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ti())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}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}`,r=new mf(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(r),r}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!kn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bu(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 r=this.keys.get(this.currentKeyId);try{let n=rt.isBuffer(i)?i:rt.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=DA("aes-256-gcm",r,f);$.setAuthTag(l);let u=$.update(c),h=$.final(),y=u.length+h.length,w=rt.allocUnsafe(y);return u.copy(w,0),h.copy(w,u.length),w.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ti()}isServerMode(){return!ti()}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,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
86
+ `),u=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(u)}┐`,y=`└${"─".repeat(u)}┘`,w=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:z.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(h),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(y),showTimestamp:!1}))}else if(!ti())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
87
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${z.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}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 r=i;if(t&&t.length>0){let u=/%([sdijfo%])/g,h=0;if(r=i.replace(u,(y,w)=>{if(w==="%")return"%";if(h>=t.length)return y;let e=t[h++];switch(w){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return y}}),h<t.length)r+=` ${t.slice(h).map((y)=>typeof y==="object"?JSON.stringify(y,null,2):String(y)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${h}${u} ${z.cyan(n)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
88
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=z.green("━".repeat(n)),c=z.gray("━".repeat(f)),$=`[${l}${c}]`,u=`${r}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||r===100?z.green("✓"):z.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",e=`\r${y}${w} ${$} ${u}${h}`,A=_.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
89
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!_.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(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Vn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=cr(this.config.logDirectory,n);if(i.before)try{if((await lr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Dn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Nh(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(u){if(c=u instanceof Error?u:Error(String(u)),$===r||!f(c))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function Wh(i){return i instanceof ji}function Ks(i){return i instanceof Ef}function zs(i){if(Wh(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>i.message.toLowerCase().includes(r.toLowerCase()))}class Rf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:u=!0}=r,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(u)return zr.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,n.useCamelCase)),u=`${r}_${$.join("_")}`,h=n.useBackwardCompatibility?`${r}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let y=bn.env[u]||(h?bn.env[h]:void 0);if(y!==void 0){if(n.verbose){let w=bn.env[u]?u:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,u,n.customParsers,n.configName)}catch(w){if(w instanceof Tf)throw w;throw Tt.envVar(u,y,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Tt.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(bn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((u)=>this.formatEnvKey(u,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
90
+
91
+ `;for(let n of i)r+=`${n.key}
92
+ `,r+=` Type: ${n.type}
93
+ `,r+=` Description: ${n.description}
94
+ `,r+=` Example: ${n.example}
95
+
96
+ `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
97
+
98
+ `;r+=`| Variable | Type | Description | Example |
99
+ `,r+=`|----------|------|-------------|----------|
100
+ `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
101
+ `;return r}}function Os(i,t){let r=Kh("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function Xh(i,t,r={}){return Jh(i,t,r,new WeakMap)}function Jh(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return _h(i,t,f,n);if(!_i(t)||!_i(i))return t;return ds(i,t,r,n)}function _h(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return Ms(i,t);case"smart":return Gs(i,t,n);default:return t}return t}function Ms(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Tc(f,n)))r.push(n);return r}function Gs(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return Hs(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function Hs(i,t,r){let n=[...t];for(let f of i){if(!_i(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((h)=>_i(h)&&($ in h)&&h[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function ds(i,t,r,n){let f=t;if(_i(f)&&n.has(f))return n.get(f);let l={...i};if(_i(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],u=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(_i($)&&_i(u))l[c]=Jh(u,$,r,n);else if(Array.isArray($)||Array.isArray(u))l[c]=_h(u,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function Kc(i,t,r="replace"){return Xh(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Tc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Tc(i[r],t[r]))return!1;return!0}if(_i(i)&&_i(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Tc(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Sf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let h=wr.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let u=async()=>{if(!on(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),w=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new Ir(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Ir(i,Error("Configuration must export a valid object"),"unknown");let E={config:Kc(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)wr.setWithFileCheck("file",E,i,l);return E}catch(h){throw h instanceof Error?Tt.configLoad(i,h):Tt.configLoad(i,Error(String(h)))}};if(c)return zr.track("loadFromPath",u,{path:i});return u()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(lc(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return Nh(async()=>{return on(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!on(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=lc(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=lc(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){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((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!on(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class zc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:u=!1}=r,h=async()=>{let y=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:w}}};if($)return await zr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,r){try{if(!is(t))throw new Kr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Kr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,u]of Object.entries(t.properties))if($ in c){let h=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],u,h,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(c))if(!$.has(u))f.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.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:Hh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Oc{fileLoader=new Sf;envProcessor=new Rf;validator=new zc;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let u=this.checkCache(c.name||"",c);if(u)return u}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(u){let h=c.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(h)throw u;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let y=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),w=!y&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),e=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw u;if(w&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)di.warn(`Slow configuration loading detected: ${u.duration}ms for ${c.name}`);$.metrics=u}return $}catch($){let u=Date.now()-t;throw di.error(`Configuration loading failed after ${u}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:u=!0,arrayStrategy:h="replace",verbose:y=!1}=i,w=l||Jt.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,$,h,y,u,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,u,n,y);let m=await this.loadHomeConfiguration(n,f,$,h,y,u);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,u,n,y);let s=await this.loadPackageJsonConfiguration(n,f,w,$,h,y,u);if(s)return e.push(Ti(w,"package.json")),this.finalizeResult(s,e,u,n,y);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw Tt.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,u,y),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,u){let h=$?Jr(i,f,c):f,y=this.getLocalDirectories(r,n);for(let w of y){if(c)di.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(A){if(c)di.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?Jr(i,r,f):r,$=[Ti(tr(),".config",i),Ti(tr(),".config"),tr()];for(let u of $){if(f)di.info(`Checking home directory: ${u}`);let h=this.fileLoader.generateConfigPaths(i,u,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:n,verbose:f});if(y){if(f)di.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?Jr(i,n,l):n;try{let u=Ti(r,"package.json");if(!mc(u))return null;let h=await import(u),y=h[i],w=i;if(!y&&t)y=h[t],w=t;if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)di.success(`Configuration loaded from package.json: ${w}`);return{config:Kc($,y,f),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(l)di.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Jr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Tt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return wr.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);wr.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ti(i,"config"),Ti(i,".config"),t?Ti(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ti(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ti(tr(),".config",i),Ti(tr(),".config"),tr()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function $h(i){let r=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return r||n}async function gs(i){return ut.loadConfig({...i,__strictErrorHandling:!0})}async function Ih(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await ut.loadConfig(i);else n=await ut.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",l=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)di.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let $=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ut.applyEnvironmentVariables($.name||"",t,!0,$.verbose||!1))?.config??t;return t}}async function qs(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ut.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&$h(r)))return(await ut.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await ut.loadConfig({...i,cwd:i.cwd||Jt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&$h(t)))return(await ut.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function Ls(i,t,r="replace"){let n=new Sf;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Jr(i,t,r=!1){let n=new Rf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let u={...c};for(let[h,y]of Object.entries(c)){let w=[...$,h],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=Jt.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof y==="boolean")u[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let s=Number(A);if(!Number.isNaN(s))u[h]=s}else if(Array.isArray(y))try{u[h]=JSON.parse(A)}catch{u[h]=A.split(",").map((s)=>s.trim())}else u[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))u[h]=l(y,w)}return u}return l(t)}function xs(i){let t=Ti(Jt.cwd(),i.configDir),r=Ti(Jt.cwd(),i.generatedDir),n=Ti(r,"config-types.ts");if(!mc(Hu(n)))_A(Hu(n),{recursive:!0,mode:511});let f=mc(t)?IA(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${Ta}
102
+ export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
103
+ `;KA(n,l,{mode:438})}function ks(i){let t=null,r=null,n=()=>{if(!r)r=Ih(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)di.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(l,c){if(t)return t[c];let $=f[c];return n(),$},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,$){if(!t)t={...f};return t[c]=$,!0}})}function Vs(i){let t=pu(ns.cwd(),i?.configDir||"./config");function r(){if(!ts(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=rs(t).filter((u)=>f.has(cc(u))).map((u)=>({base:u.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:u})),$=new Map;for(let{base:u,file:h}of c){let y=cc(h).toLowerCase(),w=$.get(u);if(!w){$.set(u,h);continue}let e=cc(w).toLowerCase();if(l.indexOf(y)<l.indexOf(e))$.set(u,h)}return Array.from($.entries()).map(([u,h])=>({base:u,file:h})).sort((u,h)=>u.base.localeCompare(h.base))}function n(){let f=r(),l=f.map((h)=>h.base),c=l.length?l.map((h)=>`'${h}'`).join(" | "):"string",$=f.length?`{
104
+ ${f.map((h)=>{let y=pu(t,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${y}').default`}).join(`,
105
+ `)}
106
+ }`:"Record<string, any>";return`export type ConfigNames = ${c}
107
+ export type ConfigByName = ${$}
108
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
109
+ export type ConfigOf = Config
110
+ `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var Kh,wr,zr,zh,Ds,bs,uh,ff,Yc,wi,x,os,hh,Qs,yh,Ps,vs,yc,Zs,wh,eh,wc,ps,ia,ta,ra,lf,Oh,na,ei,fa,la,Ah,cf,Bc,ri,z,ca,sh,$a,ah,ua,ha,ec,ya,mh,Eh,wa,Ac,ea,Aa,sa,aa,ma,$f,Mh,Ea,Ta="0.15.6",ji,Ef,Ir,Cc,Uc,Tf,Rc,Sc,Kr,jc,Fc,Tt,Gh,Hh,di,ut,dh,gh,Ya=Ys(async()=>{Kh=import.meta.require,wr=new Xc,zr=new Jc,zh={createKey:Bs,isEquivalent:Cs,estimateMemoryUsage:Us},Ds=wf(Ec.cwd(),"config"),bs=wf(Ec.cwd(),"src/generated"),uh=yf.env.CLARITY_LOG_DIR||MA(js(),"logs"),ff={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Yc=await Fs(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=wi,os=wi.red,hh=wi.green,Qs=wi.yellow,yh=wi.blue,Ps=wi.magenta,vs=wi.cyan,yc=wi.white,Zs=wi.gray,wh=wi.bgRed,eh=wi.bgYellow,wc=wi.bold,ps=wi.dim,ia=wi.italic,ta=wi.underline,ra=wi.reset,lf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Oh={debug:"\uD83D\uDD0D",info:yh("ℹ"),success:hh("✓"),warning:eh(yc(wc(" WARN "))),error:wh(yc(wc(" ERROR ")))},na=new sf("stacks"),ei=new sf("bunfig",{showTags:!0}),fa=Ei(_r.cwd(),"config"),la=Ei(_r.cwd(),"src/generated"),Ah=hf.env.CLARITY_LOG_DIR||zA(Js(),"logs"),cf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ah,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bc=await _s(),ri={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},z=ri,ca=ri.red,sh=ri.green,$a=ri.yellow,ah=ri.blue,ua=ri.magenta,ha=ri.cyan,ec=ri.white,ya=ri.gray,mh=ri.bgRed,Eh=ri.bgYellow,wa=ri.bgGray,Ac=ri.bold,ea=ri.dim,Aa=ri.italic,sa=ri.underline,aa=ri.strikethrough,ma=ri.reset,$f={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Mh={debug:"\uD83D\uDD0D",info:ah("ℹ"),success:sh("✓"),warning:Eh(ec(Ac(" WARN "))),error:mh(ec(Ac(" ERROR ")))},Ea=new mf("stacks"),ji=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Ef=class extends ji{code="CONFIG_NOT_FOUND";constructor(t,r,n){let f=n?` or alias "${n}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Ir=class extends ji{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Cc=class extends ji{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Uc=class extends ji{code="CONFIG_MERGE_ERROR";constructor(t,r,n,f){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:f,originalError:n.name,originalMessage:n.message});this.cause=n}},Tf=class extends ji{code="ENV_VAR_ERROR";constructor(t,r,n,f){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:f})}},Rc=class extends ji{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Sc=class extends ji{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Kr=class extends ji{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},jc=class extends ji{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,f){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:f})}},Fc=class extends ji{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Tt={configNotFound(i,t,r){return new Ef(i,t,r)},configLoad(i,t,r){return new Ir(i,t,r)},configValidation(i,t,r){return new Cc(i,t,r)},configMerge(i,t,r,n){return new Uc(i,t,r,n)},envVar(i,t,r,n){return new Tf(i,t,r,n)},fileSystem(i,t,r){return new Rc(i,t,r)},typeGeneration(i,t,r){return new Sc(i,t,r)},schemaValidation(i,t,r){return new Kr(i,t,r)},browserConfig(i,t,r,n){return new jc(i,t,r,n)},plugin(i,t,r){return new Fc(i,t,r)}},Gh={replace:"replace",concat:"concat",smart:"smart"},Hh=/^https?:\/\//,di=new mf("bunfig",{showTags:!0}),ut=new Oc,dh=Ti(Jt.cwd(),"config"),gh=Ti(Jt.cwd(),"src/generated")});function Ba(i,t={}){let r=ef.cwd();while(r.includes("storage"))r=ih(r,"..");let n=ih(r,i||"");if(t?.relative)return ls(ef.cwd(),n);return n}var Ca=ef.env.CLARITY_LOG_DIR||fs(Ba(),"logs"),qh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ca,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Yf={...qh},gC=(async()=>{try{let{loadConfig:i}=await Ya().then(()=>Sh),t=await i({name:"clarity",alias:"logging",defaultConfig:qh,cwd:ef.cwd()});if(t)Object.assign(Yf,t)}catch{}return Yf})();function ni(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ua(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class Lh{async format(i){let t=await Ua(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:yr.pid,hostname:t(),environment:yr.env.NODE_ENV||"development",platform:yr.platform,version:yr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:yr.env.NODE_ENV||yr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},M=ci,qC=ci.red,Ra=ci.green,LC=ci.yellow,Sa=ci.blue,xC=ci.magenta,kC=ci.cyan,Th=ci.white,VC=ci.gray,ja=ci.bgRed,Fa=ci.bgYellow,DC=ci.bgGray,Yh=ci.bold,bC=ci.dim,oC=ci.italic,QC=ci.underline,PC=ci.strikethrough,vC=ci.reset,sc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Na={debug:"\uD83D\uDD0D",info:Sa("ℹ"),success:Ra("✓"),warning:Fa(Th(Yh(" WARN "))),error:ja(Th(Yh(" ERROR ")))};class jf{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(i,t={}){this.name=i,this.config={...Yf},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Lh,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??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...sc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...sc};return{...sc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Yf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await ys(this.config.logDirectory,fh.F_OK|fh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await ws(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let u=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:nt.from(i);try{if(!Qn(this.currentLogFile))await hc(this.currentLogFile,"",{mode:420});if(f=nh(this.currentLogFile,"a",420),hs(f,u,{flag:"a"}),rh(f),f!==void 0)uc(f),f=void 0;if((await ur(this.currentLogFile)).size===0){if(await hc(this.currentLogFile,u,{flag:"w",mode:420}),(await ur(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let y=h;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(l<c-1){let w=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,w);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(f!==void 0)try{uc(f)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(u){if(l===c-1){let y=u,w=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),u}l++;let h=$*2**(l-1);await new Promise((y)=>setTimeout(y,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 hr(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 hr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return hr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,u])=>u.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return $c(16).toString("hex")}generateKey(){return $c(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(),r=$c(16),n=cs("aes-256-gcm",t,r),f=nt.isBuffer(i)?i:nt.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,u=n.getAuthTag(),h=nt.allocUnsafe(16+$+16);return r.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),u.copy(h,16+$),{encrypted:h,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=ch(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(nt.from(nt.concat(f)))),n.on("error",r),n.write(i),n.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(ni())return;if(!this.shouldWriteToFile())return;let i=await ur(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Pn(this.config.logDirectory),l=f.filter((u)=>u.startsWith(this.name)&&/\.log\.\d+$/.test(u)).sort((u,h)=>{let y=Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await ur(r).catch(()=>null))try{if(await lh(r,$),t.compress)try{let u=`${$}.gz`;await this.compressLogFile($,u),await vn($)}catch(u){console.error("Error compressing rotated file:",u)}if(l.length===0&&!f.some((u)=>u.endsWith(".log.1")))try{let u=`${r}.1`;await hc(u,"")}catch(u){console.error("Error creating backup file:",u)}}catch(u){console.error(`Error during rotation: ${u instanceof Error?u.message:String(u)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await ur(r).catch(()=>null))await lh(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Pn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await vn(hr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=th(i),n=us(t),f=ch();await ss(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),Qn(this.currentLogFile))try{let i=nh(this.currentLogFile,"r+");rh(i),uc(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(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Pn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await vn(hr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,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.shouldStyleConsole()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof I.env.NO_COLOR<"u",t=I.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let u=I.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${r} ${f}`;else if(l==="info"||l==="success")h=`${r} ${n} ${f}`;else h=`${r} ${n} ${M.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,w=$(t).length,e=Math.max(1,u-2-y-w);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=M.underline(M.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,u="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>M.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>M.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>M.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>M.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>M.strikethrough(n)),t}supportsHyperlinks(){if(ni())return!1;let i=I.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=I.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(es(t)||t.startsWith("./")||t.startsWith("../"))t=As(t);else return null;return Qn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:u,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":Na[i],e=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:M.gray(u),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:M.green(u),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:u,level:i}),console.error(A),$){let m=$.split(`
111
+ `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:M.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
112
+ `;if($)y+=`${$}
113
+ `;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let r={update:($,u)=>{},finish:($)=>{},interrupt:($,u)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:($,u)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,$),this.activeProgressBar.total),u!==void 0)this.activeProgressBar.message=u;if(this.shouldStyleConsole()&&!ni()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:($)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,$)},interrupt:($,u="info")=>{if(!ni()&&I.stdout.isTTY)I.stdout.write(`
114
+ `);if(this[u==="warning"?"warn":u]($),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:r,message:`${M.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
115
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":M.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ni())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}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}`,r=new jf(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(r),r}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!Qn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return th(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 r=this.keys.get(this.currentKeyId);try{let n=nt.isBuffer(i)?i:nt.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=$s("aes-256-gcm",r,f);$.setAuthTag(l);let u=$.update(c),h=$.final(),y=u.length+h.length,w=nt.allocUnsafe(y);return u.copy(w,0),h.copy(w,u.length),w.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ni()}isServerMode(){return!ni()}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,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
116
+ `),u=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(u)}┐`,y=`└${"─".repeat(u)}┘`,w=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:M.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(h),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(y),showTimestamp:!1}))}else if(!ni())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
117
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${M.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();I.stdin.removeListener("data",r);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}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 r=i;if(t&&t.length>0){let u=/%([sdijfo%])/g,h=0;if(r=i.replace(u,(y,w)=>{if(w==="%")return"%";if(h>=t.length)return y;let e=t[h++];switch(w){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return y}}),h<t.length)r+=` ${t.slice(h).map((y)=>typeof y==="object"?JSON.stringify(y,null,2):String(y)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${h}${u} ${M.cyan(n)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
118
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=M.green("━".repeat(n)),c=M.gray("━".repeat(f)),$=`[${l}${c}]`,u=`${r}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||r===100?M.green("✓"):M.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",e=`\r${y}${w} ${$} ${u}${h}`,A=I.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,I.stdout.write(i.lastRenderedLine),t)I.stdout.write(`
119
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!I.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(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Pn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=hr(this.config.logDirectory,n);if(i.before)try{if((await ur(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await vn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var ZC=new jf("stacks");class gi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class xh extends gi{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class Bf extends gi{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class kh extends gi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Vh extends gi{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Mc extends gi{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class Dh extends gi{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class bh extends gi{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Cf extends gi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class oh extends gi{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class Qh extends gi{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var er={configNotFound(i,t,r){return new xh(i,t,r)},configLoad(i,t,r){return new Bf(i,t,r)},configValidation(i,t,r){return new kh(i,t,r)},configMerge(i,t,r,n){return new Vh(i,t,r,n)},envVar(i,t,r,n){return new Mc(i,t,r,n)},fileSystem(i,t,r){return new Dh(i,t,r)},typeGeneration(i,t,r){return new bh(i,t,r)},schemaValidation(i,t,r){return new Cf(i,t,r)},browserConfig(i,t,r,n){return new oh(i,t,r,n)},plugin(i,t,r){return new Qh(i,t,r)}};async function Wa(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(u){if(c=u instanceof Error?u:Error(String(u)),$===r||!f(c))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class Gc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:u=!0}=r,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(u)return Wc.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,n.useCamelCase)),u=`${r}_${$.join("_")}`,h=n.useBackwardCompatibility?`${r}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let y=pn.env[u]||(h?pn.env[h]:void 0);if(y!==void 0){if(n.verbose){let w=pn.env[u]?u:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,u,n.customParsers,n.configName)}catch(w){if(w instanceof Mc)throw w;throw er.envVar(u,y,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw er.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(pn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((u)=>this.formatEnvKey(u,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
120
+
121
+ `;for(let n of i)r+=`${n.key}
122
+ `,r+=` Type: ${n.type}
123
+ `,r+=` Description: ${n.description}
124
+ `,r+=` Example: ${n.example}
125
+
126
+ `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
127
+
128
+ `;r+=`| Variable | Type | Description | Example |
129
+ `,r+=`|----------|------|-------------|----------|
130
+ `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
131
+ `;return r}}function Xa(i,t,r={}){return Ph(i,t,r,new WeakMap)}function Ph(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return vh(i,t,f,n);if(!Ii(t)||!Ii(i))return t;return Ka(i,t,r,n)}function vh(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return Ja(i,t);case"smart":return _a(i,t,n);default:return t}return t}function Ja(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Nc(f,n)))r.push(n);return r}function _a(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return Ia(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function Ia(i,t,r){let n=[...t];for(let f of i){if(!Ii(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((h)=>Ii(h)&&($ in h)&&h[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function Ka(i,t,r,n){let f=t;if(Ii(f)&&n.has(f))return n.get(f);let l={...i};if(Ii(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],u=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Ii($)&&Ii(u))l[c]=Ph(u,$,r,n);else if(Array.isArray($)||Array.isArray(u))l[c]=vh(u,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function Zh(i,t,r="replace"){return Xa(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Nc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Nc(i[r],t[r]))return!1;return!0}if(Ii(i)&&Ii(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Nc(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class ph{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let h=uf.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let u=async()=>{if(!tf(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),w=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new Bf(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Bf(i,Error("Configuration must export a valid object"),"unknown");let E={config:Zh(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)uf.setWithFileCheck("file",E,i,l);return E}catch(h){throw h instanceof Error?er.configLoad(i,h):er.configLoad(i,Error(String(h)))}};if(c)return Wc.track("loadFromPath",u,{path:i});return u()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(ac(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of n){if(!l)continue;if(r.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)r.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return r.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return Wa(async()=>{return tf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!tf(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=ac(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=ac(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){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((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!tf(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var Oa=/^https?:\/\//;class iy{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:u=!1}=r,h=async()=>{let y=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:u};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:w}}};if($)return await Wc.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,r){try{if(!za(t))throw new Cf(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Cf(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,u]of Object.entries(t.properties))if($ in c){let h=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],u,h,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let u of Object.keys(c))if(!$.has(u))f.push({path:r?`${r}.${u}`:u,message:`Additional property '${u}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.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:Oa},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ft=new jf("bunfig",{showTags:!0});function Ma(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class ty{fileLoader=new ph;envProcessor=new Gc;validator=new iy;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let u=this.checkCache(c.name||"",c);if(u)return u}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(u){let h=c.__strictErrorHandling;if(u instanceof Error&&u.name==="ConfigNotFoundError"){if(h)throw u;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(u instanceof Error&&u.name==="ConfigLoadError"){let y=u.message.includes("EACCES")||u.message.includes("EPERM")||u.message.includes("permission denied"),w=!y&&(u.message.includes("syntax")||u.message.includes("Expected")||u.message.includes("Unexpected")||u.message.includes("BuildMessage")||u.message.includes("errors building")),e=u.message.includes("Configuration must export a valid object")||u.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw u;if(w&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${u.message}`]};else throw u}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${u instanceof Error?u.message:String(u)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let u={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(u);if(n.slowThreshold&&u.duration>n.slowThreshold)ft.warn(`Slow configuration loading detected: ${u.duration}ms for ${c.name}`);$.metrics=u}return $}catch($){if($ instanceof Error&&$.name==="ConfigNotFoundError")throw $;let u=Date.now()-t;throw ft.error(`Configuration loading failed after ${u}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:u=!0,arrayStrategy:h="replace",verbose:y=!1}=i,w=l||Uf.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,$,h,y,u,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,u,n,y);let m=await this.loadHomeConfiguration(n,f,$,h,y,u);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,u,n,y);let s=await this.loadPackageJsonConfiguration(n,f,w,$,h,y,u);if(s)return e.push(Ji(w,"package.json")),this.finalizeResult(s,e,u,n,y);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw er.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,u,y),warnings:[`No configuration file found for "${n}"${Ma(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,u){let h=$?rf(i,f,c):f,y=this.getLocalDirectories(r,n);for(let w of y){if(c)ft.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:u?.ttl,useCache:!u?.ttl||u.ttl>100});if(A){if(c)ft.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?rf(i,r,f):r,$=[Ji(ir(),".config",i),Ji(ir(),".config"),ir()];for(let u of $){if(f)ft.info(`Checking home directory: ${u}`);let h=this.fileLoader.generateConfigPaths(i,u,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:n,verbose:f});if(y){if(f)ft.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?rf(i,n,l):n;try{let u=Ji(r,"package.json");if(!XA(u))return null;let h={};try{h=JSON.parse(JA(u,"utf8"))}catch(e){if(l)ft.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let y=h[i],w=i;if(!y&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(h[A]){y=h[A],w=A;break}}}if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)ft.success(`Configuration loaded from package.json: ${w}`);return{config:Zh($,y,f),source:{type:"package.json",path:u,priority:30,timestamp:new Date}}}}catch(u){if(l)ft.warn("Failed to load package.json:",[u instanceof Error?u:Error(String(u))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:rf(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw er.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return uf.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);uf.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ji(ir(),".config",i),Ji(ir(),".config"),ir()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var nU=new ty;function rf(i,t,r=!1){let n=new Gc,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let u={...c};for(let[h,y]of Object.entries(c)){let w=[...$,h],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=Uf.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof y==="boolean")u[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let s=Number(A);if(!Number.isNaN(s))u[h]=s}else if(Array.isArray(y))try{u[h]=JSON.parse(A)}catch{u[h]=A.split(",").map((s)=>s.trim())}else u[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))u[h]=l(y,w)}return u}return l(t)}var fU=Ji(Uf.cwd(),"config"),lU=Ji(Uf.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Ga={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:dc(Hc(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:dc(Hc(),".stacks","ssl","stacks.localhost.crt"),keyPath:dc(Hc(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var ry=Ga;import{execSync as Mr}from"node:child_process";import{homedir as qa}from"node:os";import{join as La}from"node:path";function Ha(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function _t(i){try{return qn(i)}catch{return null}}function gc(i){try{return bl(i)||null}catch{return null}}function qc(i,t){try{return t.every((r)=>Ql(i,r))}catch{return!1}}function da(i,t,r=443){return ol(i,t,r)}function ga(i){let t=[];for(let r of i.split(`
132
+ `)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)t.push(n[1].toUpperCase())}return t}var Yt="-d -r trustRoot -p ssl -p basic",It="/Library/Keychains/System.keychain",Lc="rpx.localhost";function Gr(){return La(qa(),"Library/Keychains/login.keychain-db")}function xc(){return[It,Gr()]}function ny(i,t=Lc){let r=Mr(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let f of r.split(`
133
+ `)){let l=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(l)n.push(l[1].toUpperCase())}return n}function Ff(i){if(process.platform!=="darwin")return;let t=_t(i.caPath);if(!t)return;let r=i.commonName??Lc,n=i.keychains??xc();for(let f of n)for(let l of ny(f,r)){if(l===t)continue;try{if(f.startsWith("/Library"))Or(`security delete-certificate -Z ${l} "${f}"`);else Mr(`security delete-certificate -Z ${l} "${f}"`,{stdio:"ignore"});a("ssl",`Removed stale Root CA ${l} from ${f}`,i.verbose)}catch{}}}function Hr(i,t,r){if(process.platform!=="darwin")return dr(i,r);try{let f=Mr(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return a("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,r?.verbose),f}catch{return!1}}function dr(i,t){let r=_t(i);if(!r)return!1;for(let n of xc())try{let f=Mr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let l of f.split(`
134
+ `))if(l.toUpperCase().includes("SHA-256")){if(l.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return a("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}function kc(i,t){if(process.platform!=="darwin")return!1;let r=t.serverName;Ff({caPath:i,commonName:t.commonName,verbose:t.verbose});let n=Gr();try{Mr(`security add-trusted-cert ${Yt} -k "${n}" "${i}"`,{stdio:"ignore"})}catch{}try{Or(`security add-trusted-cert ${Yt} -k ${It} "${i}"`)}catch{return!1}return Hr(i,r,{verbose:t.verbose})||dr(i,{verbose:t.verbose})}var Bt=null,oc=b(Ar(),".stacks","ssl","rpx.localhost.crt");function yy(i,t){return[...new Set(i.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function wy(i,t,r){let n=b(Ar(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:oc,keyPath:b(n,"rpx.localhost.key"),caCertPath:b(n,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:f.map((l)=>({from:"localhost:1",to:l,cleanUrls:!1}))}}var xa="rpx-root-ca.crt",ka="rpx-root-ca.key";function Qc(i){return{caCertPath:b(i,xa),caKeyPath:b(i,ka)}}function IU(i){return{certPath:b(i,"rpx.localhost.crt"),keyPath:b(i,"rpx.localhost.key"),caCertPath:b(i,"rpx.localhost.ca.crt"),rootCA:Qc(i)}}async function Va(i,t){try{let[r,n]=await Promise.all([P.readFile(i.caCertPath,"utf8"),P.readFile(i.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:n}}catch(r){return a("ssl",`No existing Root CA at ${i.caCertPath} (${r.code||r}), will create one`,t),null}}function fy(i){let t=new Set;t.add(i);let r=i.split(".");if(r.length>=2)t.add(`*.${r.slice(1).join(".")}`);return Array.from(t)}function ey(i){let r=bc(i).replace(/\*/g,"wildcard"),n=b(Ar(),".stacks","ssl"),f=n;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:n,{caCertPath:i.https.caCertPath||b(f,`${r}.ca.crt`),certPath:i.https.certPath||b(f,`${r}.crt`),keyPath:i.https.keyPath||b(f,`${r}.key`)};return{caCertPath:b(f,`${r}.ca.crt`),certPath:b(f,`${r}.crt`),keyPath:b(f,`${r}.key`)}}function ly(i){let t=new Set;if(Nf(i))i.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";fy(n).forEach((f)=>t.add(f))});else if($y(i)){let r=i.to||"rpx.localhost";fy(r).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function KU(i){a("ssl","Loading SSL configuration",i.verbose);let t={...ry,...i};if(i.https=Zc(t),!i.https?.keyPath&&!i.https?.certPath)return a("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let r=!i.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${r}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",i.verbose);let r=await P.readFile(i.https?.keyPath,"utf8"),n=await P.readFile(i.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",i.verbose),{key:r,cert:n}}catch(r){return a("ssl",`Failed to read certificates: ${r}`,i.verbose),null}}catch(r){throw a("ssl",`SSL configuration error: ${r}`,i.verbose),r}}async function zU(i,t){if(qi.platform==="darwin")return Da(i,t);if(qi.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)n(!0);else r(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(l)=>{n(!l)})})})}catch{return!1}return!1}async function Da(i,t){if(qi.platform!=="darwin")return!1;let r=t?.serverName??"rpx.localhost",n=t?.verbose??!1;try{if(Hr(i,r,{verbose:n}))return a("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return a("ssl","Trusting Root CA for browsers (login + system keychains)",n),kc(i,{serverName:r,verbose:n})}catch{return!1}}async function Ay(i){if(Bt&&!i.forceRegenerate){a("ssl","Using cached SSL configuration",i.verbose);return}Pc();let t=Nf(i)?i.proxies.map((y)=>y.to):[i.to];a("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let r=Zc(i,i.verbose),n=r.basePath||b(Ar(),".stacks","ssl");await P.mkdir(n,{recursive:!0});let f=Qc(n),l=await Va(f,i.verbose),c=!1;if(!l){if(i.verbose)j.info("Generating Root CA certificate (one-time)...");l=await Vl(r);try{await Promise.all([P.writeFile(f.caCertPath,l.certificate),P.writeFile(f.caKeyPath,l.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,i.verbose)}catch(y){throw a("ssl",`Error saving Root CA files: ${y}`,i.verbose),Error(`Failed to save Root CA files: ${y}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,i.verbose);if(i.verbose)j.info(`Generating host certificate for: ${t.join(", ")}`);let $=await Dl({...r,rootCA:{certificate:l.certificate,privateKey:l.privateKey}});try{await Promise.all([P.writeFile(r.certPath,$.certificate),P.writeFile(r.keyPath,$.privateKey),P.writeFile(r.caCertPath,l.certificate)]),a("ssl","Certificate files saved successfully",i.verbose)}catch(y){throw a("ssl",`Error saving certificate files: ${y}`,i.verbose),Error(`Failed to save certificate files: ${y}`)}if(c?!1:await sy(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)j.success("Root CA is already trusted in system trust store");if(Bt={key:$.privateKey,cert:$.certificate,ca:l.certificate},i.verbose)j.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)j.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(qi.platform==="darwin")try{Ff({caPath:f.caCertPath,verbose:i.verbose});let y=Gr();try{Vc(`security add-trusted-cert ${Yt} -k "${y}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Or(`security add-trusted-cert ${Yt} -k ${It} "${f.caCertPath}"`),i.verbose)j.success("Successfully added Root CA to system trust store");h=!0;let w=b(n,"trust-rpx-cert.sh"),e=`#!/bin/bash
135
+ echo "Trusting RPX Root CA"
136
+ sudo security add-trusted-cert ${Yt} -k ${It} "${f.caCertPath}"
137
+ echo "Root CA trusted! Please restart your browser."
138
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
139
+ `;await P.writeFile(w,e,{mode:493})}catch(y){if(i.verbose)j.warn(`Could not add Root CA to trust store automatically: ${y}`);let w=b(n,"trust-rpx-cert.sh"),e=`#!/bin/bash
140
+ echo "Trusting RPX Root CA"
141
+ sudo security add-trusted-cert ${Yt} -k ${It} "${f.caCertPath}"
142
+ echo "Root CA trusted! Please restart your browser."
143
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
144
+ `;if(await P.writeFile(w,e,{mode:493}),i.verbose)j.info(`Created a trust helper script at: ${w}`),j.info(`If you're still having certificate issues, run: sh ${w}`)}else if(qi.platform==="linux")try{let{exec:y}=await import("node:child_process"),w="/usr/local/share/ca-certificates/rpx",e=`
145
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
146
+ cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
147
+ update-ca-certificates
148
+ echo "RPX Root CA installed. Please restart your browser."
149
+ `,A=b(Dc.tmpdir(),`rpx-trust-${Date.now()}.sh`);await P.writeFile(A,e,{mode:493}),await new Promise((m)=>{y(`sudo bash "${A}"`,(s)=>{if(s){if(i.verbose)j.warn(`Could not trust certificates: ${s}`);m(!1)}else{if(i.verbose)j.success("Successfully added certificates to system trust store");m(!0)}})}),await P.unlink(A).catch(()=>{}),h=!0}catch(y){if(i.verbose)j.warn(`Failed to trust certificates: ${y}`)}else if(qi.platform==="win32")try{let y=`
150
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
151
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
152
+ $store.Open("ReadWrite")
153
+ $store.Add($cert)
154
+ $store.Close()
155
+ Write-Host "Root CA trusted successfully!"
156
+ `,w=b(Dc.tmpdir(),"rpx-trust.ps1");if(await P.writeFile(w,y),Vc(`powershell -ExecutionPolicy Bypass -File "${w}"`),i.verbose)j.success("Successfully added certificate to Windows trust store");h=!0}catch(y){if(i.verbose)j.warn(`Could not trust certificate: ${y}`)}else try{await Pl($,l.certificate,r),h=!0}catch(y){if(i.verbose)j.warn(`Could not add certificate to trust store: ${y}`)}if(Bt={key:$.privateKey,cert:$.certificate,ca:l.certificate},i.verbose)j.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!h&&i.verbose)j.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),j.warn("This will bypass the warning and you should only need to do it once")}function Pc(){Bt=null}async function vc(i){if(!i)return null;if(Bt)return Bt;let t=Zc(i);try{let[r,n,f]=await Promise.all([P.access(t.keyPath).then(()=>!0).catch(()=>!1),P.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?P.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return a("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let l="regenerateUntrustedCerts"in i,c=i.regenerateUntrustedCerts,$=l?c!==!1:!0;a("ssl",`Trust check: hasFlag=${l}, flagValue=${c}, shouldCheckTrust=${$}`,i.verbose);let u=t.basePath||b(Ar(),".stacks","ssl"),h=Qc(u);if(!($?await sy(h.caCertPath,i):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[w,e,A]=await Promise.all([P.readFile(t.keyPath,"utf8"),P.readFile(t.certPath,"utf8"),f&&t.caCertPath?P.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(A&&!A.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(Nf(i))try{let{X509Certificate:m}=await import("node:crypto"),E=new m(e).subjectAltName||"",B=i.proxies.map((F)=>F.to).filter((F)=>!E.includes(`DNS:${F}`));if(B.length>0)return a("ssl",`Certificate missing SANs for: ${B.join(", ")}, will regenerate`,i.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,i.verbose)}return a("ssl","Successfully loaded existing certificates",i.verbose),Bt={key:w,cert:e,ca:A},Bt}catch(r){return a("ssl",`Error checking existing certificates: ${r}`,i.verbose),null}}function Zc(i,t){let r=bc(i);a("ssl",`Primary domain: ${r}`,t);let n=ey(i),f=b(Ar(),".stacks","ssl");if(typeof i.https==="object"){let l=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,c={domain:r,hostCertCN:r,basePath:l,caCertPath:i.https.caCertPath||n.caCertPath,certPath:i.https.certPath||n.certPath,keyPath:i.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||r,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(ly(i)).map(($)=>({type:2,value:$}))};if(cy(i.https.rootCA))c.rootCA=i.https.rootCA;return c}return{domain:r,hostCertCN:r,basePath:f,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(ly(i)).map((l)=>({type:2,value:l}))}}async function OU(i,t){let r=ey({to:i,verbose:t}),n=[r.caCertPath,r.certPath,r.keyPath];a("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((f)=>uy(f,t)))}async function sy(i,t){try{if(a("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),qi.platform==="darwin"){if(t?.serverName)return Hr(i,t.serverName,{verbose:t?.verbose});return dr(i,{verbose:t?.verbose})}else if(qi.platform==="win32")try{let r=gc(i)||"";if(!r)return a("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(Vc(n).toString().includes(r))return a("ssl","Certificate found in trusted root store",t?.verbose),!0;return a("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return a("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(qi.platform==="linux")try{let r=_t(i);if(!r)return a("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of n){let l;try{l=await P.readdir(f)}catch{continue}for(let c of l){let $=_t(hy.join(f,c));if($&&$===r)return a("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return a("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return a("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return a("ssl",`Platform ${qi.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return a("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}import{createHash as my,timingSafeEqual as ay}from"node:crypto";import{readFileSync as ba}from"node:fs";var oa="/.well-known/acme-challenge/";function gr(i,t){let r=Buffer.from(i,"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return ay(r,r),!1;return ay(r,n)}function Qa(i,t){let r=(e)=>my("md5").update(e).digest(),n=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),l=r(Buffer.concat([n,f,n])),c=[n,Buffer.from("$apr1$","utf8"),f];for(let e=n.length;e>0;e-=16)c.push(l.subarray(0,Math.min(e,16)));for(let e=n.length;e>0;e>>=1)c.push(e&1?Buffer.from([0]):n.subarray(0,1));let $=r(Buffer.concat(c));for(let e=0;e<1000;e++){let A=[];if(A.push(e&1?n:$.subarray(0,16)),e%3)A.push(f);if(e%7)A.push(n);A.push(e&1?$.subarray(0,16):n),$=r(Buffer.concat(A))}let u="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",h=(e,A)=>{let m="",s=e;for(let E=0;E<A;E++)m+=u[s&63],s>>=6;return m},y=$,w="";return w+=h(y[0]<<16|y[6]<<8|y[12],4),w+=h(y[1]<<16|y[7]<<8|y[13],4),w+=h(y[2]<<16|y[8]<<8|y[14],4),w+=h(y[3]<<16|y[9]<<8|y[15],4),w+=h(y[4]<<16|y[10]<<8|y[5],4),w+=h(y[11],2),`$apr1$${t}$${w}`}function Pa(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let n=t.split("$")[2]??"";return gr(Qa(i,n),t)}if(t.startsWith("{SHA}")){let r=my("sha1").update(i,"utf8").digest("base64");return gr(`{SHA}${r}`,t)}return gr(i,t)}function va(i){let t=new Map;for(let r of i.split(`
157
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let f=n.indexOf(":");if(f<=0)continue;t.set(n.slice(0,f),n.slice(f+1))}return t}function Ey(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",r=[];if(i.username)r.push({username:i.username,password:i.password??""});for(let l of i.users??[])if(l?.username)r.push({username:l.username,password:l.password??""});let n;if(i.htpasswdFile)try{n=va(ba(i.htpasswdFile,"utf8"))}catch{n=void 0}if(r.length===0&&(!n||n.size===0))return;return{realm:t,verify:(l,c)=>{let $=!1;for(let u of r)if(gr(l,u.username)&&gr(c,u.password))$=!0;if(n){let u=n.get(l);if(u&&Pa(c,u))$=!0}return $}}}function Ty(i,t,r){if(t.startsWith(oa))return;let n=i.headers.get("authorization")??"",f=n.indexOf(" "),l=f===-1?n:n.slice(0,f),c=f===-1?"":n.slice(f+1).trim();if(l.toLowerCase()==="basic"&&c){let u="";try{u=Buffer.from(c,"base64").toString("utf8")}catch{u=""}let h=u.indexOf(":");if(h>=0&&r.verify(u.slice(0,h),u.slice(h+1)))return}let $=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${$}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:Za}=Bun,qr=Symbol("rpx.pool.fallback"),Wf=Symbol("rpx.pool.stale");var pa=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function im(i){return pa.has(i.toUpperCase())}var i0=Symbol("rpx.pool.timeout"),Kt=Symbol("rpx.pool.busy");function tm(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function rm(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function nm(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function fm(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Cy=1048576;function lm(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var pc=30000,cm=16384,Uy=262144,$m=2097152,um=524288,hm=8192,ym=4096,wm=new TextEncoder,Ry=new TextDecoder,em=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class Sy{socket=null;buf=new Uint8Array(cm);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,r=t.write(i);while(r<i.length){if(this.closed)throw Wf;await new Promise((n)=>{this.drainWaiter=n}),r+=t.write(i.subarray(r))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>$m)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=um)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class jy{host;port;maxTotal;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=tm();maxWaiters;checkoutIdleMs=nm();inUse=new Set;constructor(i,t,r){this.host=i;this.port=t;this.maxTotal=r;this.maxWaiters=rm(r)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new Sy;return Za({hostname:this.host,port:this.port,socket:{data:(t,r)=>i.push(r),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let n=fm();if(n>0)r.timeout?.(n);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Kt;let i=await this.waitForSlot();if(i===Kt)throw Kt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,r=(l)=>{if(t)return;t=!0,clearTimeout(f),i(l)},n=(l)=>r(l),f=setTimeout(()=>{let l=this.waiters.indexOf(n);if(l!==-1)this.waiters.splice(l,1);r(Kt)},this.queueWaitMs);f.unref?.(),this.waiters.push(n)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min(pc,this.checkoutIdleMs):pc;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-pc;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=i-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=r)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper)clearInterval(this.sweeper),this.sweeper=null}}var Yy=new Map;function Am(i,t){let r=Yy.get(i);if(!r){let n=i.lastIndexOf(":"),f=n===-1?i:i.slice(0,n),l=n===-1?80:Number(i.slice(n+1));r=new jy(f,l,t),Yy.set(i,r)}return r}function By(i,t,r){for(let n=r+3;n<t;n++)if(i[n]===10&&i[n-1]===13&&i[n-2]===10&&i[n-3]===13)return n-3;return-1}function sm(i,t,r){let n=Ry.decode(i.subarray(t,r)),f=n.indexOf(`\r
158
+ `),l=f===-1?n:n.slice(0,f),c=l.indexOf(" "),$=Number.parseInt(l.slice(c+1,c+5),10),u=l.startsWith("HTTP/1.0"),h=[],y=-1,w=!1,e=u,A=!1,m=!1,s=f===-1?n.length:f+2;while(s<n.length){let E=n.indexOf(`\r
159
+ `,s);if(E===-1)E=n.length;let T=n.slice(s,E);if(s=E+2,T==="")continue;let B=T.indexOf(":");if(B===-1)continue;let F=T.slice(0,B),N=T.slice(B+1).trim(),R=F.charCodeAt(0)|32;if(R===99||R===116||R===107){let W=F.toLowerCase();if(W==="content-length"){let k=/^\d+$/.test(N)?Number(N):Number.NaN;if(!Number.isSafeInteger(k)||y>=0&&y!==k)m=!0;else y=k;continue}if(W==="transfer-encoding"){if(N.toLowerCase().includes("chunked"))w=!0;continue}if(W==="connection"){let k=N.toLowerCase();if(k.includes("close"))e=!0;if(k.includes("keep-alive"))A=!0;continue}if(W==="keep-alive")continue}h.push([F,N])}if(u&&A)e=!1;if(w&&y>=0)y=-1;return{status:$,headerEnd:r,headers:h,contentLength:y,chunked:w,closeConn:e,malformed:m}}function am(i,t){return t||i===204||i===304}async function Fy(i){let{hostPort:t,method:r,path:n,reqHeaders:f,forwardedHost:l,originOverride:c,body:$}=i,u=r==="HEAD";if(f.get("expect")||f.get("upgrade"))throw qr;let h=null;if($){let A=f.get("content-length"),m=A?Number.parseInt(A,10):Number.NaN;if(Number.isNaN(m)||m>Cy)throw qr;if(h=await Um($),h===null)throw qr}let y=Cm(r,n,f,t,l,c,h),w=y;if(h&&h.length)w=new Uint8Array(y.length+h.length),w.set(y),w.set(h,y.length);let e=Am(t,i.maxPerHost??lm());for(let A=0;;A++){if(A>0)await new Promise((s)=>{setTimeout(s,A)});let m;try{m=e.acquireIdleSync()??await e.acquireOrDial()}catch(s){if(s!==Kt&&A<4)continue;throw s}try{let s=m.socket.write(w);if(s<w.length)await m.writeAll(w.subarray(s));return await Em(e,m,u)}catch(s){let E=s===Wf&&A<4&&(m.fresh||im(r));if(e.destroy(m),E)continue;if(s===Wf)throw Error("upstream closed connection");throw s}}}async function mm(i){let t=By(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw i0;if(i.len===i.pos)throw Wf;throw Error("upstream closed mid-header")}if(i.len-i.pos>Uy)throw Error("upstream header block too large");await i.waitForData(i.len),t=By(i.buf,i.len,i.pos)}return t}async function Em(i,t,r){let n;for(;;){let l=await mm(t);if(n=sm(t.buf,t.pos,l),t.pos=l+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=n.headers;if(am(n.status,r))return Ny(i,t,n.closeConn),new Response(null,{status:n.status,headers:f});if(n.chunked)return new Response(Bm(i,t,n.closeConn),{status:n.status,headers:f});if(n.contentLength>=0){if(t.len-t.pos>=n.contentLength){let c=t.pos+n.contentLength,$=t.len>c,u=null;if(n.contentLength>=hm)u=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(ym);else if(n.contentLength>0)u=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,n.closeConn||$)i.destroy(t);else i.release(t);return new Response(u,{status:n.status,headers:f})}return new Response(Tm(i,t,n.contentLength,n.closeConn),{status:n.status,headers:f})}return new Response(Ym(t),{status:n.status,headers:f})}function Ny(i,t,r){if(r||t.pos!==t.len)i.destroy(t);else i.release(t)}function Tm(i,t,r,n){let f=t.len-t.pos,l=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-f,t.queuedBytes=0,t.streamingBody=!0;let c=($)=>{if(t.bodyQueue=null,n||t.len>0)i.destroy(t);else i.release(t);$.close()};return new ReadableStream({start($){if(l)$.enqueue(l);if(t.bodyRemaining===0&&t.bodyQueue.length===0)c($)},async pull($){for(;;){let u=t.bodyQueue;if(u&&u.length>0){let h=u.shift();if(t.queuedBytes-=h.length,t.resumeIfDrained(),$.enqueue(h),t.bodyRemaining===0&&u.length===0)c($);return}if(t.bodyRemaining===0){if(t.bodyQueue)c($);return}if(t.closed){t.bodyQueue=null,i.destroy(t),$.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function Ym(i){return i.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(i.len>i.pos){t.enqueue(i.buf.slice(i.pos,i.len)),i.pos=i.len,i.resumeIfDrained();return}if(i.closed){i.destroy(),t.close();return}await i.waitForData(i.len)}},cancel(){i.destroy()}})}function Bm(i,t,r){t.streamingBody=!0;let n=0,f=!1;async function l(){for(;;){for(let c=t.pos;c+1<t.len;c++)if(t.buf[c]===13&&t.buf[c+1]===10){let $=Ry.decode(t.buf.subarray(t.pos,c));return t.pos=c+2,$}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>Uy)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(c){for(;;){if(n>0){if(t.len===t.pos){if(t.closed){i.destroy(t),c.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let y=Math.min(n,t.len-t.pos);if(c.enqueue(t.buf.slice(t.pos,t.pos+y)),t.pos+=y,n-=y,t.resumeIfDrained(),n===0)f=!0;return}if(f)await l(),f=!1;let $=await l(),u=$.indexOf(";"),h=Number.parseInt(u===-1?$:$.slice(0,u),16);if(!Number.isInteger(h)||h<0){i.destroy(t),c.error(Error("upstream sent malformed chunk size"));return}if(h===0){for(;;)if(await l()==="")break;Ny(i,t,r),c.close();return}n=h}},cancel(){i.destroy(t)}})}function Cm(i,t,r,n,f,l,c){let $=`${i} ${t} HTTP/1.1\r
160
+ host: ${n}\r
161
+ x-forwarded-for: 127.0.0.1\r
162
+ x-forwarded-proto: https\r
163
+ x-forwarded-host: ${f}\r
164
+ `;if(l!==void 0)$+=`origin: ${l}\r
165
+ `;let u=!1;for(let[h,y]of r){let w=h.toLowerCase();if(em.has(w))continue;if(l!==void 0&&w==="origin")continue;if(w==="content-length")u=!0;$+=`${h}: ${y}\r
166
+ `}if($+=`connection: keep-alive\r
167
+ `,c&&!u)$+=`content-length: ${c.length}\r
168
+ `;return $+=`\r
169
+ `,wm.encode($)}async function Um(i){let t=i.getReader(),r=[],n=0;for(;;){let{done:c,value:$}=await t.read();if(c)break;if($){if(n+=$.length,n>Cy)return t.cancel().catch(()=>{}),null;r.push($)}}if(r.length===1)return r[0];let f=new Uint8Array(n),l=0;for(let c of r)f.set(c,l),l+=c.length;return f}function xU(i){let t=typeof i==="string"?{to:i}:i,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function Wy(i,t,r){if(!i.preservePath)return i.to||"/";let n=`${t}${r}`;return n==="/"?`${i.to}/`:`${i.to}${n}`}import*as Ki from"node:path";function Xy(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var Rm={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"};function Sm(i){let t=Ki.extname(i).toLowerCase();return Rm[t]??"application/octet-stream"}function jm(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ki.posix.normalize(`/${t}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function Fm(i,t){let r=jm(i);if(r===null)return null;let n=Ki.posix.extname(r);if(t.cleanUrls&&n===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ki.join(t.dir,r),redirectTo:f||"/"}}if(r===""||i.endsWith("/"))return{filePath:Ki.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Ki.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ki.join(t.dir,`${r}.html`)};return{filePath:Ki.join(t.dir,r,"index.html")}}async function Jy(i,t){let r=Fm(i,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(r.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":Sm(r.filePath),"Cache-Control":n}});if(t.spa){let l=Ki.join(t.dir,"index.html"),c=Bun.file(l);if(await c.exists())return new Response(c,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var Nm=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function Wm(i){let t=i.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function Ky(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let r=i.slice(t.length);return r===""?"/":r}return i}function _y(i,t,r){let n=t.sourceHost??"",l=t.stripBasePathPrefix??!1?Ky(i,t.basePath):i,c=Iy(l,t.pathRewrites);if(c)n=c.targetHost,l=c.targetPath,a("request",`Path rewrite: ${i} → ${n}${l}`,r);return{targetHost:n,targetPath:l}}function Xm(i){let t=i.indexOf("://"),r=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=i.indexOf("?",r);if(n===-1)return{pathname:i.slice(r),search:""};return{pathname:i.slice(r,n),search:i.slice(n)}}function t0(i,t,r){let n=async(f,l)=>{let{pathname:c,search:$}=Xm(f.url),u=Wm(f),h=i(u,c);if(!h&&r){let m=await r(u,c,f);if(m instanceof Response)return m;if(m&&m.retry)h=i(u,c)}if(!h)return a("request",`No route found for host: ${u}`,t),new Response(`No proxy configured for ${u}`,{status:404});if(h.auth){let m=Ty(f,c,h.auth);if(m)return a("request",`401 challenge for ${u}${c}`,t),m}if(h.redirect){let m=Wy(h.redirect,c,$);return a("request",`${h.redirect.status} redirect ${u}${c} → ${m}`,t),new Response(null,{status:h.redirect.status,headers:{location:m}})}if(h.static){let s=h.stripBasePathPrefix??!0?Ky(c,h.basePath):c;return Jy(s,h.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!l||!h.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:m,targetPath:s}=_y(c,h,t),E=`ws://${m}${s}${$}`,T={};for(let[N,R]of f.headers)if(!Nm.has(N.toLowerCase())&&N.toLowerCase()!=="host")T[N]=R;T.host=m,T["x-forwarded-for"]="127.0.0.1",T["x-forwarded-proto"]="https",T["x-forwarded-host"]=u;let B={targetUrl:E,forwardHeaders:T};if(l.upgrade(f,{data:B})){a("ws",`upgraded ${u}${s} → ${E}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}if(!h.sourceHost)return new Response(`No upstream configured for ${u}`,{status:502});if(h.cleanUrls&&c.endsWith(".html")){let m=c.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let{targetHost:y,targetPath:w}=_y(c,h,t),e=h.changeOrigin?`http://${h.sourceHost}`:void 0,A=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD";try{return await Fy({hostPort:y,method:f.method,path:`${w}${$}`,reqHeaders:f.headers,forwardedHost:u,originOverride:e,body:f.body})}catch(m){if(m===i0)return a("request",`Upstream timeout for ${u}`,t),new Response("Gateway Timeout",{status:504});if(m===Kt)return a("request",`Upstream pool saturated for ${u}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(m===qr||!A)try{let s=new Headers(f.headers);if(s.set("host",y),s.set("x-forwarded-for","127.0.0.1"),s.set("x-forwarded-proto","https"),s.set("x-forwarded-host",u),e!==void 0)s.set("origin",e);return await fetch(`http://${y}${w}${$}`,{method:f.method,headers:s,body:f.body,redirect:"manual"})}catch(s){return a("request",`Proxy error for ${u}: ${s}`,t),new Response(`Proxy Error: ${s}`,{status:502})}return a("request",`Proxy error for ${u}: ${m}`,t),new Response(`Proxy Error: ${m}`,{status:502})}};return async(f,l)=>{try{return await n(f,l)}catch(c){return a("request",`Unhandled proxy handler error: ${c}`,t),new Response("Bad Gateway",{status:502})}}}function r0(i){let t=new WeakMap;return{open(r){let{targetUrl:n,forwardHeaders:f}=r.data,l;try{l=new WebSocket(n,{headers:f})}catch($){a("ws",`failed to open upstream ${n}: ${$}`,i),r.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let c={upstream:l,upstreamOpen:!1,pending:[]};t.set(r,c),l.addEventListener("open",()=>{c.upstreamOpen=!0;for(let $ of c.pending)l.send($);c.pending=[]}),l.addEventListener("message",($)=>{r.send($.data)}),l.addEventListener("close",($)=>{try{r.close($.code||1000,$.reason||"")}catch{}}),l.addEventListener("error",()=>{a("ws",`upstream error for ${n}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,n){let f=t.get(r);if(!f)return;let l=typeof n==="string"?n:new Uint8Array(n);if(f.upstreamOpen)f.upstream.send(l);else f.pending.push(l)},close(r,n,f){let l=t.get(r);if(!l)return;t.delete(r);try{l.upstream.close(n||1000,f||"")}catch{}}}}function Xf(i){return i.startsWith("*.")}function n0(i,t){if(!Xf(t))return!1;let r=t.slice(1);return i.length>r.length&&i.endsWith(r)}function zy(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[l,c]of i){if(!Xf(l))continue;if(n0(t,l)){let $=l.length-1;if($>f)f=$,n=c}}return n}function zt(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function Jm(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function f0(i){let t=new Map;for(let n of i){let f=zt(n.path),l=t.get(n.host);if(!l)l=new Map,t.set(n.host,l);l.set(f,n.route)}let r=new Map;for(let[n,f]of t){let l=[];for(let[c,$]of f)l.push({path:c,route:$});l.sort((c,$)=>$.path.length-c.path.length),r.set(n,l)}return r}function l0(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[l,c]of i){if(!Xf(l))continue;if(n0(t,l)){let $=l.length-1;if($>f)f=$,n=c}}return n}function c0(i,t,r){let n=l0(i,t);if(!n)return;for(let f of n)if(Jm(r,f.path))return f.route;return}import*as Lr from"node:fs/promises";import*as $0 from"node:path";function _m(i){if(!i.endsWith(".crt"))return null;let t=i.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function Im(i,t,r,n){try{let[f,l]=await Promise.all([Lr.readFile(t,"utf8"),Lr.readFile(r,"utf8")]);return{serverName:i,cert:f,key:l}}catch(f){return a("sni",`skipping ${i}: ${f.message}`,n),null}}async function u0(i,t){let r=new Map;if(i.certsDir){let f=[];try{f=await Lr.readdir(i.certsDir)}catch(l){a("sni",`certsDir read failed (${i.certsDir}): ${l.message}`,t)}for(let l of f){let c=_m(l);if(!c)continue;let $=l.slice(0,-4);r.set(c,{certPath:$0.join(i.certsDir,l),keyPath:$0.join(i.certsDir,`${$}.key`)})}}if(i.domains)for(let[f,l]of Object.entries(i.domains))r.set(f,l);let n=[];for(let[f,l]of r){let c=await Im(f,l.certPath,l.keyPath,t);if(c)n.push(c)}return n}import*as Ct from"node:fs/promises";import*as h0 from"node:path";var Km=60000,Oy=4096;function zm(i,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return i===n||i.endsWith(`.${n}`)})}function My(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class Jf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??zn,this.issuer=i.issuer??_l,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??Km;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!My(i))return!1;if(zm(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return a("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!My(i))return!1;let t=this.inFlight.get(i);if(t)return t;let r=this.negativeCache.get(i);if(r!==void 0&&Date.now()<r)return a("on-demand",`${i} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,n),n}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return a("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{a("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let r={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,r),this.negativeCache.delete(i),a("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),a("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=Oy){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=Oy){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:r}=this.pathsFor(i);try{let[n,f]=await Promise.all([Ct.readFile(t,"utf8"),Ct.readFile(r,"utf8")]),l={serverName:i,cert:n,key:f};return this.certs.set(i,l),a("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:h0.join(this.certsDir,`${i}.crt`),keyPath:h0.join(this.certsDir,`${i}.key`)}}async persist(i,t,r){await Ct.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:f}=this.pathsFor(i);await Promise.all([Ct.writeFile(n,t,"utf8"),Ct.writeFile(f,r,{encoding:"utf8",mode:384})])}}import{existsSync as Om,readdirSync as Mm,readFileSync as Gm,statSync as Hm}from"node:fs";import{homedir as dy}from"node:os";import{isAbsolute as dm,join as sr}from"node:path";var gy=["~/Code"],qy=["localhost","test"],gm=1800000,y0={dirExists:(i)=>{try{return Hm(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return Om(i)}catch{return!1}},readText:(i)=>{try{return Gm(i,"utf8")}catch{return null}}};function w0(i,t){if(i==="~")return t;if(i.startsWith("~/"))return sr(t,i.slice(2));return i}function qm(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function Gy(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function Lm(i,t){for(let r of t){let n=`.${r}`;if(i.endsWith(n)){let f=i.slice(0,-n.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function xm(i,t){let r=t.readText(sr(i,"rpx.site.json"));if(r)try{let f=JSON.parse(r);if(f&&typeof f==="object")return f}catch{}let n=t.readText(sr(i,"package.json"));if(n)try{let f=JSON.parse(n);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function km(i){let t=i.selfRegisters??!1;return{command:i.command,env:i.env,urlEnv:i.urlEnv,selfRegisters:t,routes:i.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function Vm(i,t){let r=xm(i,t);if(r?.command)return km(r);let n=t.fileExists(sr(i,"buddy")),f=t.readText(sr(i,"package.json")),l=null;if(f)try{l=JSON.parse(f)}catch{l=null}let c={...l?.dependencies??{},...l?.devDependencies??{}};if(n||Object.keys(c).some((u)=>u==="stacks"||u.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(l?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function e0(i,t={}){let r={dirExists:t.dirExists??y0.dirExists,fileExists:t.fileExists??y0.fileExists,readText:t.readText??y0.readText},n=t.detect??Vm,f=t.homeDir??dy(),l=i.tlds??qy,c=(i.roots??gy).map((e)=>w0(e,f)),$=i.idleTimeoutMs??gm,u=new Map;for(let e of i.sites??[])u.set(e.to,e);let h=(e)=>e.idleTimeoutMs??$;function y(e){let A=zy(u,e);if(!A)return null;let m=dm(A.dir)?A.dir:w0(A.dir,f),s=A.selfRegisters??!1,E=A.routes??[];if(!s&&E.length===0)E=n(m,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let T=Hy({...A.env??{}},void 0,e);return{host:e,id:Gy(e),dir:m,command:A.command,env:T,routes:E,selfRegisters:s,idleTimeoutMs:h(A),source:"config"}}function w(e){let A=Lm(e,l);if(!A)return null;for(let m of c){let s=sr(m,A);if(!r.dirExists(s))continue;let E=n(s,r);if(!E)continue;let T=E.selfRegisters??!1;return{host:e,id:Gy(e),dir:s,command:E.command,env:Hy({...E.env??{}},E.urlEnv,e),routes:T?[]:E.routes??[],selfRegisters:T,idleTimeoutMs:$,source:"discovered"}}return null}return{resolve(e){let A=qm(e);if(!A)return null;return y(A)??w(A)}}}function Dm(i){try{return Mm(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function yR(i,t={}){let r=t.homeDir??dy(),n=i.tlds??qy,f=(i.roots??gy).map((w)=>w0(w,r)),l=t.readdir??Dm,c=e0(i,t),$=[],u=new Set,h=(w)=>{if(w&&!u.has(w.host))u.add(w.host),$.push(w)};for(let w of i.sites??[])if(!w.to.includes("*"))h(c.resolve(w.to));let y=n[0]??"localhost";for(let w of f)for(let e of l(w))h(c.resolve(`${e}.${y}`));return $}function Hy(i,t,r){if(!t)return i;let n=`https://${r}`;for(let f of t)if(i[f]===void 0)i[f]=n;return i}import{closeSync as by,openSync as vm,readFileSync as Zm}from"node:fs";import*as oy from"node:fs/promises";import{spawn as pm}from"node:child_process";import{homedir as iE}from"node:os";import*as kr from"node:path";import*as xi from"node:process";import*as _f from"node:net";function xy(i,t,r){return a("port",`Checking if port ${i} is in use on ${t}`,r),new Promise((n)=>{let f=_f.createServer(),l=setTimeout(()=>{a("port",`Checking port ${i} timed out, assuming it's in use`,r),f.close(),n(!0)},3000);f.once("error",(c)=>{if(clearTimeout(l),c.code==="EADDRINUSE")a("port",`Port ${i} is in use`,r),n(!0);else a("port",`Error checking port ${i}: ${c.message}`,r),n(!0)}),f.once("listening",()=>{clearTimeout(l),a("port",`Port ${i} is available`,r),f.close(),n(!1)});try{f.listen(i,t)}catch(c){clearTimeout(l),a("port",`Exception checking port ${i}: ${c}`,r),n(!0)}})}async function A0(i,t,r,n=50){a("port",`Finding available port starting from ${i} (max attempts: ${n})`,r);let f=i,l=0;while(l<n){if(l++,!await xy(f,t,r))return a("port",`Found available port: ${f} after ${l} attempts`,r),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${l}/${n})`,r),f++}throw Error(`Unable to find available port after ${n} attempts starting from ${i}`)}function Ly(i,t,r=5000,n){return a("port",`Testing connection to ${t}:${i}`,n),new Promise((f)=>{let l=_f.connect({host:t,port:i,timeout:r});l.once("connect",()=>{a("port",`Successfully connected to ${t}:${i}`,n),l.end(),f(!0)}),l.once("timeout",()=>{a("port",`Connection to ${t}:${i} timed out`,n),l.destroy(),f(!1)}),l.once("error",(c)=>{a("port",`Failed to connect to ${t}:${i}: ${c.message}`,n),l.destroy(),f(!1)})})}class ky{usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,r=50){this.hostname=i,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await xy(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await Ly(i,this.hostname,3000,this.verbose))return a("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let r=await A0(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await Ly(r,this.hostname,3000,this.verbose))if(r<i+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(i){a("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var AR=new ky;import*as If from"node:fs";import*as Yi from"node:fs/promises";import{homedir as bm}from"node:os";import*as s0 from"node:path";import*as Kf from"node:process";var om=/^[a-zA-Z0-9._-]+$/;function Ut(){return s0.join(bm(),".stacks","rpx","registry.d")}function a0(i){return typeof i==="string"&&i.length>0&&i.length<=128&&om.test(i)}function m0(i,t){if(!a0(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return s0.join(i,`${t}.json`)}function Li(i){if(!Number.isInteger(i)||i<=0)return!1;try{return Kf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function Vy(i){if(!i||typeof i!=="object")return!1;let t=i,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",l=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&a0(t.id)&&(n||f)&&typeof t.to==="string"&&t.to.length>0&&l&&r&&typeof t.createdAt==="string"}async function Qm(i){await Yi.mkdir(i,{recursive:!0})}async function Dy(i,t=Ut(),r){if(!Vy(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await Qm(t);let n=m0(t,i.id),f=`${n}.tmp.${Kf.pid}.${Date.now()}`,l=JSON.stringify(i,null,2);try{await Yi.writeFile(f,l,{encoding:"utf8",mode:420}),await Yi.rename(f,n),a("registry",`wrote entry ${i.id} → ${n}`,r)}catch(c){throw await Yi.unlink(f).catch(()=>{}),c}}async function E0(i,t=Ut(),r){let n=m0(t,i);try{await Yi.unlink(n),a("registry",`removed entry ${i}`,r)}catch(f){if(f.code!=="ENOENT")throw f}}async function Pm(i,t=Ut(),r){let n=m0(t,i);try{let f=await Yi.readFile(n,"utf8"),l=JSON.parse(f);if(!Vy(l))return a("registry",`entry ${i} failed validation, removing`,r),await Yi.unlink(n).catch(()=>{}),null;return l}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return a("registry",`entry ${i} has invalid JSON, removing`,r),await Yi.unlink(n).catch(()=>{}),null;throw f}}async function ht(i=Ut(),t){let r;try{r=await Yi.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let n=[];for(let f of r){if(!f.endsWith(".json"))continue;let l=f.slice(0,-5);if(!a0(l))continue;let c=await Pm(l,i,t);if(c)n.push(c)}return n}async function xr(i=Ut(),t){let r=await ht(i,t),n=0;for(let f of r){if(f.pid===void 0)continue;if(!Li(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await E0(f.id,i,t).catch(()=>{}),n++}return n}function zf(i,t={}){let r=t.dir??Ut(),n=t.debounceMs??100,f=t.pollMs??Math.max(n*2,250),l=t.verbose;If.mkdirSync(r,{recursive:!0});let c=null,$=!1,u=null,h=!1,y=(E)=>{return JSON.stringify(E.map((T)=>({id:T.id,from:T.from,to:T.to,path:T.path,pid:T.pid,pathRewrites:T.pathRewrites,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,static:T.static})).sort((T,B)=>T.id.localeCompare(B.id)))},w=()=>{if(c=null,$)return;ht(r,l).then((E)=>{return u=y(E),i(E)}).catch((E)=>{a("registry",`watcher onChange failed: ${E}`,l)})},e=()=>{if($)return;if(c)clearTimeout(c);c=setTimeout(w,n)},m=setInterval(()=>{if($||h)return;h=!0,ht(r,l).then((E)=>{if(y(E)!==u)e()}).catch((E)=>{a("registry",`watcher poll failed: ${E}`,l)}).finally(()=>{h=!1})},f),s=If.watch(r,{persistent:!0},(E,T)=>{if(T&&/\.tmp\.\d+\.\d+$/.test(T))return;e()});return s.on("error",(E)=>{a("registry",`watcher error: ${E}`,l)}),e(),{close:()=>{if($=!0,c)clearTimeout(c);clearInterval(m),s.close()}}}var tE=120000,rE=200,nE=30000,fE=3000,lE=4000;class Y0{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??Ut(),this.rpxDir=i.rpxDir??kr.join(iE(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??tE,this.pollIntervalMs=i.pollIntervalMs??rE,this.restartDelayMs=i.restartDelayMs??fE,this.killGraceMs=i.killGraceMs??lE,this.launch=i.launcher??$E(this.verbose),this.probePort=i.probePort??cE,this.pickPort=i.pickPort??((r)=>A0(r,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??Dy,this.removeEntry=i.removeEntry??E0;let t=i.reapIntervalMs??nE;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let r=this.resolver.resolve(i);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let $ of i.routes){if(t.has($.portEnv))continue;let u=await this.pickPort($.defaultPort??3000);t.set($.portEnv,u)}let r=kr.join(this.rpxDir,"sites",`${i.id}.log`);await oy.mkdir(kr.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(i,t),f=null,l;try{f=this.launch({command:i.command,cwd:i.dir,env:n,logPath:r})}catch($){l=`failed to spawn: ${$.message}`}let c={site:i,status:l?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:l?this.now():0,error:l,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,c),l)return j.warn(`rpx: site ${i.host} ${l}`),c;return j.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then(($)=>this.onProcessExit(c,$)).catch(()=>{}),c.ready=this.driveReadiness(c).catch(($)=>{a("sites",`readiness loop for ${i.host} threw: ${$}`,this.verbose)}),c}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){j.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let r of i.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<r&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await n()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",j.success(`rpx: ${t.host} ready`);return}await T0(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let r=i.routes.filter((f)=>f.readyGate??zt(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let f of n)if(!await this.probePort(f))return!1;return n.length>0}}async publishRoutes(i){let{site:t,ports:r}=i;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((u)=>zt(u.path)==="/")??t.routes[0],f=r.get(n.portEnv);if(f===void 0)return;let l=[];for(let u of t.routes){if(u===n)continue;let h=r.get(u.portEnv);if(h===void 0)continue;l.push({from:zt(u.path),to:`localhost:${h}`,stripPrefix:u.stripPrefix??!1})}let c={id:t.id,from:`localhost:${f}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:l.length>0?l:void 0,pid:i.handle?.pid};await this.writeEntry(c,this.registryDir,this.verbose),i.routeIds=[t.id];let $=this.now()+2000;while(this.now()<$&&!this.isHostRoutable(t.host))await T0(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),j.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let r={};for(let[n,f]of Object.entries(xi.env))if(typeof f==="string")r[n]=f;Object.assign(r,i.env);for(let[n,f]of t)r[n]=String(f);return r.RPX_SITE_HOST=i.host,r.RPX_SITE_URL=`https://${i.host}`,r}readLogTail(i,t=40){try{return Zm(i.logPath,"utf8").split(`
170
+ `).slice(-t).join(`
171
+ `).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),j.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),T0(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,r]of this.sites){let n=r.site.idleTimeoutMs;if(n<=0)continue;let f=i-r.lastAccess;if((r.status==="ready"||i-r.startedAt>this.startupTimeoutMs)&&f>n)a("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function T0(i){return new Promise((t)=>setTimeout(t,i))}async function cE(i){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function $E(i){let t=uE();return({command:r,cwd:n,env:f,logPath:l})=>{let c=vm(l,"a");try{let $=pm("sh",["-c",r],{cwd:n,env:f,detached:!0,stdio:["ignore",c,c],...t?{uid:t.uid,gid:t.gid}:{}}),u=$.pid;if(u===void 0)throw Error("spawn returned no pid");let h=new Promise((y)=>{$.once("exit",(w)=>{y(w)}),$.once("error",()=>{y(null)})}).finally(()=>{try{by(c)}catch{}});return a("sites",`spawned pid ${u}: sh -c ${r} (cwd ${n})`,i),{pid:u,exited:h,stop:(y="SIGTERM")=>{try{xi.kill(-u,y)}catch{try{$.kill(y)}catch{}}}}}catch($){try{by(c)}catch{}throw $}}}function uE(){if(xi.platform==="win32")return null;if(!(typeof xi.getuid==="function"&&xi.getuid()===0))return null;let t=Number.parseInt(xi.env.SUDO_UID??"",10),r=Number.parseInt(xi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}function ar(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var hE=`
172
+ :root { color-scheme: light dark }
173
+ * { box-sizing: border-box }
174
+ body {
175
+ margin: 0; min-height: 100vh; display: grid; place-items: center;
176
+ font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
177
+ background: #0b0c0f; color: #e7e9ee;
178
+ }
179
+ .card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
180
+ .row { display: flex; align-items: center; gap: .75rem; }
181
+ h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
182
+ p { margin: .5rem 0 0; color: #9aa1ad }
183
+ code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
184
+ pre {
185
+ margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
186
+ background: #16181d; border: 1px solid #23262d; border-radius: 8px;
187
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
188
+ white-space: pre-wrap; word-break: break-word;
189
+ }
190
+ .spinner {
191
+ width: 16px; height: 16px; border-radius: 50%;
192
+ border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
193
+ animation: spin .8s linear infinite;
194
+ }
195
+ .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
196
+ @keyframes spin { to { transform: rotate(360deg) } }
197
+ `;function Qy(i,t,r){return`<!doctype html>
198
+ <html lang="en">
199
+ <head>
200
+ <meta charset="utf-8">
201
+ <meta name="viewport" content="width=device-width, initial-scale=1">
202
+ ${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
203
+ <title>${ar(i)}</title>
204
+ <style>${hE}</style>
205
+ </head>
206
+ <body><main class="card">${t}</main></body>
207
+ </html>`}function Py(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),r=i.logTail?`<pre>${ar(i.logTail)}</pre>`:"",n=`
208
+ <div class="row"><div class="spinner"></div><h1>Starting ${ar(i.host)}…</h1></div>
209
+ <p>rpx is booting this site's dev server on demand. This page reloads itself —
210
+ it'll switch to the app as soon as it's ready (usually a few seconds).</p>
211
+ <p>Booting for ${t}s.</p>
212
+ ${r}`;return new Response(Qy(`Starting ${i.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function vy(i){let t=i.logTail?`<pre>${ar(i.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
213
+ <div class="row"><div class="dot"></div><h1>${ar(i.host)} failed to start</h1></div>
214
+ <p>${ar(i.error)}</p>
215
+ ${t}
216
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(Qy(`${i.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var yE=5000;function Bi(){return Di.join(nw(),".stacks","rpx")}function Mf(i=Bi()){return Di.join(i,"daemon.pid")}async function Er(i=Bi()){try{let t=await Ai.readFile(Mf(i),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wE(i=Bi()){let t=await Er(i);return t!==null&&Li(t)}async function fw(i=Bi()){await Ai.mkdir(i,{recursive:!0});let t=Mf(i);while(!0){try{let n=await Ai.open(t,"wx");try{await n.write(`${Y.pid}
217
+ `)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await Er(i);if(r!==null&&Li(r))throw Error(`rpx daemon already running (pid=${r})`);await Ai.unlink(t).catch(()=>{})}}async function mr(i=Bi()){await Ai.unlink(Mf(i)).catch(()=>{})}function lw(i){let t=i.cleanUrls??!1,r=zt(i.path),n=Ey(i.auth);if(i.static)return{static:Xy(i.static,t),cleanUrls:t,basePath:r,auth:n};let f=i.from??"localhost:1";return{sourceHost:new URL(f.startsWith("http")?f:`http://${f}`).host,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:r,auth:n}}function eE(i){return i.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??i[0]??"rpx.localhost"}async function Of(i,t,r=[],n=!1){let f=await ht(t,i.verbose),l=[...new Set([...f.map((y)=>y.to).filter(Boolean),...r])],c=eE(l),$=[...new Set([c,...l,"rpx.localhost"])],u=wy(l,c,i.verbose);if(typeof i.https==="object"&&typeof u.https==="object")u.https={...u.https,...i.https};let h=await vc(u);if(h&&(n||!qc(oc,$)))a("daemon",`regenerating shared cert for host(s): ${$.join(", ")}`,i.verbose),Pc(),h=null;if(!h)a("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Ay({...u,forceRegenerate:!0}),h=await vc(u);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function AE(i,t,r,n){let f=Y.env.SUDO_PASSWORD,l=Y.env.HOME??nw(),c=[Y.execPath,...Y.argv.slice(1)],$=[`HOME=${l}`,`PATH=${Y.env.PATH??""}`];if(n)$.push("RPX_VERBOSE=1");for(let[m,s]of Object.entries(Y.env))if(s!==void 0&&m!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(m))$.push(`${m}=${s}`);let u=f?["-S","-p","","env",...$,...c]:["-n","env",...$,...c];a("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,n);let h=rw("sudo",u,{detached:!0,stdio:["pipe","ignore","ignore"]}),y=null,w=null;if(h.once("error",(m)=>{y=m}),h.once("exit",(m)=>{w=m??0}),f&&h.stdin)h.stdin.write(`${f}
218
+ `),h.stdin.end();h.unref();let e=Mf(i),A=Date.now()+15000;while(Date.now()<A){if(y)throw y;let m=await Er(i);if(m!==null&&Li(m)){if(n)j.success(`rpx daemon elevated to root (pid=${m}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:e,done:Promise.resolve(),stop:async()=>{try{Y.kill(m,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(w!==null&&w!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${w}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((s)=>setTimeout(s,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var Zy=!1;function B0(){if(Zy)return;Zy=!0,Y.on("uncaughtException",(i)=>{j.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),Y.on("unhandledRejection",(i)=>{j.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function cw(i,t){let r;try{r=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let n=(i.headers.get("host")??r.hostname).split(":")[0];if(t&&r.pathname.startsWith("/.well-known/acme-challenge/")){let f=t.challengeStore.handlePath(r.pathname);if(f!==void 0)return new Response(f,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(n))t.ensureCert(n).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${n}${r.pathname}${r.search}`}})}async function VR(i={}){B0();let t=i.verbose??!1,r=i.rpxDir??Bi(),n=i.registryDir??Di.join(r,"registry.d"),f=i.httpsPort??443,l=i.httpPort??80,c=i.hostname??"0.0.0.0",$=i.gcIntervalMs??yE;if(Y.env.RPX_DAEMON_WORKER==="1")return mE({rpxDir:Y.env.RPX_WORKER_RPXDIR??r,registryDir:Y.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(Y.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:Y.env.RPX_WORKER_HOSTNAME??c,verbose:Y.env.RPX_WORKER_VERBOSE==="1"||t});let u=f>0&&f<1024||l>0&&l<1024,h=typeof Y.getuid==="function"&&Y.getuid()===0;if(Y.platform!=="win32"&&u&&!h)return AE(r,f,l,t);let y=Math.max(1,i.workers??(Number.parseInt(Y.env.RPX_WORKERS??"",10)||1));if(y>1){if(i.onDemandSites?.enabled)j.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return EE(i,{rpxDir:r,registryDir:n,httpsPort:f,httpPort:l,hostname:c,verbose:t,gcIntervalMs:$,workers:y})}let w=await fw(r),e=new Map,A=(C,X)=>c0(e,C,X);function m(C){e=f0(C.map((et)=>({host:et.to,path:et.path,route:lw(et)})));let X=Array.from(e.keys());a("daemon",`routing table now covers ${X.length} host(s): ${X.join(", ")||"<empty>"}`,t)}await xr(n,t).catch((C)=>{a("daemon",`initial gc failed: ${C}`,t)});let s=await ht(n,t);m(s),await Yr({rpxDir:r,verbose:t}).catch((C)=>{a("daemon",`DNS reconcile on start failed: ${C}`,t)}),await Vr(s,{rpxDir:r,verbose:t,ownerPid:Y.pid}).catch((C)=>{a("daemon",`DNS setup on start failed: ${C}`,t)});let E=[];if(i.productionCerts){if(E=await u0(i.productionCerts,t),t&&E.length>0)j.info(`SNI: serving ${E.length} real cert(s): ${E.map((C)=>C.serverName).join(", ")}`)}let T=new Set,B=null,F;if(i.onDemandSites?.enabled){if(B=new Y0({resolver:e0(i.onDemandSites),registryDir:n,rpxDir:r,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(C)=>l0(e,C)!==void 0,onSiteActivating:(C)=>{Nt(C)}}),F=async(C)=>{let X=await B.onRequest(C);switch(X.kind){case"ready":return{retry:!0};case"starting":return Py({host:X.host,sinceMs:X.sinceMs,logTail:X.logTail});case"failed":return vy({host:X.host,error:X.error,logTail:X.logTail});case"unknown":default:return}},t)j.info("rpx: on-demand sites enabled")}let N=t0(A,t,F),R=r0(t),W=null;if(E.length===0)W=await Of(i,n);let k=i.onDemandTls,fi=k?.enabled?new Jf({config:k,certsDir:k.certsDir??i.productionCerts?.certsDir??Di.join(r,"on-demand-certs"),initial:E,verbose:t,onCertAdded:(C)=>{Mt(C)}}):null;function ki(C){if(C.length>0)return C.map((X)=>({serverName:X.serverName,cert:X.cert,key:X.key}));return{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1}}function or(C){return Bun.serve({port:f,hostname:c,reusePort:tw(),tls:ki(C),fetch(X,et){return N(X,et)},websocket:R,error(X){return a("daemon",`https server error: ${X}`,t),new Response(`Server Error: ${X.message}`,{status:500})}})}let St=(C)=>[...new Set(C.map((X)=>X.to).filter(Boolean))],Ot=(C)=>{if(!W)return E;return yy([...St(C),...T,"rpx.localhost"],W)},wt=or(fi?fi.sniEntries():E.length>0?E:Ot(s)),jt=null,Ft=!1;async function Mt(C){if(Vi)return;if(jt=C,Ft)return;Ft=!0;try{while(!Vi&&jt){let X=jt;jt=null,a("daemon",`rebuilding :443 with ${X.length} SNI cert(s)`,t),wt.stop(!1);let et,J0=!1;for(let _0=0;_0<20&&!Vi;_0++)try{wt=or(X),J0=!0;break}catch(Cw){et=Cw,await new Promise((Uw)=>setTimeout(Uw,25))}if(!J0)j.error(`rpx: failed to rebuild :443 after issuing cert: ${et?.message}`)}}finally{Ft=!1}}let bi=null;if(l>0)bi=Bun.serve({port:l,hostname:c,fetch(C){return cw(C,fi)},error(){return new Response("Bad Request",{status:400})}});if(t)j.success(`rpx daemon listening on https://${c}:${f}${bi?` (http→https on :${l})`:""}`),j.info(`pid file: ${w}`),j.info(`registry: ${n}`);async function J(C){if(Vi||E.length>0||fi||!W)return;try{W=await Of(i,n,[...T]),await Mt(Ot(C))}catch(X){a("daemon",`TLS sync on registry change failed: ${X}`,t)}}async function Nt(C){if(Vi||E.length>0||fi||!W||!C)return;if(T.has(C))return;T.add(C);try{W=await Of(i,n,[...T],!0);let X=await ht(n,t);await Mt(Ot(X))}catch(X){a("daemon",`dev cert refresh for ${C} failed: ${X}`,t)}}let qf=zf((C)=>{m(C),J(C),Vr(C,{rpxDir:r,verbose:t,ownerPid:Y.pid}).catch((X)=>{a("daemon",`DNS sync on registry change failed: ${X}`,t)})},{dir:n,verbose:t}),Gt=setInterval(()=>{xr(n,t).then((C)=>{if(C>0)a("daemon",`gc reaped ${C} stale entries`,t)}).catch((C)=>{a("daemon",`periodic gc failed: ${C}`,t)})},$);if(typeof Gt.unref==="function")Gt.unref();let Vi=!1,Br,Ht=new Promise((C)=>{Br=C});async function Lf(){if(Vi)return Ht;if(Vi=!0,clearInterval(Gt),qf.close(),await B?.stopAll().catch((C)=>{a("daemon",`site supervisor stopAll failed: ${C}`,t)}),wt.stop(!1),bi?.stop(!1),await Tr({rpxDir:r,verbose:t}).catch((C)=>{a("daemon",`DNS teardown failed: ${C}`,t)}),await mr(r),t)j.info("rpx daemon stopped");return Br(),Ht}let X0=(C)=>{a("daemon",`received ${C}, shutting down`,t),Lf().catch(()=>{})};return Y.once("SIGINT",X0),Y.once("SIGTERM",X0),{stop:Lf,done:Ht,httpsPort:typeof wt.port==="number"?wt.port:f,httpPort:bi&&typeof bi.port==="number"?bi.port:l,pidPath:w,ensureCert:(C)=>fi?fi.ensureCert(C):Promise.resolve(!1),listSites:()=>B?.list()??[]}}function C0(i){return Di.join(i,"cluster-sni.json")}async function py(i,t,r){let n=C0(i),f=`${n}.${Y.pid}.tmp`;await Ai.writeFile(f,JSON.stringify({sni:t,dev:r}),"utf8"),await Ai.rename(f,n)}async function iw(i){try{return JSON.parse(await Ai.readFile(C0(i),"utf8"))}catch{return{sni:[],dev:null}}}function sE(i){if(i.sni.length>0)return i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));if(i.dev)return{key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function aE(){let i=Y.execPath,t=Y.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let r=Di.basename(i).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&Y.argv[1])return[i,Y.argv[1],"daemon:start"];return[i,"daemon:start"]}async function mE(i){B0();let{rpxDir:t,registryDir:r,httpsPort:n,hostname:f,verbose:l}=i,c=new Map,$=(R,W)=>c0(c,R,W),u=(R)=>{c=f0(R.map((W)=>({host:W.to,path:W.path,route:lw(W)})))};u(await ht(r,l));let h=t0($,l),y=r0(l),w=!1,e=(R)=>Bun.serve({port:n,hostname:f,reusePort:!0,tls:sE(R),fetch(W,k){return h(W,k)},websocket:y,error(W){return a("daemon",`worker https error: ${W}`,l),new Response(`Server Error: ${W.message}`,{status:500})}}),A=e(await iw(t));async function m(){if(w)return;let R=await iw(t),W=null;for(let fi=0;fi<20&&!w;fi++)try{W=e(R);break}catch{await new Promise((ki)=>setTimeout(ki,25))}if(!W){a("daemon","worker reloadTls: could not bind new listener; keeping current",l);return}let k=A;A=W,k.stop(!1)}let s=zf((R)=>u(R),{dir:r,verbose:l}),E=()=>{m().catch(()=>{})};Y.on("SIGHUP",E);let T,B=new Promise((R)=>{T=R});async function F(){if(w)return B;return w=!0,Y.off("SIGHUP",E),s.close(),A.stop(!1),T(),B}let N=()=>{F().then(()=>Y.exit(0)).catch(()=>Y.exit(0))};if(Y.once("SIGTERM",N),Y.once("SIGINT",N),l)j.success(`rpx worker (pid ${Y.pid}) serving :${n}`);return{stop:F,done:B,httpsPort:typeof A.port==="number"?A.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function EE(i,t){B0();let{rpxDir:r,registryDir:n,httpsPort:f,httpPort:l,hostname:c,verbose:$,gcIntervalMs:u,workers:h}=t,y=await fw(r),w=[];if(i.productionCerts)w=await u0(i.productionCerts,$);let e=null;if(w.length===0)e=await Of(i,n);let A=e?{key:e.key,cert:e.cert,ca:Array.isArray(e.ca)?e.ca.join(`
219
+ `):e.ca}:null,m=!1,s=[];function E(J){for(let Nt of s)try{Nt.kill(J)}catch{}}async function T(J){await py(r,J,A),E("SIGHUP")}let B=i.onDemandTls,F=B?.enabled?new Jf({config:B,certsDir:B.certsDir??i.productionCerts?.certsDir??Di.join(r,"on-demand-certs"),initial:w,verbose:$,onCertAdded:(J)=>{T(J)}}):null;await py(r,F?F.sniEntries():w,A);let N=await ht(n,$);await Yr({rpxDir:r,verbose:$}).catch((J)=>{a("daemon",`DNS reconcile on start failed: ${J}`,$)}),await Vr(N,{rpxDir:r,verbose:$,ownerPid:Y.pid}).catch((J)=>{a("daemon",`DNS setup on start failed: ${J}`,$)}),await xr(n,$).catch(()=>{});let R=zf((J)=>{Vr(J,{rpxDir:r,verbose:$,ownerPid:Y.pid}).catch((Nt)=>{a("daemon",`DNS sync on registry change failed: ${Nt}`,$)})},{dir:n,verbose:$}),W=setInterval(()=>{xr(n,$).catch(()=>{})},u);W.unref?.();let k=null;if(l>0)k=Bun.serve({port:l,hostname:c,fetch(J){return cw(J,F)},error(){return new Response("Bad Request",{status:400})}});let fi=10,ki=60000,or=30000,St=0,Ot=Date.now();function wt(){if(m)return;let J={...Y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:c,RPX_WORKER_VERBOSE:$?"1":"0"},Nt=Bun.spawn(aE(),{env:J,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(qf,Gt){if(m)return;let Vi=s.indexOf(qf);if(Vi!==-1)s.splice(Vi,1);let Br=Date.now();if(Br-Ot>ki)Ot=Br,St=0;if(St++,St>fi){j.error(`rpx: worker keeps exiting (code ${Gt}); giving up after ${fi} restarts in ${Math.round(ki/1000)}s`);return}let Ht=Math.min(or,100*2**Math.min(St,8));a("daemon",`worker exited (code ${Gt}); respawning in ${Ht}ms (restart ${St}/${fi})`,$),setTimeout(wt,Ht).unref?.()}});s.push(Nt)}for(let J=0;J<h;J++)wt();if($)j.success(`rpx coordinator listening on https://${c}:${f} via ${h} worker(s)${k?` (http→https on :${l})`:""}`),j.info(`pid file: ${y}`);let jt,Ft=new Promise((J)=>{jt=J});async function Mt(){if(m)return Ft;if(m=!0,clearInterval(W),R.close(),k?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(s.map((J)=>J.exited)),new Promise((J)=>setTimeout(J,3000))]),E("SIGKILL"),await Tr({rpxDir:r,verbose:$}).catch((J)=>{a("daemon",`DNS teardown failed: ${J}`,$)}),await mr(r),await Ai.unlink(C0(r)).catch(()=>{}),$)j.info("rpx coordinator stopped");return jt(),Ft}let bi=(J)=>{a("daemon",`coordinator received ${J}, shutting down`,$),Mt().catch(()=>{})};return Y.once("SIGINT",bi),Y.once("SIGTERM",bi),{stop:Mt,done:Ft,httpsPort:f,httpPort:l,pidPath:y,ensureCert:(J)=>F?F.ensureCert(J):Promise.resolve(!1),listSites:()=>[]}}function TE(){let i=Y.execPath,t=Di.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&Y.argv[1])return[i,Y.argv[1],"daemon:start"];return[i,"daemon:start"]}async function DR(i={}){let t=i.rpxDir??Bi(),r=i.verbose??!1;await Yr({rpxDir:t,verbose:r}).catch((y)=>{a("daemon",`DNS reconcile before ensureDaemonRunning: ${y}`,r)});let n=await Er(t);if(n!==null&&Li(n))return a("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)a("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await mr(t);await Ai.mkdir(t,{recursive:!0});let f=i.spawnCommand??TE();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,r);let l=rw(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??Y.cwd(),env:i.spawnEnv?{...Y.env,...i.spawnEnv}:Y.env});l.unref();let c=null;l.once("error",(y)=>{c=y});let $=i.startupTimeoutMs??5000,u=i.pollIntervalMs??50,h=Date.now()+$;while(Date.now()<h){if(c)throw c;let y=await Er(t);if(y!==null&&Li(y))return a("daemon",`daemon registered with pid=${y}`,r),{pid:y,spawned:!0};await new Promise((w)=>setTimeout(w,u))}if(c)throw c;throw Error(`rpx daemon failed to start within ${$}ms (rpxDir=${t})`)}async function bR(i={}){let t=i.rpxDir??Bi(),r=i.verbose??!1,n=i.timeoutMs??5000,f=i.pollIntervalMs??50,l=i.forceAfterTimeout??!0,c=await Er(t);if(c===null||!Li(c)){if(c!==null)await mr(t);return await Yr({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:c,forced:!1}}try{Y.kill(c,"SIGTERM")}catch(u){if(u.code==="ESRCH")return await mr(t),{stopped:!1,pid:c,forced:!1};throw u}let $=Date.now()+n;while(Date.now()<$){if(!Li(c))return a("daemon",`daemon pid=${c} stopped cleanly`,r),{stopped:!0,pid:c,forced:!1};await new Promise((u)=>setTimeout(u,f))}if(!l)throw Error(`rpx daemon (pid=${c}) did not exit within ${n}ms`);a("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,r);try{Y.kill(c,"SIGKILL")}catch(u){if(u.code!=="ESRCH")throw u}return await mr(t),await Tr({rpxDir:t,verbose:r}).catch((u)=>{a("daemon",`DNS teardown after SIGKILL: ${u}`,r)}),{stopped:!0,pid:c,forced:!0}}async function oR(i={}){let t=i.rpxDir??Bi();if(await wE(t))return;await Yr({rpxDir:t,verbose:i.verbose})}import*as Rt from"node:fs/promises";import{homedir as YE}from"node:os";import*as U0 from"node:path";var Gf=1,BE="dns-state.json",$w=["com","test","dev","app","page","local","localhost","example","invalid"];function uw(){return U0.join(YE(),".stacks","rpx")}function R0(i=uw()){return U0.join(i,BE)}async function Hf(i=uw()){try{let t=await Rt.readFile(R0(i),"utf8"),r=JSON.parse(t);if(r.version!==Gf||!Array.isArray(r.resolvers))return null;return{version:Gf,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function hw(i,t){await Rt.mkdir(i,{recursive:!0}),await Rt.writeFile(R0(i),`${JSON.stringify(t,null,2)}
220
+ `,"utf8")}async function S0(i){await Rt.rm(R0(i),{force:!0})}function yw(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function CE(i){let t=yw(i);if(!t)return null;let r=t.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function j0(i){let t=new Set;for(let r of i){let n=CE(r);if(n)t.add(n)}return Array.from(t).sort()}function F0(i){let t=new Set;for(let r of i){let n=yw(r);if(n)t.add(n)}return Array.from(t).sort()}var gf=15353,UE="# managed-by: rpx",sw="/etc/resolver",Ci=null,df=new Set;function aw(i){return{id:i.readUInt16BE(0),flags:i.readUInt16BE(2),qdcount:i.readUInt16BE(4),ancount:i.readUInt16BE(6),nscount:i.readUInt16BE(8),arcount:i.readUInt16BE(10)}}function mw(i,t,r=0){let n=[],f=t,l=0;while(!0){if(f>=i.length||++l>128)break;let c=i[f];if(c===0){f++;break}if((c&192)===192){if(f+1>=i.length||r>=10)break;let $=i.readUInt16BE(f)&16383,{name:u}=mw(i,$,r+1);if(u)n.push(u);f+=2;break}if(f++,f+c>i.length)break;n.push(i.subarray(f,f+c).toString("ascii")),f+=c}return{name:n.join("."),newOffset:f}}function RE(i,t){let{name:r,newOffset:n}=mw(i,t),f=i.readUInt16BE(n),l=i.readUInt16BE(n+2);return{question:{name:r,type:f,class:l},newOffset:n+4}}function Dr(i){let t=i.split("."),r=[];for(let n of t)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function SE(i,t,r){let n=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),n.push(f),n.push(Dr(t.name));let l=Buffer.alloc(4);l.writeUInt16BE(t.type,0),l.writeUInt16BE(t.class,2),n.push(l),n.push(Dr(t.name));let c=Buffer.alloc(10);if(c.writeUInt16BE(t.type,0),c.writeUInt16BE(1,2),c.writeUInt32BE(300,4),t.type===1){c.writeUInt16BE(4,8),n.push(c);let $=r.split(".").map((u)=>Number.parseInt(u,10));n.push(Buffer.from($))}else if(t.type===28)c.writeUInt16BE(16,8),n.push(c),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,Dr(t.name),l]);return Buffer.concat(n)}function jE(i,t){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(i,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(Dr(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),r.push(f),Buffer.concat(r)}async function FE(i,t){if(yt.platform!=="darwin")return!1;let r=F0(i);if(r.length===0)return!1;if(Ci){for(let n of r)df.add(n);return a("dns","DNS server already running — merged domains",t),!0}return df=new Set(r),new Promise((n)=>{Ci=ww.createSocket("udp4"),Ci.on("error",(f)=>{a("dns",`DNS server error: ${f.message}`,t),Ci?.close(),Ci=null,n(!1)}),Ci.on("message",(f,l)=>{try{let c=aw(f),{question:$}=RE(f,12);a("dns",`Query for ${$.name} type ${$.type} from ${l.address}`,t);let u=$.name.toLowerCase(),h=!1;for(let w of df)if(u===w||u.endsWith(`.${w}`)){h=!0;break}let y;if(h&&($.type===1||$.type===28))y=SE(c.id,$,"127.0.0.1"),a("dns",`Responding with localhost for ${$.name}`,t);else y=jE(c.id,$),a("dns",`NXDOMAIN for ${$.name}`,t);Ci?.send(y,l.port,l.address)}catch(c){a("dns",`Error processing DNS query: ${c}`,t)}}),Ci.on("listening",()=>{let f=Ci?.address();a("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),n(!0)});try{Ci.bind(gf,"127.0.0.1")}catch(f){a("dns",`Failed to bind DNS server: ${f}`,t),n(!1)}})}function Ew(i){if(Ci)a("dns","Stopping DNS server",i),Ci.close(),Ci=null,df=new Set}function nS(){return Ci!==null}async function NE(i,t=500){let r=i.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let f=ww.createSocket("udp4"),l=setTimeout(()=>{f.close(),n(!1)},t);f.on("message",($)=>{clearTimeout(l),f.close();try{let u=aw($);n(u.ancount>0)}catch{n(!1)}}),f.on("error",()=>{clearTimeout(l),f.close(),n(!1)});let c=WE(r,1);f.send(c,gf,"127.0.0.1",($)=>{if($)clearTimeout(l),f.close(),n(!1)})})}function WE(i,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([Dr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([r,n])}function XE(){return`${UE}
221
+ nameserver 127.0.0.1
222
+ port ${gf}
223
+ `}function br(i){return Aw.join(sw,i)}function JE(i){return i.includes("127.0.0.1")&&i.includes(String(gf))}async function _E(i){try{return await ew.readFile(br(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function N0(i){if(yt.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:n}=await import("./chunk-c9brkawa.js");if(!n()&&!r()){a("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),a("dns","DNS cache flushed",i)}catch(f){a("dns",`Could not flush DNS cache: ${f}`,i)}}function Tw(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function IE(i,t){Tw(i);let{execSudoSync:r}=await import("./chunk-c9brkawa.js"),n=XE().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${sw} && printf "%b" "${n}" > ${br(i)}'`;r(f),a("dns",`Created ${br(i)}`,t)}async function KE(i,t){Tw(i);let{execSudoSync:r}=await import("./chunk-c9brkawa.js");r(`rm -f ${br(i)}`),a("dns",`Removed ${br(i)}`,t)}async function fS(i,t){return Bw({domains:t??[],verbose:i})}async function zE(i,t){if(yt.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-c9brkawa.js");if(!n()&&!r())return a("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await IE(f,t);return await N0(t),!0}catch(f){return a("dns",`Failed to create resolver file: ${f}`,t),!1}}async function W0(i,t){if(yt.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-c9brkawa.js");if(!n()&&!r())return;try{for(let f of i)await KE(f,t);await N0(t)}catch(f){a("dns",`Failed to remove resolver files: ${f}`,t)}}async function Yw(i){if(yt.platform!=="darwin")return[];let t=[];for(let r of $w){let n=await _E(r);if(n&&JE(n))await W0([r],i),t.push(r)}return t}async function Bw(i){let t=i.rpxDir??Bi(),r=F0(i.domains);if(r.length===0)return!1;let n=j0(r),f=await FE(r,i.verbose);if(!f){let $=r[0];if($&&await NE($))f=!0;else a("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await zE(n,i.verbose))return!1;let c={version:Gf,resolvers:n,domains:r,ownerPid:i.ownerPid??yt.pid,updatedAt:new Date().toISOString()};return await hw(t,c),!0}async function Vr(i,t={}){let r=i.map((u)=>u.to).filter(Boolean),n=t.rpxDir??Bi(),f=j0(r),$=((await Hf(n))?.resolvers??[]).filter((u)=>!f.includes(u));if($.length>0)await W0($,t.verbose);if(f.length===0){Ew(t.verbose),await S0(n);return}await Bw({domains:r,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??yt.pid})}async function Tr(i={}){let t=i.rpxDir??Bi();Ew(i.verbose);let n=(await Hf(t))?.resolvers??[];await W0(n,i.verbose),await Yw(i.verbose),await S0(t)}async function lS(i){await Tr({verbose:i})}async function Yr(i={}){let t=i.rpxDir??Bi(),r=await Hf(t),n=r?.ownerPid!=null&&Li(r.ownerPid);if(r&&!n){a("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,i.verbose),await Tr(i);return}let f=await Yw(i.verbose);if(f.length>0)a("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await N0(i.verbose)}
224
+ export{j as a,ry as b,Ha as c,_t as d,gc as e,qc as f,da as g,ga as h,Yt as i,It as j,Lc as k,Gr as l,xc as m,ny as n,Ff as o,Hr as p,dr as q,kc as r,oc as s,yy as t,wy as u,Qc as v,IU as w,KU as x,zU as y,Ay as z,Pc as A,vc as B,Zc as C,OU as D,sy as E,va as F,Ey as G,Ty as H,xU as I,Wy as J,Xy as K,Sm as L,jm as M,Fm as N,Jy as O,Ky as P,t0 as Q,r0 as R,Xf as S,n0 as T,zy as U,zt as V,Jm as W,f0 as X,l0 as Y,c0 as Z,_m as _,u0 as $,zm as aa,My as ba,Jf as ca,w0 as da,Gy as ea,Lm as fa,xm as ga,Vm as ha,e0 as ia,yR as ja,xy as ka,A0 as la,ky as ma,AR as na,Ut as oa,a0 as pa,Li as qa,Dy as ra,E0 as sa,Pm as ta,ht as ua,xr as va,zf as wa,Y0 as xa,ar as ya,Py as za,vy as Aa,Gf as Ba,$w as Ca,yw as Da,CE as Ea,j0 as Fa,F0 as Ga,gf as Ha,UE as Ia,FE as Ja,Ew as Ka,nS as La,NE as Ma,br as Na,JE as Oa,fS as Pa,Yw as Qa,Bw as Ra,Vr as Sa,Tr as Ta,lS as Ua,Yr as Va,Bi as Wa,Mf as Xa,Er as Ya,wE as Za,fw as _a,mr as $a,VR as ab,TE as bb,DR as cb,bR as db,oR as eb};