@stacksjs/rpx 0.11.44 → 0.11.45

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,252 @@
1
+ import{Ab as x,Bb as Ll,Cb as M$,Eb as Nt,Fb as Y,Gb as L$,Kb as _h,Lb as $l,Nb as er,Ob as zh,Qb as y$,Rb as Qh}from"./chunk-w4t1nar9.js";import Z$ from"node:dgram";import*as v$ from"node:fs/promises";import*as p$ from"node:path";import*as Bt from"node:process";import{spawn as x$}from"node:child_process";import*as Ei from"node:fs/promises";import{homedir as g$}from"node:os";import*as vi from"node:path";import*as m from"node:process";var F={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 ul}from"node:child_process";import Z from"node:fs/promises";import*as hl from"node:os";import{homedir as Ef}from"node:os";import*as Mh from"node:path";import{join as d}from"node:path";import*as si from"node:process";import{createRequire as u1}from"node:module";import{Resolver as y0}from"node:dns/promises";import{createHash as $1,sign as A1}from"node:crypto";import{createHash as T1}from"node:crypto";import{sign as E1}from"node:crypto";import{generateKeyPairSync as lw,X509Certificate as X1}from"node:crypto";import w0 from"node:os";import u0 from"node:path";import{existsSync as fy,statSync as ny}from"fs";import{existsSync as S1,mkdirSync as tj,readdirSync as fj,readFileSync as J1,writeFileSync as nj}from"fs";import{homedir as qt}from"os";import{dirname as lj,resolve as zi}from"path";import dn from"process";import{existsSync as ry,statSync as cy}from"fs";import{existsSync as M0,mkdirSync as F1,readdirSync as K1,writeFileSync as I1}from"fs";import{homedir as Lt}from"os";import{dirname as ly,resolve as Bi}from"path";import _t from"process";import{join as _1,relative as z1,resolve as yy}from"path";import _n from"process";import{existsSync as yw,mkdirSync as Bj,readdirSync as Cj,writeFileSync as Uj}from"fs";import{homedir as h0}from"os";import{dirname as Rj,resolve as Yi}from"path";import Kf from"process";import{join as Q1,relative as M1,resolve as wy}from"path";import zn from"process";import{existsSync as ww,mkdirSync as Jj,readdirSync as Fj,writeFileSync as Kj}from"fs";import{dirname as _j,resolve as Qn}from"path";import O0 from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as O1,createDecipheriv as G1,randomBytes as $0}from"crypto";import{closeSync as A0,createReadStream as uy,createWriteStream as a1,existsSync as T0,fsyncSync as hy,openSync as $y,writeFileSync as H1}from"fs";import{access as e1,constants as Ay,mkdir as q1,readdir as yn,rename as Ty,stat as xt,unlink as wn,writeFile as E0}from"fs/promises";import{join as gt}from"path";import wi from"process";import{pipeline as L1}from"stream/promises";import{createGzip as Ey}from"zlib";import kt from"process";import ft from"process";import{Buffer as oi}from"buffer";import{createCipheriv as x1,createDecipheriv as g1,randomBytes as Y0}from"crypto";import{closeSync as B0,createReadStream as Yy,createWriteStream as k1,existsSync as un,fsyncSync as By,openSync as Cy,writeFileSync as V1}from"fs";import{access as s1,constants as Uy,mkdir as D1,readdir as hn,rename as jy,stat as Vt,unlink as $n,writeFile as C0}from"fs/promises";import{isAbsolute as d1,join as st,resolve as b1}from"path";import e from"process";import{pipeline as P1}from"stream/promises";import{createGzip as my}from"zlib";import Dt from"process";import nt from"process";import An from"process";import{existsSync as Tn}from"fs";import{resolve as U0}from"path";import{existsSync as Z1}from"fs";import{existsSync as v1,readdirSync as p1}from"fs";import{extname as j0,resolve as Ry}from"path";import o1 from"process";import{join as iA,relative as tA,resolve as Wy}from"path";import Mn from"process";import{Buffer as it}from"buffer";import{createCipheriv as fA,createDecipheriv as nA,randomBytes as m0}from"crypto";import{closeSync as R0,createReadStream as Xy,createWriteStream as rA,existsSync as En,fsyncSync as Ny,openSync as Sy,writeFileSync as cA}from"fs";import{access as lA,constants as Jy,mkdir as yA,readdir as Yn,rename as Fy,stat as dt,unlink as Bn,writeFile as W0}from"fs/promises";import{isAbsolute as wA,join as bt,resolve as uA}from"path";import q from"process";import{pipeline as hA}from"stream/promises";import{createGzip as Ky}from"zlib";import Pt from"process";import rt from"process";import Cn from"process";import{existsSync as Un}from"fs";import{resolve as X0}from"path";import{existsSync as $A}from"fs";import{exec as MT}from"node:child_process";import s0 from"node:fs";import OT from"node:os";import ei from"node:path";import Vw from"node:process";import{promisify as GT}from"node:util";import ot from"node:crypto";import ct from"node:fs";import b0 from"node:path";import rE from"node:crypto";import cE from"node:fs";import lE from"node:tls";import{execSync as uE}from"node:child_process";import sn from"node:os";var h1=u1(import.meta.url),Dy=30000;async function Rn(i,t={},f=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(f)})}catch(n){if(n&&typeof n==="object"&&n.name==="TimeoutError"){let r=Error(`ACME HTTP request to ${i} timed out after ${f}ms`);throw r.name="AcmeRequestTimeoutError",r}throw n}}async function dy(i,t,f={}){let n=f.timeoutMs??120000,r=f.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new y0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new y0,l.setServers($)}catch{}let y=Date.now()+n,w=l??new y0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,r))}}class Ff{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(Ff.PATH_PREFIX);if(t===-1)return;let f=i.slice(t+Ff.PATH_PREFIX.length);return this.get(f)}}var Dn=new Ff;function Wn(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function I0(i){return Buffer.from(i,"base64url")}function by(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 Py(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return $1("sha256").update(t).digest("base64url")}function Zy(i){let{protectedHeader:t,payload:f,privateKey:n}=i,r=Wn(JSON.stringify(t)),c=f===""?"":Wn(JSON.stringify(f)),l=`${r}.${c}`,y=A1("sha256",Buffer.from(l),{key:n,dsaEncoding:"ieee-p1363"});return{protected:r,payload:c,signature:Wn(y)}}var vy="https://acme-staging-v02.api.letsencrypt.org/directory",py="https://acme-v02.api.letsencrypt.org/directory";class Kn extends Error{problem;httpStatus;constructor(i,t,f){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=f}}class In{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=by(i.accountPublicKey),this.thumbprint=Py(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??Dy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await Rn(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await Rn(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:f,useJwk:n}=i,r={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)r.jwk=this.jwk;else r.kid=this.requireKid();let c=Zy({protectedHeader:r,payload:f,privateKey:this.accountKey}),l=await Rn(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Kn(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),f={termsOfServiceAgreed:!0};if(i.email)f.contact=[`mailto:${i.email}`];let n=await this.signedPost({url:t.newAccount,payload:f,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(),f={identifiers:i.map((r)=>({type:"dns",value:r}))},n=await this.signedPost({url:t.newOrder,payload:f});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 T1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let f=t.timeoutMs??60000,n=t.intervalMs??2000,r=Date.now()+f;while(Date.now()<r){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Kn(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ty(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 f=t.timeoutMs??60000,n=t.intervalMs??2000,r=Date.now()+f;while(Date.now()<r){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await ty(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 f=i.challenges.find((n)=>n.type===t);if(!f)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return f}}function oy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],f=t[0];if(!f)return{certPem:`${i.trim()}
2
+ `,chainPem:""};let n=`${f.trim()}
3
+ `,r=t.slice(1).map((c)=>c.trim()).join(`
4
+ `);return{certPem:n,chainPem:r?`${r}
5
+ `:""}}function iw(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function ty(i){return new Promise((t)=>setTimeout(t,i))}function Y1(i){if(i<128)return Buffer.from([i]);let t=[],f=i;while(f>0)t.unshift(f&255),f>>=8;return Buffer.from([128|t.length,...t])}function Rt(i,t){return Buffer.concat([Buffer.from([i]),Y1(t.length),t])}function tw(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let f=[],n=i;while(n>0)f.unshift(n&255),n>>=8;if(f[0]&128)f.unshift(0);t=Buffer.from(f)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Rt(2,t)}function It(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let f=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let r=t[n],c=[r&127];r=Math.floor(r/128);while(r>0)c.unshift(r&127|128),r=Math.floor(r/128);f.push(...c)}return Rt(6,Buffer.from(f))}function _i(...i){return Rt(48,Buffer.concat(i))}function _0(...i){return Rt(49,Buffer.concat(i))}function z0(i){return Rt(3,Buffer.concat([Buffer.from([0]),i]))}function fw(i){return Rt(4,i)}function nw(i){return Rt(12,Buffer.from(i,"utf8"))}function Q0(i,t,f){let n=128|(f?32:0)|i;return Rt(n,t)}var B1="1.2.840.10045.2.1",C1="1.2.840.10045.3.1.7",U1="1.2.840.10045.4.3.2",j1="2.5.4.3",m1="1.2.840.113549.1.9.14",R1="2.5.29.17";function W1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let f=I0(t.x),n=I0(t.y);if(f.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${f.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),f,n])}function rw(i){let{domains:t,publicKey:f,privateKey:n}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let r=_i(_0(_i(It(j1),nw(t[0])))),c=_i(_i(It(B1),It(C1)),z0(W1(f))),l=t.map((E)=>Q0(2,Buffer.from(E,"ascii"),!1)),y=_i(...l),w=_i(It(R1),fw(y)),u=_i(w),h=_i(It(m1),_0(u)),$=Q0(0,h,!0),A=_i(tw(0),r,c,$),T=E1("sha256",A,n),C=_i(It(U1));return _i(A,C,z0(T))}function cw(i){return rw(i).toString("base64url")}function N1(i){if(i){let{createPrivateKey:r,createPublicKey:c}=h1("node:crypto"),l=r(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:f}=lw("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:f,pem:n}}async function P0(i){let{domains:t,method:f}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(f==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&f!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=i.directoryUrl??(i.staging===!1?py:vy),r=N1(i.accountKeyPem),c=new In({directoryUrl:n,accountKey:r.privateKey,accountPublicKey:r.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??Dn,u=[],h=[];try{for(let I of l.authorizations){let z=await c.getAuthorization(I);if(z.status==="valid")continue;let X=In.selectChallenge(z,f);if(f==="dns-01"){let li=iw(z.identifier.value),yi=c.dns01TxtValue(X.token);await i.dnsProvider.setTxt(li,yi),u.push({name:li,value:yi}),await dy(li,yi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(X.token,c.keyAuthorization(X.token)),h.push(X.token);await c.notifyChallengeReady(X.url),await c.pollAuthorization(I,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=lw("ec",{namedCurve:"P-256"}),T=cw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let C=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(C),{certPem:B,chainPem:U}=oy(E),R=U?`${B}${U}`:B,N=$.export({format:"pem",type:"pkcs8"}).toString(),J=new Date(new X1(B).validTo);return{certPem:B,keyPem:N,chainPem:U,fullChainPem:R,accountKeyPem:r.pem,notAfter:J}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class uw{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 f=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${f}`}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(([,f],[,n])=>f.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let f=0;f<t;f++)this.cache.delete(i[f][0])}set(i,t,f,n){if(!this.options.enabled)return;let r=this.generateKey(i,f),c=n??this.options.ttl,l=this.estimateSize(t);this.cache.set(r,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let f=this.generateKey(i,t),n=this.cache.get(f);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(f),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!fy(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let f=this.get(i,t);if(!f)return;if(this.isFileModified(t,f.fileTimestamp)){this.delete(i,t);return}return f.value}setWithFileCheck(i,t,f,n){try{let r=fy(f)?ny(f):null,c=r?r.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},f,n)}catch{this.set(i,t,f,n)}}delete(i,t){let f=this.generateKey(i,t);return this.cache.delete(f)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,f]of this.cache.entries())if(this.isExpired(f))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,r)=>n+r.size,0),f=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:f[0],newestEntry:f[f.length-1]}}export(){let i={};for(let[t,f]of this.cache.entries())i[t]={value:f.value,timestamp:f.timestamp.toISOString(),ttl:f.ttl,hits:f.hits,size:f.size};return i}import(i){this.cache.clear();for(let[t,f]of Object.entries(i))if(typeof f==="object"&&f!==null){let n=f;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class hw{metrics=[];maxMetrics=1000;async track(i,t,f={}){let n=performance.now(),r=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:r,...f}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:r,...f}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((r)=>r.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let f=t.map((r)=>r.duration),n=f.reduce((r,c)=>r+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...f),maxDuration:Math.max(...f),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var On=new uw,Z0=new hw,AA=Object.defineProperty,TA=(i)=>i;function EA(i,t){this[i]=TA.bind(null,t)}var YA=(i,t)=>{for(var f in t)AA(i,f,{get:t[f],enumerable:!0,configurable:!0,set:EA.bind(t,f)})},BA=(i,t)=>()=>(i&&(t=i(i=0)),t),$w={};YA($w,{withErrorRecovery:()=>Ew,tryLoadConfig:()=>qA,loadConfigWithResult:()=>HA,loadConfig:()=>jw,isRetryableError:()=>zA,isConfigNotFoundError:()=>_A,isBunfigError:()=>Yw,globalPerformanceMonitor:()=>Qf,globalCache:()=>vt,getEnvOrDefault:()=>QA,generateConfigTypes:()=>LA,defaultGeneratedDir:()=>Fw,defaultConfigDir:()=>Jw,deepMergeWithArrayStrategy:()=>tc,deepMerge:()=>Bw,createLibraryConfig:()=>xA,config:()=>eA,bunfigPlugin:()=>gA,applyEnvVarsToConfig:()=>Sf,TypeGenerationError:()=>x0,SchemaValidationError:()=>_f,PluginError:()=>k0,PerformanceMonitor:()=>p0,FileSystemError:()=>L0,ErrorFactory:()=>mt,EnvVarError:()=>Ln,EnvProcessor:()=>bn,ConfigValidator:()=>fc,ConfigValidationError:()=>e0,ConfigNotFoundError:()=>qn,ConfigMergeError:()=>q0,ConfigLoader:()=>nc,ConfigLoadError:()=>If,ConfigFileLoader:()=>Pn,ConfigCache:()=>v0,CacheUtils:()=>Rw,BunfigError:()=>Si,BrowserConfigError:()=>g0,ArrayMergeStrategies:()=>Nw});class v0{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 f=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${f}`}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(([,f],[,n])=>f.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let f=0;f<t;f++)this.cache.delete(i[f][0])}set(i,t,f,n){if(!this.options.enabled)return;let r=this.generateKey(i,f),c=n??this.options.ttl,l=this.estimateSize(t);this.cache.set(r,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let f=this.generateKey(i,t),n=this.cache.get(f);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(f),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!ry(i))return!0;return cy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let f=this.get(i,t);if(!f)return;if(this.isFileModified(t,f.fileTimestamp)){this.delete(i,t);return}return f.value}setWithFileCheck(i,t,f,n){try{let r=ry(f)?cy(f):null,c=r?r.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},f,n)}catch{this.set(i,t,f,n)}}delete(i,t){let f=this.generateKey(i,t);return this.cache.delete(f)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,f]of this.cache.entries())if(this.isExpired(f))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,r)=>n+r.size,0),f=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:f[0],newestEntry:f[f.length-1]}}export(){let i={};for(let[t,f]of this.cache.entries())i[t]={value:f.value,timestamp:f.timestamp.toISOString(),ttl:f.ttl,hits:f.hits,size:f.size};return i}import(i){this.cache.clear();for(let[t,f]of Object.entries(i))if(typeof f==="object"&&f!==null){let n=f;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class p0{metrics=[];maxMetrics=1000;async track(i,t,f={}){let n=performance.now(),r=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:r,...f}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:r,...f}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((r)=>r.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let f=t.map((r)=>r.duration),n=f.reduce((r,c)=>r+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...f),maxDuration:Math.max(...f),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function CA(i,t={}){let f=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return f?`${i}:${f}`:i}function UA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function jA(i){return i.getStats().size*2}function o0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&s(t[0])&&"id"in t[0]&&t[0].id===3&&s(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(s(t)&&s(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(s(i)&&"arr"in i&&Array.isArray(i.arr)&&s(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&s(t[0])&&s(i[0])){let n=[...t];for(let r of i)if(s(r)&&"name"in r){if(!n.find((c)=>s(c)&&("name"in c)&&c.name===r.name))n.push(r)}else if(s(r)&&"path"in r){if(!n.find((c)=>s(c)&&("path"in c)&&c.path===r.path))n.push(r)}else if(!n.some((c)=>Gn(c,r)))n.push(r);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}if(!s(t)||!s(i))return t;let f={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(r===null||r===void 0)continue;else if(s(r)&&s(f[n]))f[n]=o0(f[n],r);else if(Array.isArray(r)&&Array.isArray(f[n]))if(r.length>0&&f[n].length>0&&s(r[0])&&s(f[n][0])){let c=[...r];for(let l of f[n])if(s(l)&&"name"in l){if(!c.find((y)=>s(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(s(l)&&"path"in l){if(!c.find((y)=>s(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Gn(y,l)))c.push(l);f[n]=c}else if(r.every((c)=>typeof c==="string")&&f[n].every((c)=>typeof c==="string")){let c=[...r];for(let l of f[n])if(!c.includes(l))c.push(l);f[n]=c}else f[n]=r;else f[n]=r}return f}function Gn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!Gn(i[f],t[f]))return!1;return!0}if(s(i)&&s(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!Gn(i[r],t[r]))return!1}return!0}return!1}function s(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function mA(i,t){if(!ww(i))return null;try{let f=await import(i),n=f.default||f;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return o0(t,n)}catch{return null}}catch{return null}}async function RA({name:i="",cwd:t,defaultConfig:f}){let n=t||O0.cwd(),r=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of r){let w=Qn(n,`${l}${y}`),u=await mA(w,f);if(u!==null)return u}try{let l=Qn(n,"package.json");if(ww(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(f,y)}catch{}}}catch{}return f}function WA(i,t={}){let f=zn.cwd();while(f.includes("storage"))f=wy(f,"..");let n=wy(f,i||"");if(t?.relative)return M1(zn.cwd(),n);return n}async function XA(){try{let i=await RA({name:"clarity",defaultConfig:Nn,cwd:zn.cwd(),endpoint:"",headers:{}});return{...Nn,...i}}catch{return Nn}}function b(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function NA(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let i=ft.type;if(i==="renderer"||i==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class Aw{async format(i){let t=await NA(),f=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:f})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:kt.pid,hostname:t(),environment:kt.env.NODE_ENV||"development",platform:kt.platform,version:kt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:kt.env.NODE_ENV||kt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class an{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={...a0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Aw,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??wi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let f={...t},n=t.timestamp!==void 0;if(n)delete f.timestamp;if(this.config={...this.config,...f,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),c=this.generateKey();this.currentKeyId=r,this.keys.set(r,c),this.encryptionKeys.set(r,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Sn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Sn};return{...Sn,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:a0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},f={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!f.level||!["debug","info","success","warning","error"].includes(f.level))f.level=t.level;return f}async writeToFile(i){let t=(async()=>{let n,r=0,c=3,l=1000;while(r<c)try{try{try{await e1(this.config.logDirectory,Ay.F_OK|Ay.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await q1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Ut.from(i);try{if(!T0(this.currentLogFile))await E0(this.currentLogFile,"",{mode:420});if(n=$y(this.currentLogFile,"a",420),H1(n,y,{flag:"a"}),hy(n),n!==void 0)A0(n),n=void 0;if((await xt(this.currentLogFile)).size===0){if(await E0(this.currentLogFile,y,{flag:"w",mode:420}),(await xt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(r<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${r+1}/${c}:`,h);let $=l*2**r;await new Promise((A)=>setTimeout(A,$)),r++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{A0(n)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(r===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}r++;let w=l*2**(r-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let f=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(f,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 gt(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 gt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return gt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,f=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),f=this.generateKey();this.currentKeyId=t,this.keys.set(t,f),this.encryptionKeys.set(t,{key:f,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),r=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,r);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return $0(16).toString("hex")}generateKey(){return $0(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(),f=$0(16),n=O1("aes-256-gcm",t,f),r=Ut.concat([n.update(i,"utf8"),n.final()]),c=n.getAuthTag();return{encrypted:Ut.concat([f,r,c]),iv:f}}async compressData(i){return new Promise((t,f)=>{let n=Ey(),r=[];n.on("data",(c)=>r.push(c)),n.on("end",()=>t(Ut.from(Ut.concat(r)))),n.on("error",f),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(b())return;let i=await xt(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 f=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await yn(this.config.logDirectory),c=r.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${f}.${l}`;if(await xt(f).catch(()=>null))try{if(await Ty(f,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await wn(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!r.some((w)=>w.endsWith(".log.1")))try{let w=`${f}.1`;await E0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),c=f.replace(/\.log$/,`-${r}.log`);if(await xt(f).catch(()=>null))await Ty(f,c)}if(this.currentLogFile=n,t.maxFiles){let r=(await yn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of r.slice(t.maxFiles))await wn(gt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let f=uy(i),n=a1(t),r=Ey();await L1(f,r,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let f of this.logBuffer){let n=await this.formatter.format(f);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 f={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(f)}}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()})),T0(this.currentLogFile))try{let i=$y(this.currentLogFile,"r+");hy(i),A0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await yn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await wn(gt(this.config.logDirectory,t))}catch(f){console.error(`Failed to delete temp file ${t}:`,f)}}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?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:f="",tag:n="",message:r,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(f)T.push(f.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(r),T.join(" ")}let w=wi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${f} ${r}`;else if(c==="info"||c==="success")u=`${f} ${n} ${r}`;else u=`${f} ${n} ${k.cyan(r)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let f=/%([sdijfo%])/g,n=0,r=i.replace(f,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)r+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return r}async log(i,t,...f){let n=new Date,r=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,f);if(this.fancy&&!b()){let u=Ww[i],h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:k.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:k.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
6
+ `);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:r,message:k.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let w=`${c} ${this.environment}.${i.toUpperCase()}: ${l}
7
+ `;if(y)w+=`${y}
8
+ `;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!b()){let f=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:k.blue("◐"),tag:f,message:`${k.cyan(i)}...`}))}return async(f)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),c=`${i} completed in ${r}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(f)w+=` ${JSON.stringify(f)}`;if(w+=`
9
+ `,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let u=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:k.green("✓"),tag:u,message:`${c}${f?` ${JSON.stringify(f)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,f=new an(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(f),f}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!T0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uy(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 f=this.keys.get(this.currentKeyId);try{let n=Ut.isBuffer(i)?i:Ut.from(i,"base64"),r=n.slice(0,16),c=n.slice(-16),l=n.slice(16,-16),y=G1("aes-256-gcm",f,r);return y.setAuthTag(c),Ut.concat([y.update(l),y.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 b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,f=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!b()){let c=i.split(`
10
+ `),l=Math.max(...c.map((h)=>h.length))+2,y=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,u=c.map((h)=>{let $=" ".repeat(l-h.length-2);return`│ ${h}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:f,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:f,message:k.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:f,message:k.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:f,message:k.cyan(w),showTimestamp:!1}))}else if(!b())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let r=`${n} ${this.environment}.INFO: [BOX] ${i}
11
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}async prompt(i){if(b())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${k.cyan("?")} ${i} (y/n) `);let f=(n)=>{let r=n.toString().trim().toLowerCase();wi.stdin.removeListener("data",f);try{if(typeof wi.stdin.setRawMode==="function")wi.stdin.setRawMode(!1)}catch{}wi.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof wi.stdin.setRawMode==="function")wi.stdin.setRawMode(!0)}catch{}wi.stdin.resume(),wi.stdin.once("data",f)})}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 f=i;if(t&&t.length>0){let r=/%([sdijfo%])/g,c=0;if(f=i.replace(r,(l,y)=>{if(y==="%")return"%";if(c>=t.length)return l;let w=t[c++];switch(y){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),c<t.length)f+=` ${t.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!b()){let r=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",c=k.blue("◐");console.error(`${c} ${r} ${k.cyan(f)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
12
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let f=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:f,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,n)),r!==void 0)this.activeProgressBar.message=r;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())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,r="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;wi.stdout.write(`${"\r".padEnd(wi.stdout.columns||80)}\r`),this.log(r,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!wi.stdout.isTTY)return;let f=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*f/100),r=i.barLength-n,c=k.green("━".repeat(n)),l=k.gray("━".repeat(r)),y=`[${c}${l}]`,w=`${f}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||f===100?k.green("✓"):k.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=wi.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,wi.stdout.write(i.lastRenderedLine),t)wi.stdout.write(`
13
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!wi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await yn(this.config.logDirectory),f=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let r=gt(this.config.logDirectory,n);if(i.before)try{if((await xt(r)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${r}:`,c);continue}f.push(r)}if(f.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${f.length} log file(s)...`);for(let n of f)try{await wn(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Xn(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&L(t[0])&&"id"in t[0]&&t[0].id===3&&L(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(L(t)&&L(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(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&L(t[0])&&L(i[0])){let n=[...t];for(let r of i)if(L(r)&&"name"in r){if(!n.find((c)=>L(c)&&("name"in c)&&c.name===r.name))n.push(r)}else if(L(r)&&"path"in r){if(!n.find((c)=>L(c)&&("path"in c)&&c.path===r.path))n.push(r)}else if(!n.some((c)=>Hn(c,r)))n.push(r);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}if(!L(t)||!L(i))return t;let f={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(r===null||r===void 0)continue;else if(L(r)&&L(f[n]))f[n]=Xn(f[n],r);else if(Array.isArray(r)&&Array.isArray(f[n]))if(r.length>0&&f[n].length>0&&L(r[0])&&L(f[n][0])){let c=[...r];for(let l of f[n])if(L(l)&&"name"in l){if(!c.find((y)=>L(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(L(l)&&"path"in l){if(!c.find((y)=>L(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Hn(y,l)))c.push(l);f[n]=c}else if(r.every((c)=>typeof c==="string")&&f[n].every((c)=>typeof c==="string")){let c=[...r];for(let l of f[n])if(!c.includes(l))c.push(l);f[n]=c}else f[n]=r;else f[n]=r}return f}function ic(i,t,f="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return f==="replace"?t:Xn(i,t);if(Array.isArray(i))return f==="replace"?t:Xn(i,t);if(!L(t)||!L(i))return t;let n={...i};for(let r of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let c=t[r],l=n[r];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(f==="replace")n[r]=c;else n[r]=Xn(l,c);else if(L(c)&&L(l))n[r]=ic(l,c,f);else n[r]=c}return n}function Hn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!Hn(i[f],t[f]))return!1;return!0}if(L(i)&&L(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!Hn(i[r],t[r]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function jn(i,t,f="replace"){if(!yw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ic(t,r,f)}catch{return null}}catch{return null}}function SA(i,t,f=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),r={...t};function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${n}_${$.map(A).join("_")}`,C=`${n}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(f)hi.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let E=Kf.env[T]||Kf.env[C];if(E!==void 0){if(f)hi.info(`Using environment variable ${E?T:C} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(E);else if(typeof h==="boolean")w[u]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let B=JSON.parse(E);if(Array.isArray(B))w[u]=B;else w[u]=E.split(",").map((U)=>U.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(r)}async function JA({name:i="",alias:t,cwd:f,configDir:n,defaultConfig:r,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof r==="object"&&r!==null&&!Array.isArray(r)?SA(i,r,c):r,u=f||Kf.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)hi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Yi(u,"config"),Yi(u,".config"),n?Yi(u,n):void 0].filter(Boolean)));for(let B of E){if(c)hi.info(`Searching for configuration in: ${B}`);let U=[Yi(u,"config"),Yi(u,".config")].concat(n?[Yi(u,n)]:[]).includes(B)?[...$,...A,...T,...C]:[...A,...$,...C,...T];for(let R of U)for(let N of h){let J=Yi(B,`${R}${N}`),I=await jn(J,w,y);if(I!==null){if(c)hi.success(`Configuration loaded from: ${J}`);return I}}}if(i){let B=Yi(h0(),".config",i),U=["config",`${i}.config`];if(t)U.push(`${t}.config`);if(c)hi.info(`Checking user config directory: ${B}`);for(let R of U)for(let N of h){let J=Yi(B,`${R}${N}`),I=await jn(J,w,y);if(I!==null){if(c)hi.success(`Configuration loaded from user config directory: ${J}`);return I}}}if(i){let B=Yi(h0(),".config"),U=[`.${i}.config`];if(t)U.push(`.${t}.config`);if(c)hi.info(`Checking user config directory for dotfile configs: ${B}`);for(let R of U)for(let N of h){let J=Yi(B,`${R}${N}`),I=await jn(J,w,y);if(I!==null){if(c)hi.success(`Configuration loaded from user config directory dotfile: ${J}`);return I}}}if(i){let B=h0(),U=[`.${i}.config`,`.${i}`];if(t)U.push(`.${t}.config`),U.push(`.${t}`);if(c)hi.info(`Checking user home directory for dotfile configs: ${B}`);for(let R of U)for(let N of h){let J=Yi(B,`${R}${N}`),I=await jn(J,w,y);if(I!==null){if(c)hi.success(`Configuration loaded from user home directory: ${J}`);return I}}}try{let B=Yi(u,"package.json");if(yw(B)){let U=await import(B),R=U[i];if(!R&&t){if(R=U[t],R&&c)hi.success(`Using alias "${t}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(c)hi.success(`Configuration loaded from package.json: ${R===U[i]?i:t}`);return ic(w,R,y)}catch(N){if(c)hi.warn("Failed to merge package.json config:",N)}}}catch(B){if(c)hi.warn("Failed to load package.json:",B)}if(c)hi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function FA(i,t={}){let f=_n.cwd();while(f.includes("storage"))f=yy(f,"..");let n=yy(f,i||"");if(t?.relative)return z1(_n.cwd(),n);return n}async function KA(){try{let i=await JA({name:"clarity",alias:"logging",defaultConfig:Jn,cwd:_n.cwd()});return{...Jn,...i||{}}}catch{return Jn}}function p(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function IA(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nt<"u"){let i=nt.type;if(i==="renderer"||i==="worker")return!1;return!!(nt.versions&&(nt.versions.node||nt.versions.bun))}return!1}class Tw{async format(i){let t=await IA(),f=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:f})}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 en{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={...H0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Tw,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??e.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let f={...t},n=t.timestamp!==void 0;if(n)delete f.timestamp;if(this.config={...this.config,...f,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),c=this.generateKey();this.currentKeyId=r,this.keys.set(r,c),this.encryptionKeys.set(r,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},f=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[f]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Fn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Fn};return{...Fn,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:H0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},f={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!f.level||!["debug","info","success","warning","error"].includes(f.level))f.level=t.level;return f}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,r=0,c=3,l=1000;while(r<c)try{try{try{await s1(this.config.logDirectory,Uy.F_OK|Uy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await D1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:oi.from(i);try{if(!un(this.currentLogFile))await C0(this.currentLogFile,"",{mode:420});if(n=Cy(this.currentLogFile,"a",420),V1(n,y,{flag:"a"}),By(n),n!==void 0)B0(n),n=void 0;if((await Vt(this.currentLogFile)).size===0){if(await C0(this.currentLogFile,y,{flag:"w",mode:420}),(await Vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(r<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${r+1}/${c}:`,h);let $=l*2**r;await new Promise((A)=>setTimeout(A,$)),r++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{B0(n)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(r===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}r++;let w=l*2**(r-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let f=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(f,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 st(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 st(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return st(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(p())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,f=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),f=this.generateKey();this.currentKeyId=t,this.keys.set(t,f),this.encryptionKeys.set(t,{key:f,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),r=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,r);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Y0(16).toString("hex")}generateKey(){return Y0(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(),f=Y0(16),n=x1("aes-256-gcm",t,f),r=oi.isBuffer(i)?i:oi.from(i,"utf8"),c=n.update(r),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=oi.allocUnsafe(16+y+16);return f.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:f}}async compressData(i){return new Promise((t,f)=>{let n=my(),r=[];n.on("data",(c)=>r.push(c)),n.on("end",()=>t(oi.from(oi.concat(r)))),n.on("error",f),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(p())return;if(!this.shouldWriteToFile())return;let i=await Vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let f=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await hn(this.config.logDirectory),c=r.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${f}.${l}`;if(await Vt(f).catch(()=>null))try{if(await jy(f,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await $n(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!r.some((w)=>w.endsWith(".log.1")))try{let w=`${f}.1`;await C0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),c=f.replace(/\.log$/,`-${r}.log`);if(await Vt(f).catch(()=>null))await jy(f,c)}if(this.currentLogFile=n,t.maxFiles){let r=(await hn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of r.slice(t.maxFiles))await $n(st(this.config.logDirectory,c))}}}async compressLogFile(i,t){let f=Yy(i),n=k1(t),r=my();await P1(f,r,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let f of this.logBuffer){let n=await this.formatter.format(f);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()})),un(this.currentLogFile))try{let i=Cy(this.currentLogFile,"r+");By(i),B0(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(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await hn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await $n(st(this.config.logDirectory,t))}catch(f){console.error(`Failed to delete temp file ${t}:`,f)}}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||p())return!1;let i=typeof e.env.NO_COLOR<"u",t=e.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof e.stderr<"u"&&e.stderr.isTTY||typeof e.stdout<"u"&&e.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:f="",tag:n="",message:r,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(f)T.push(f.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(r),T.join(" ")}let w=e.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${f} ${r}`;else if(c==="info"||c==="success")u=`${f} ${n} ${r}`;else u=`${f} ${n} ${O.cyan(r)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let f=/%([sdijfo%])/g,n=0,r=i.replace(f,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)r+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return r}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(f,n,r)=>{let c=O.underline(O.blue(n)),l=this.toAbsoluteFilePath(r);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(f,n)=>O.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(f,n)=>O.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(f,n)=>O.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(f,n)=>O.italic(n)),t=t.replace(/~([^~]+)~/g,(f,n)=>O.strikethrough(n)),t}supportsHyperlinks(){if(p())return!1;let i=e.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 f=e.env.HOME||"";if(f)t=t.replace(/^~(?=$|\/)/,f)}if(d1(t)||t.startsWith("./")||t.startsWith("../"))t=b1(t);else return null;return un(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,f=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:f}}async log(i,t,...f){let n=new Date,r=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,f);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Xw[i],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:O.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:O.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
14
+ `);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:r,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
15
+ `;if(y)h+=`${y}
16
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let f={update:(r,c)=>{},finish:(r)=>{},interrupt:(r,c)=>{}};if(!this.enabled)return f;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&e.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(r,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,r),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!p()&&e.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(r)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,r)},interrupt:(r,c="info")=>{if(!p()&&e.stdout.isTTY)e.stdout.write(`
17
+ `);if(this[c==="warning"?"warn":c](r),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&e.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let f=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:f,message:`${O.cyan(i)}...`}))}return async(f)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),c=`${i} completed in ${r}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(f)w+=` ${JSON.stringify(f)}`;if(w+=`
18
+ `,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":O.green("✓"),tag:u,message:`${c}${f?` ${JSON.stringify(f)}`:""}`}))}else if(!p())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,f=new en(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(f),f}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!un(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Yy(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 f=this.keys.get(this.currentKeyId);try{let n=oi.isBuffer(i)?i:oi.from(i,"base64"),r=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=g1("aes-256-gcm",f,r);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=oi.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.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 p()}isServerMode(){return!p()}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,f=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:r,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=r.split(`
19
+ `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:f,message:O.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:f,message:O.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:f,message:O.cyan(h),showTimestamp:!1}))}else if(!p())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(p())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let f=(n)=>{let r=n.toString().trim().toLowerCase();e.stdin.removeListener("data",f);try{if(typeof e.stdin.setRawMode==="function")e.stdin.setRawMode(!1)}catch{}e.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof e.stdin.setRawMode==="function")e.stdin.setRawMode(!0)}catch{}e.stdin.resume(),e.stdin.once("data",f)})}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 f=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(f=i.replace(l,(w,u)=>{if(u==="%")return"%";if(y>=t.length)return w;let h=t[y++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),y<t.length)f+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:n,fileText:r}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${y}${l} ${O.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
21
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!e.stdout.isTTY)return;let f=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*f/100),r=i.barLength-n,c=O.green("━".repeat(n)),l=O.gray("━".repeat(r)),y=`[${c}${l}]`,w=`${f}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||f===100?O.green("✓"):O.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=e.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,e.stdout.write(i.lastRenderedLine),t)e.stdout.write(`
22
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!e.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(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await hn(this.config.logDirectory),f=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let r=st(this.config.logDirectory,n);if(i.before)try{if((await Vt(r)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${r}:`,c);continue}f.push(r)}if(f.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${f.length} log file(s)...`);for(let n of f)try{await $n(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ew(i,t={}){let{maxRetries:f=3,retryDelay:n=1000,isRetryable:r=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=f;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===f||!r(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Yw(i){return i instanceof Si}function _A(i){return i instanceof qn}function zA(i){if(Yw(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 bn{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,f={}){let{prefix:n,useCamelCase:r=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=f,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:r,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Qf.track("applyEnvironmentVariables",u,{configName:i});return u()}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,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${f}_${y.join("_")}`,u=n.useBackwardCompatibility?`${f}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,f,n);else{let h=An.env[w]||(u?An.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=An.env[w]?w:u}try{i[r]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof Ln)throw $;throw mt.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,f,n,r){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw mt.envVar(f,i,`${t} (via ${c.name} parser)`,r)}return i}getEnvironmentVariables(i){let t={},f=i.toUpperCase();for(let[n,r]of Object.entries(An.env))if(n.startsWith(f)&&r!==void 0)t[n]=r;return t}validateEnvironmentVariable(i,t,f){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(f)try{this.parseEnvironmentValue(i,t,f,{})}catch(r){n.push(`Cannot parse value "${t}" as ${f}: ${r}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,f={}){let{prefix:n,format:r="text"}=f,c=n||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),r){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=`${f}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,f,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}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 f=`Environment Variables for ${t}:
23
+
24
+ `;for(let n of i)f+=`${n.key}
25
+ `,f+=` Type: ${n.type}
26
+ `,f+=` Description: ${n.description}
27
+ `,f+=` Example: ${n.example}
28
+
29
+ `;return f}formatAsMarkdown(i,t){let f=`# Environment Variables for ${t}
30
+
31
+ `;f+=`| Variable | Type | Description | Example |
32
+ `,f+=`|----------|------|-------------|----------|
33
+ `;for(let n of i)f+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
34
+ `;return f}}function QA(i,t){let f=mw("process");if(typeof f>"u"||!f.env)return t;let n=f.env[i];return n!==void 0?n:t}function Bw(i,t,f={}){return Cw(i,t,f,new WeakMap)}function Cw(i,t,f,n){let{arrayMergeMode:r="replace",skipNullish:c=!1,customMerger:l}=f;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Uw(i,t,r,n);if(!Qi(t)||!Qi(i))return t;return aA(i,t,f,n)}function Uw(i,t,f,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(f){case"replace":return t;case"concat":return MA(i,t);case"smart":return OA(i,t,n);default:return t}return t}function MA(i,t){let f=[...t];for(let n of i)if(!f.some((r)=>G0(r,n)))f.push(n);return f}function OA(i,t,f){if(t.length===0)return i;if(i.length===0)return t;if(Qi(t[0])&&Qi(i[0]))return GA(i,t,f);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}function GA(i,t,f){let n=[...t];for(let r of i){if(!Qi(r)){n.push(r);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in r){if(n.find((w)=>Qi(w)&&(y in w)&&w[y]===r[y])){l=!0;break}}if(!l)n.push(r)}return n}function aA(i,t,f,n){let r=t;if(Qi(r)&&n.has(r))return n.get(r);let c={...i};if(Qi(r))n.set(r,c);for(let l in r){if(!Object.prototype.hasOwnProperty.call(r,l))continue;let y=r[l],w=c[l];if(f.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Qi(y)&&Qi(w))c[l]=Cw(w,y,f,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=Uw(w,y,f.arrayMergeMode||"smart",n);else c[l]=y}return c}function tc(i,t,f="replace"){return Bw(i,t,{arrayMergeMode:f==="replace"?"replace":"smart",skipNullish:!0})}function G0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!G0(i[f],t[f]))return!1;return!0}if(Qi(i)&&Qi(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!G0(i[r],t[r]))return!1}return!0}return!1}function Qi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Pn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,f={}){let{arrayStrategy:n="replace",useCache:r=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=f;if(r){let u=vt.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Tn(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new If(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new If(i,Error("Configuration must export a valid object"),"unknown");let C={config:tc(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(r)vt.setWithFileCheck("file",C,i,c);return C}catch(u){throw u instanceof Error?mt.configLoad(i,u):mt.configLoad(i,Error(String(u)))}};if(l)return Qf.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,f={}){for(let n of i)try{let r=await this.loadFromPath(n,t,f);if(r)return r}catch(r){if(r instanceof Error&&r.name==="ConfigLoadError")throw r;if(f.verbose)console.warn(`Failed to load config from ${n}:`,r)}return null}generateConfigPaths(i,t,f){let n=this.generateNamePatterns(i,f),r=[];for(let c of n)for(let l of this.extensions)r.push(U0(t,`${c}${l}`));return r}generateNamePatterns(i,t){let f=[];if(f.push("config",".config"),i)f.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(f.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)f.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return f.filter(Boolean)}checkFileAccess(i){return Ew(async()=>{return Tn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,f){let n=[];if(!Tn(i))return n;if(t||f){let r=this.generateNamePatterns(t||"",f);for(let c of r)for(let l of this.extensions){let y=U0(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:r}=await import("fs"),c=r(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=U0(i,l);if(await this.checkFileAccess(y))n.push(y)}}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(!Tn(i))return t.push("Configuration file does not exist"),t;let f=await import(i),n=f.default||f;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:r}=await import("fs"),c=r(i,"utf8");JSON.parse(c)}catch(r){t.push(`Invalid JSON syntax: ${r}`)}}catch(f){t.push(`Failed to load configuration file: ${f}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let f=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let r=await this.loadFromPath(n,{},t);if(r)f.set(n,r.config)}catch(r){if(t.verbose)console.warn(`Failed to preload ${n}:`,r)}})),f}}class fc{async validateConfiguration(i,t,f={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=f,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,validateRequired:r,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Qf.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,f){try{if(!Z1(t))throw new _f(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),r=n.default||n;if(Array.isArray(r))return this.validateWithRules(i,r,f);else return this.validateWithJSONSchema(i,r,f)}catch(n){throw new _f(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,f){let n=[],r=[];return this.validateObjectAgainstSchema(i,t,"",n,r,f),{isValid:n.length===0,errors:n,warnings:r}}validateObjectAgainstSchema(i,t,f,n,r,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:f,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:f,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:f,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:f,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:f,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:f,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:f,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=f?`${f}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,r,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:f?`${f}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=f?`${f}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,r,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))r.push({path:f?`${f}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,f){let n=[],r=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),f.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:r}}validateWithRule(i,t,f){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:f,message:t.message||`Property '${f}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let r=Array.isArray(i)?"array":typeof i;if(r!==t.type)n.push({path:f,message:t.message||`Expected type ${t.type}, got ${r}`,expected:t.type,actual:r,rule:"type"})}if(t.min!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r<t.min)n.push({path:f,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:r,rule:"min"})}if(t.max!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r>t.max)n.push({path:f,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:r,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:f,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:f,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let r=t.validator(i);if(r)n.push({path:f,message:t.message||r,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let f=t.split("."),n=i;for(let r of f)if(n&&typeof n==="object"&&r in n)n=n[r];else return;return n}generateRulesFromInterface(i){let t=[],f=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of f){let[,r,c,l]=n;t.push({path:r,required:!c,type:this.mapTypeScriptType(l)})}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:Sw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class nc{fileLoader=new Pn;envProcessor=new bn;validator=new fc;async loadConfig(i){let t=Date.now(),{cache:f,performance:n,schema:r,validate:c,...l}=i;try{if(f?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,f)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(r||c)await this.validateConfiguration(y.config,r,c,l.name);if(f?.enabled&&y)this.cacheResult(l.name||"",y,f,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)qi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw qi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,f){let{name:n="",alias:r,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_t.cwd(),A=[],T=await this.loadLocalConfiguration(n,r,$,l,y,u,h,w,f);if(T)return A.push(...this.getLocalSearchPaths(n,r,$,l)),this.finalizeResult(T,A,w,n,h);let C=await this.loadHomeConfiguration(n,r,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(C,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,r,$,y,u,h,w);if(E)return A.push(Bi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,r,$,l)),t)throw mt.configNotFound(n,A,r);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${r?` or alias "${r}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,f,n,r,c,l,y,w){let u=y?Sf(i,r,l):r,h=this.getLocalDirectories(f,n);for(let $ of h){if(l)qi.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)qi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,f,n,r,c){if(!i)return null;let l=c?Sf(i,f,r):f,y=[Bi(Lt(),".config",i),Bi(Lt(),".config"),Lt()];for(let w of y){if(r)qi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:r});if(h){if(r)qi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,f,n,r,c,l){let y=l?Sf(i,n,c):n;try{let w=Bi(f,"package.json");if(!M0(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)qi.success(`Configuration loaded from package.json: ${$}`);return{config:tc(y,h,r),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)qi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,f,n){if(!f||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Sf(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,f,n,r){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,f,n){let r=[];if(f){let c=f(i);if(c)r.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)r.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(r.length>0)throw mt.configValidation(n||"unknown",r,n)}checkCache(i,t){let f=this.generateCacheKey(i,t);return vt.get(f)||null}cacheResult(i,t,f,n){let r=this.generateCacheKey(i,n);vt.set(r,t,void 0,f.ttl)}generateCacheKey(i,t){let f=[i];if(t.alias)f.push(`alias:${t.alias}`);if(t.cwd)f.push(`cwd:${t.cwd}`);if(t.configDir)f.push(`configDir:${t.configDir}`);if("checkEnv"in t)f.push(`checkEnv:${t.checkEnv}`);return f.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Bi(i,"config"),Bi(i,".config"),t?Bi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,f,n){let r=[];return r.push(...this.getLocalSearchPaths(i,t,f,n)),r.push(...this.getHomeSearchPaths(i,t)),r.push(Bi(f,"package.json")),r}getLocalSearchPaths(i,t,f,n){let r=this.getLocalDirectories(f,n),c=[];for(let l of r)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let f=[Bi(Lt(),".config",i),Bi(Lt(),".config"),Lt()],n=[];for(let r of f)n.push(...this.fileLoader.generateConfigPaths(i,r,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function Iy(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")),f=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||f}async function HA(i){return lt.loadConfig({...i,__strictErrorHandling:!0})}async function jw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},f="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(f)n=await lt.loadConfig(i);else n=await lt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let r=n instanceof Error?n.name:"UnknownError",c=n instanceof Error?n.message:String(n);if(!(r==="ConfigNotFoundError"||r==="ConfigLoadError"||r==="ConfigValidationError"||c.includes("config"))&&i.verbose)qi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let l=f?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await lt.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function eA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await lt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(f){if(f instanceof Error&&(f.name==="ConfigNotFoundError"||f.name==="ConfigLoadError"&&Iy(f)))return(await lt.applyEnvironmentVariables(i,{},!0,!1)).config;throw f}}try{return(await lt.loadConfig({...i,cwd:i.cwd||_t.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Iy(t)))return(await lt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function qA(i,t,f="replace"){let n=new Pn;try{let r=await n.loadFromPath(i,t,{arrayStrategy:f,useCache:!1,trackPerformance:!1});return r?r.config:null}catch{return null}}function Sf(i,t,f=!1){let n=new bn,r=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${r}_${$.join("_").toUpperCase()}`,`${r}_${$.map((E)=>E.toUpperCase()).join("")}`,`${r}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=_t.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function LA(i){let t=Bi(_t.cwd(),i.configDir),f=Bi(_t.cwd(),i.generatedDir),n=Bi(f,"config-types.ts");if(!M0(ly(n)))F1(ly(n),{recursive:!0,mode:511});let r=M0(t)?K1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${YT}
35
+ export type ConfigNames = ${r.length?`'${r.join("' | '")}'`:"string"}
36
+ `;I1(n,c,{mode:438})}function xA(i){let t=null,f=null,n=()=>{if(!f)f=jw(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)qi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return f},r="defaultConfig"in i?i.defaultConfig:{};return t=r,n(),new Proxy({},{get(c,l){if(t)return t[l];let y=r[l];return n(),y},has(c,l){return l in(t||r)},ownKeys(){return Object.keys(t||r)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||r,l)},set(c,l,y){if(!t)t={...r};return t[l]=y,!0}})}function gA(i){let t=Ry(o1.cwd(),i?.configDir||"./config");function f(){if(!v1(t))return[];let r=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=p1(t).filter((w)=>r.has(j0(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),y=new Map;for(let{base:w,file:u}of l){let h=j0(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=j0($).toLowerCase();if(c.indexOf(h)<c.indexOf(A))y.set(w,u)}return Array.from(y.entries()).map(([w,u])=>({base:w,file:u})).sort((w,u)=>w.base.localeCompare(u.base))}function n(){let r=f(),c=r.map((w)=>w.base),l=c.length?c.map((w)=>`'${w}'`).join(" | "):"string",y=r.length?`{
37
+ ${r.map((w)=>{let u=Ry(t,w.file).replace(/\\/g,"/");return` '${w.base}': typeof import('${u}').default`}).join(`,
38
+ `)}
39
+ }`:"Record<string, any>";return`export type ConfigNames = ${l}
40
+ export type ConfigByName = ${y}
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(r){r.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),r.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var mw,vt,Qf,Rw,kA,VA,_y,Nn,a0,ui,k,sA,zy,DA,Qy,dA,bA,N0,PA,My,Oy,S0,ZA,vA,pA,oA,Sn,Ww,iT,hi,tT,fT,Gy,Jn,H0,o,O,nT,ay,rT,Hy,cT,lT,J0,yT,ey,qy,wT,F0,uT,hT,$T,AT,TT,Fn,Xw,ET,YT="0.15.6",Si,qn,If,e0,q0,Ln,L0,x0,_f,g0,k0,mt,Nw,Sw,qi,lt,Jw,Fw,BT=BA(async()=>{mw=import.meta.require,vt=new v0,Qf=new p0,Rw={createKey:CA,isEquivalent:UA,estimateMemoryUsage:jA},kA=Qn(O0.cwd(),"config"),VA=Qn(O0.cwd(),"src/generated"),_y=zn.env.CLARITY_LOG_DIR||Q1(WA(),"logs"),Nn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_y,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},a0=await XA(),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"},k=ui,sA=ui.red,zy=ui.green,DA=ui.yellow,Qy=ui.blue,dA=ui.magenta,bA=ui.cyan,N0=ui.white,PA=ui.gray,My=ui.bgRed,Oy=ui.bgYellow,S0=ui.bold,ZA=ui.dim,vA=ui.italic,pA=ui.underline,oA=ui.reset,Sn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ww={debug:"\uD83D\uDD0D",info:Qy("ℹ"),success:zy("✓"),warning:Oy(N0(S0(" WARN "))),error:My(N0(S0(" ERROR ")))},iT=new an("stacks"),hi=new an("bunfig",{showTags:!0}),tT=Yi(Kf.cwd(),"config"),fT=Yi(Kf.cwd(),"src/generated"),Gy=_n.env.CLARITY_LOG_DIR||_1(FA(),"logs"),Jn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},H0=await KA(),o={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=o,nT=o.red,ay=o.green,rT=o.yellow,Hy=o.blue,cT=o.magenta,lT=o.cyan,J0=o.white,yT=o.gray,ey=o.bgRed,qy=o.bgYellow,wT=o.bgGray,F0=o.bold,uT=o.dim,hT=o.italic,$T=o.underline,AT=o.strikethrough,TT=o.reset,Fn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Xw={debug:"\uD83D\uDD0D",info:Hy("ℹ"),success:ay("✓"),warning:qy(J0(F0(" WARN "))),error:ey(J0(F0(" ERROR ")))},ET=new en("stacks"),Si=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,f])=>`${t}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},qn=class extends Si{code="CONFIG_NOT_FOUND";constructor(i,t,f){let n=f?` or alias "${f}"`:"";super(`Configuration "${i}"${n} not found`,{configName:i,alias:f,searchPaths:t,searchPathCount:t.length})}},If=class extends Si{code="CONFIG_LOAD_ERROR";constructor(i,t,f){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:f,originalError:t.name,originalMessage:t.message});this.cause=t}},e0=class extends Si{code="CONFIG_VALIDATION_ERROR";constructor(i,t,f){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:f,validationErrors:t,errorCount:t.length})}},q0=class extends Si{code="CONFIG_MERGE_ERROR";constructor(i,t,f,n){super(`Failed to merge configuration from "${i}" with "${t}": ${f.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:f.name,originalMessage:f.message});this.cause=f}},Ln=class extends Si{code="ENV_VAR_ERROR";constructor(i,t,f,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${f}`,{envKey:i,envValue:t,expectedType:f,configName:n})}},L0=class extends Si{code="FILE_SYSTEM_ERROR";constructor(i,t,f){super(`File system ${i} failed for "${t}": ${f.message}`,{operation:i,path:t,originalError:f.name,originalMessage:f.message});this.cause=f}},x0=class extends Si{code="TYPE_GENERATION_ERROR";constructor(i,t,f){super(`Failed to generate types from "${i}" to "${t}": ${f.message}`,{configDir:i,outputPath:t,originalError:f.name,originalMessage:f.message});this.cause=f}},_f=class extends Si{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:i,configName:f,validationErrors:t,errorCount:t.length})}},g0=class extends Si{code="BROWSER_CONFIG_ERROR";constructor(i,t,f,n){super(`Failed to fetch configuration from "${i}": ${t} ${f}`,{endpoint:i,status:t,statusText:f,configName:n})}},k0=class extends Si{code="PLUGIN_ERROR";constructor(i,t,f){super(`Plugin "${i}" failed during ${t}: ${f.message}`,{pluginName:i,operation:t,originalError:f.name,originalMessage:f.message});this.cause=f}},mt={configNotFound(i,t,f){return new qn(i,t,f)},configLoad(i,t,f){return new If(i,t,f)},configValidation(i,t,f){return new e0(i,t,f)},configMerge(i,t,f,n){return new q0(i,t,f,n)},envVar(i,t,f,n){return new Ln(i,t,f,n)},fileSystem(i,t,f){return new L0(i,t,f)},typeGeneration(i,t,f){return new x0(i,t,f)},schemaValidation(i,t,f){return new _f(i,t,f)},browserConfig(i,t,f,n){return new g0(i,t,f,n)},plugin(i,t,f){return new k0(i,t,f)}},Nw={replace:"replace",concat:"concat",smart:"smart"},Sw=/^https?:\/\//,qi=new en("bunfig",{showTags:!0}),lt=new nc,Jw=Bi(_t.cwd(),"config"),Fw=Bi(_t.cwd(),"src/generated")});function CT(i,t={}){let f=Mn.cwd();while(f.includes("storage"))f=Wy(f,"..");let n=Wy(f,i||"");if(t?.relative)return tA(Mn.cwd(),n);return n}var UT=Mn.env.CLARITY_LOG_DIR||iA(CT(),"logs"),Kw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:UT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xn={...Kw},Rm=(async()=>{try{let{loadConfig:i}=await BT().then(()=>$w),t=await i({name:"clarity",alias:"logging",defaultConfig:Kw,cwd:Mn.cwd()});if(t)Object.assign(xn,t)}catch{}return xn})();function ii(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jT(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rt<"u"){let i=rt.type;if(i==="renderer"||i==="worker")return!1;return!!(rt.versions&&(rt.versions.node||rt.versions.bun))}return!1}class Iw{async format(i){let t=await jT(),f=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:f})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Pt.pid,hostname:t(),environment:Pt.env.NODE_ENV||"development",platform:Pt.platform,version:Pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pt.env.NODE_ENV||Pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var 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"},a=ri,Wm=ri.red,mT=ri.green,Xm=ri.yellow,RT=ri.blue,Nm=ri.magenta,Sm=ri.cyan,Ly=ri.white,Jm=ri.gray,WT=ri.bgRed,XT=ri.bgYellow,Fm=ri.bgGray,xy=ri.bold,Km=ri.dim,Im=ri.italic,_m=ri.underline,zm=ri.strikethrough,Qm=ri.reset,K0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},NT={debug:"\uD83D\uDD0D",info:RT("ℹ"),success:mT("✓"),warning:XT(Ly(xy(" WARN "))),error:WT(Ly(xy(" ERROR ")))};class Zn{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 Iw,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??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let f={...t},n=t.timestamp!==void 0;if(n)delete f.timestamp;if(this.config={...this.config,...f,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),c=this.generateKey();this.currentKeyId=r,this.keys.set(r,c),this.encryptionKeys.set(r,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},f=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[f]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...K0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...K0};return{...K0,...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},f={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!f.level||!["debug","info","success","warning","error"].includes(f.level))f.level=t.level;return f}shouldWriteToFile(){return!ii()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,r=0,c=3,l=1000;while(r<c)try{try{try{await lA(this.config.logDirectory,Jy.F_OK|Jy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await yA(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:it.from(i);try{if(!En(this.currentLogFile))await W0(this.currentLogFile,"",{mode:420});if(n=Sy(this.currentLogFile,"a",420),cA(n,y,{flag:"a"}),Ny(n),n!==void 0)R0(n),n=void 0;if((await dt(this.currentLogFile)).size===0){if(await W0(this.currentLogFile,y,{flag:"w",mode:420}),(await dt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(r<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${r+1}/${c}:`,h);let $=l*2**r;await new Promise((A)=>setTimeout(A,$)),r++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{R0(n)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(r===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}r++;let w=l*2**(r-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let f=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(f,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 bt(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 bt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return bt(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,f=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),f=this.generateKey();this.currentKeyId=t,this.keys.set(t,f),this.encryptionKeys.set(t,{key:f,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),r=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,r);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return m0(16).toString("hex")}generateKey(){return m0(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(),f=m0(16),n=fA("aes-256-gcm",t,f),r=it.isBuffer(i)?i:it.from(i,"utf8"),c=n.update(r),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=it.allocUnsafe(16+y+16);return f.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:f}}async compressData(i){return new Promise((t,f)=>{let n=Ky(),r=[];n.on("data",(c)=>r.push(c)),n.on("end",()=>t(it.from(it.concat(r)))),n.on("error",f),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 dt(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 f=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await Yn(this.config.logDirectory),c=r.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${f}.${l}`;if(await dt(f).catch(()=>null))try{if(await Fy(f,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await Bn(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!r.some((w)=>w.endsWith(".log.1")))try{let w=`${f}.1`;await W0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),c=f.replace(/\.log$/,`-${r}.log`);if(await dt(f).catch(()=>null))await Fy(f,c)}if(this.currentLogFile=n,t.maxFiles){let r=(await Yn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of r.slice(t.maxFiles))await Bn(bt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let f=Xy(i),n=rA(t),r=Ky();await hA(f,r,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let f of this.logBuffer){let n=await this.formatter.format(f);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()})),En(this.currentLogFile))try{let i=Sy(this.currentLogFile,"r+");Ny(i),R0(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 Yn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Bn(bt(this.config.logDirectory,t))}catch(f){console.error(`Failed to delete temp file ${t}:`,f)}}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()?a.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ii())return!1;let i=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:f="",tag:n="",message:r,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(f)T.push(f.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(r),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${f} ${r}`;else if(c==="info"||c==="success")u=`${f} ${n} ${r}`;else u=`${f} ${n} ${a.cyan(r)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let f=/%([sdijfo%])/g,n=0,r=i.replace(f,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)r+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return r}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(f,n,r)=>{let c=a.underline(a.blue(n)),l=this.toAbsoluteFilePath(r);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(f,n)=>a.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(f,n)=>a.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(f,n)=>a.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(f,n)=>a.italic(n)),t=t.replace(/~([^~]+)~/g,(f,n)=>a.strikethrough(n)),t}supportsHyperlinks(){if(ii())return!1;let i=q.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 f=q.env.HOME||"";if(f)t=t.replace(/^~(?=$|\/)/,f)}if(wA(t)||t.startsWith("./")||t.startsWith("../"))t=uA(t);else return null;return En(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,f=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:f}}async log(i,t,...f){if(!this.shouldLog(i))return;let n=new Date,r=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,f);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":NT[i],A=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:a.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:a.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
44
+ `);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:r,message:a.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ii()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
45
+ `;if(y)h+=`${y}
46
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let f={update:(r,c)=>{},finish:(r)=>{},interrupt:(r,c)=>{}};if(!this.enabled)return f;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ii()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(r,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,r),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!ii()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(r)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,r)},interrupt:(r,c="info")=>{if(!ii()&&q.stdout.isTTY)q.stdout.write(`
47
+ `);if(this[c==="warning"?"warn":c](r),this.activeProgressBar&&this.shouldStyleConsole()&&!ii()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":a.blue("◐"),tag:f,message:`${a.cyan(i)}...`}))}return async(f)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),c=`${i} completed in ${r}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(f)w+=` ${JSON.stringify(f)}`;if(w+=`
48
+ `,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":a.green("✓"),tag:u,message:`${c}${f?` ${JSON.stringify(f)}`:""}`}))}else if(!ii())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,f=new Zn(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(f),f}createReadStream(){if(ii())throw Error("createReadStream is not supported in browser environments");if(!En(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xy(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 f=this.keys.get(this.currentKeyId);try{let n=it.isBuffer(i)?i:it.from(i,"base64"),r=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=nA("aes-256-gcm",f,r);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=it.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.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,f=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:r,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=r.split(`
49
+ `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:f,message:a.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:f,message:a.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:f,message:a.cyan(h),showTimestamp:!1}))}else if(!ii())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ii())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${a.cyan("?")} ${i} (y/n) `);let f=(n)=>{let r=n.toString().trim().toLowerCase();q.stdin.removeListener("data",f);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",f)})}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 f=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(f=i.replace(l,(w,u)=>{if(u==="%")return"%";if(y>=t.length)return w;let h=t[y++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),y<t.length)f+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:n,fileText:r}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${a.blue("◐")} `;console.error(`${y}${l} ${a.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
51
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let f=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*f/100),r=i.barLength-n,c=a.green("━".repeat(n)),l=a.gray("━".repeat(r)),y=`[${c}${l}]`,w=`${f}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||f===100?a.green("✓"):a.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=q.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
52
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ii()||!q.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 Yn(this.config.logDirectory),f=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let r=bt(this.config.logDirectory,n);if(i.before)try{if((await dt(r)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${r}:`,c);continue}f.push(r)}if(f.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${f.length} log file(s)...`);for(let n of f)try{await Bn(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Mm=new Zn("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,f])=>`${t}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class _w extends gi{code="CONFIG_NOT_FOUND";constructor(i,t,f){let n=f===void 0?[]:Array.isArray(f)?f.filter(Boolean):[f],r="";if(n.length===1)r=` or alias "${n[0]}"`;else if(n.length>1)r=` or aliases ${n.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${r} not found`,{configName:i,alias:f,searchPaths:t,searchPathCount:t.length})}}class gn extends gi{code="CONFIG_LOAD_ERROR";constructor(i,t,f){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:f,originalError:t.name,originalMessage:t.message});this.cause=t}}class zw extends gi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,f){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:f,validationErrors:t,errorCount:t.length})}}class Qw extends gi{code="CONFIG_MERGE_ERROR";constructor(i,t,f,n){super(`Failed to merge configuration from "${i}" with "${t}": ${f.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:f.name,originalMessage:f.message});this.cause=f}}class rc extends gi{code="ENV_VAR_ERROR";constructor(i,t,f,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${f}`,{envKey:i,envValue:t,expectedType:f,configName:n})}}class Mw extends gi{code="FILE_SYSTEM_ERROR";constructor(i,t,f){super(`File system ${i} failed for "${t}": ${f.message}`,{operation:i,path:t,originalError:f.name,originalMessage:f.message});this.cause=f}}class Ow extends gi{code="TYPE_GENERATION_ERROR";constructor(i,t,f){super(`Failed to generate types from "${i}" to "${t}": ${f.message}`,{configDir:i,outputPath:t,originalError:f.name,originalMessage:f.message});this.cause=f}}class kn extends gi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:i,configName:f,validationErrors:t,errorCount:t.length})}}class Gw extends gi{code="BROWSER_CONFIG_ERROR";constructor(i,t,f,n){super(`Failed to fetch configuration from "${i}": ${t} ${f}`,{endpoint:i,status:t,statusText:f,configName:n})}}class aw extends gi{code="PLUGIN_ERROR";constructor(i,t,f){super(`Plugin "${i}" failed during ${t}: ${f.message}`,{pluginName:i,operation:t,originalError:f.name,originalMessage:f.message});this.cause=f}}var pt={configNotFound(i,t,f){return new _w(i,t,f)},configLoad(i,t,f){return new gn(i,t,f)},configValidation(i,t,f){return new zw(i,t,f)},configMerge(i,t,f,n){return new Qw(i,t,f,n)},envVar(i,t,f,n){return new rc(i,t,f,n)},fileSystem(i,t,f){return new Mw(i,t,f)},typeGeneration(i,t,f){return new Ow(i,t,f)},schemaValidation(i,t,f){return new kn(i,t,f)},browserConfig(i,t,f,n){return new Gw(i,t,f,n)},plugin(i,t,f){return new aw(i,t,f)}};async function ST(i,t={}){let{maxRetries:f=3,retryDelay:n=1000,isRetryable:r=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=f;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===f||!r(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class cc{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,f={}){let{prefix:n,useCamelCase:r=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=f,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:r,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Z0.track("applyEnvironmentVariables",u,{configName:i});return u()}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,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${f}_${y.join("_")}`,u=n.useBackwardCompatibility?`${f}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,f,n);else{let h=Cn.env[w]||(u?Cn.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=Cn.env[w]?w:u}try{i[r]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof rc)throw $;throw pt.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,f,n,r){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw pt.envVar(f,i,`${t} (via ${c.name} parser)`,r)}return i}getEnvironmentVariables(i){let t={},f=i.toUpperCase();for(let[n,r]of Object.entries(Cn.env))if(n.startsWith(f)&&r!==void 0)t[n]=r;return t}validateEnvironmentVariable(i,t,f){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(f)try{this.parseEnvironmentValue(i,t,f,{})}catch(r){n.push(`Cannot parse value "${t}" as ${f}: ${r}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,f={}){let{prefix:n,format:r="text"}=f,c=n||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),r){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=`${f}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,f,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}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 f=`Environment Variables for ${t}:
53
+
54
+ `;for(let n of i)f+=`${n.key}
55
+ `,f+=` Type: ${n.type}
56
+ `,f+=` Description: ${n.description}
57
+ `,f+=` Example: ${n.example}
58
+
59
+ `;return f}formatAsMarkdown(i,t){let f=`# Environment Variables for ${t}
60
+
61
+ `;f+=`| Variable | Type | Description | Example |
62
+ `,f+=`|----------|------|-------------|----------|
63
+ `;for(let n of i)f+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
64
+ `;return f}}function JT(i,t,f={}){return Hw(i,t,f,new WeakMap)}function Hw(i,t,f,n){let{arrayMergeMode:r="replace",skipNullish:c=!1,customMerger:l}=f;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return ew(i,t,r,n);if(!Mi(t)||!Mi(i))return t;return _T(i,t,f,n)}function ew(i,t,f,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(f){case"replace":return t;case"concat":return FT(i,t);case"smart":return KT(i,t,n);default:return t}return t}function FT(i,t){let f=[...t];for(let n of i)if(!f.some((r)=>V0(r,n)))f.push(n);return f}function KT(i,t,f){if(t.length===0)return i;if(i.length===0)return t;if(Mi(t[0])&&Mi(i[0]))return IT(i,t,f);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}function IT(i,t,f){let n=[...t];for(let r of i){if(!Mi(r)){n.push(r);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in r){if(n.find((w)=>Mi(w)&&(y in w)&&w[y]===r[y])){l=!0;break}}if(!l)n.push(r)}return n}function _T(i,t,f,n){let r=t;if(Mi(r)&&n.has(r))return n.get(r);let c={...i};if(Mi(r))n.set(r,c);for(let l in r){if(!Object.prototype.hasOwnProperty.call(r,l))continue;let y=r[l],w=c[l];if(f.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Mi(y)&&Mi(w))c[l]=Hw(w,y,f,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=ew(w,y,f.arrayMergeMode||"smart",n);else c[l]=y}return c}function qw(i,t,f="replace"){return JT(i,t,{arrayMergeMode:f==="replace"?"replace":"smart",skipNullish:!0})}function V0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!V0(i[f],t[f]))return!1;return!0}if(Mi(i)&&Mi(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!V0(i[r],t[r]))return!1}return!0}return!1}function Mi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Lw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,f={}){let{arrayStrategy:n="replace",useCache:r=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=f;if(r){let u=On.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Un(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new gn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new gn(i,Error("Configuration must export a valid object"),"unknown");let C={config:qw(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(r)On.setWithFileCheck("file",C,i,c);return C}catch(u){throw u instanceof Error?pt.configLoad(i,u):pt.configLoad(i,Error(String(u)))}};if(l)return Z0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,f={}){for(let n of i)try{let r=await this.loadFromPath(n,t,f);if(r)return r}catch(r){if(r instanceof Error&&r.name==="ConfigLoadError")throw r;if(f.verbose)console.warn(`Failed to load config from ${n}:`,r)}return null}generateConfigPaths(i,t,f){let n=this.generateNamePatterns(i,f),r=[];for(let c of n)for(let l of this.extensions)r.push(X0(t,`${c}${l}`));return r}generateNamePatterns(i,t){let f=[];if(f.push("config",".config"),i)f.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of n){if(!c)continue;if(f.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)f.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let r=new Set;return f.filter((c)=>{if(!c||r.has(c))return!1;return r.add(c),!0})}checkFileAccess(i){return ST(async()=>{return Un(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,f){let n=[];if(!Un(i))return n;if(t||f){let r=this.generateNamePatterns(t||"",f);for(let c of r)for(let l of this.extensions){let y=X0(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:r}=await import("fs"),c=r(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=X0(i,l);if(await this.checkFileAccess(y))n.push(y)}}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(!Un(i))return t.push("Configuration file does not exist"),t;let f=await import(i),n=f.default||f;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:r}=await import("fs"),c=r(i,"utf8");JSON.parse(c)}catch(r){t.push(`Invalid JSON syntax: ${r}`)}}catch(f){t.push(`Failed to load configuration file: ${f}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let f=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let r=await this.loadFromPath(n,{},t);if(r)f.set(n,r.config)}catch(r){if(t.verbose)console.warn(`Failed to preload ${n}:`,r)}})),f}}var zT=/^https?:\/\//;class xw{async validateConfiguration(i,t,f={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=f,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,validateRequired:r,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Z0.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,f){try{if(!$A(t))throw new kn(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),r=n.default||n;if(Array.isArray(r))return this.validateWithRules(i,r,f);else return this.validateWithJSONSchema(i,r,f)}catch(n){throw new kn(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,f){let n=[],r=[];return this.validateObjectAgainstSchema(i,t,"",n,r,f),{isValid:n.length===0,errors:n,warnings:r}}validateObjectAgainstSchema(i,t,f,n,r,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:f,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:f,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:f,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:f,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:f,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:f,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:f,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=f?`${f}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,r,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:f?`${f}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=f?`${f}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,r,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))r.push({path:f?`${f}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,f){let n=[],r=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),f.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:r}}validateWithRule(i,t,f){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:f,message:t.message||`Property '${f}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let r=Array.isArray(i)?"array":typeof i;if(r!==t.type)n.push({path:f,message:t.message||`Expected type ${t.type}, got ${r}`,expected:t.type,actual:r,rule:"type"})}if(t.min!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r<t.min)n.push({path:f,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:r,rule:"min"})}if(t.max!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r>t.max)n.push({path:f,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:r,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:f,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:f,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let r=t.validator(i);if(r)n.push({path:f,message:t.message||r,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let f=t.split("."),n=i;for(let r of f)if(n&&typeof n==="object"&&r in n)n=n[r];else return;return n}generateRulesFromInterface(i){let t=[],f=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of f){let[,r,c,l]=n;t.push({path:r,required:!c,type:this.mapTypeScriptType(l)})}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:zT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var tt=new Zn("bunfig",{showTags:!0});function QT(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((f)=>`"${f}"`).join(", ")}`}class gw{fileLoader=new Lw;envProcessor=new cc;validator=new xw;async loadConfig(i){let t=Date.now(),{cache:f,performance:n,schema:r,validate:c,...l}=i;try{if(f?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,f)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(r||c)await this.validateConfiguration(y.config,r,c,l.name);if(f?.enabled&&y)this.cacheResult(l.name||"",y,f,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)tt.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw tt.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,f){let{name:n="",alias:r,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||dn.cwd(),A=[],T=await this.loadLocalConfiguration(n,r,$,l,y,u,h,w,f);if(T)return A.push(...this.getLocalSearchPaths(n,r,$,l)),this.finalizeResult(T,A,w,n,h);let C=await this.loadHomeConfiguration(n,r,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(C,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,r,$,y,u,h,w);if(E)return A.push(zi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,r,$,l)),t)throw pt.configNotFound(n,A,r);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${QT(r)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,f,n,r,c,l,y,w){let u=y?mn(i,r,l):r,h=this.getLocalDirectories(f,n);for(let $ of h){if(l)tt.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)tt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,f,n,r,c){if(!i)return null;let l=c?mn(i,f,r):f,y=[zi(qt(),".config",i),zi(qt(),".config"),qt()];for(let w of y){if(r)tt.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:r});if(h){if(r)tt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,f,n,r,c,l){let y=l?mn(i,n,c):n;try{let w=zi(f,"package.json");if(!S1(w))return null;let u={};try{u=JSON.parse(J1(w,"utf8"))}catch(A){if(c)tt.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)tt.success(`Configuration loaded from package.json: ${$}`);return{config:qw(y,h,r),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)tt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,f,n){if(!f||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:mn(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,f,n,r){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,f,n){let r=[];if(f){let c=f(i);if(c)r.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)r.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(r.length>0)throw pt.configValidation(n||"unknown",r,n)}checkCache(i,t){let f=this.generateCacheKey(i,t);return On.get(f)||null}cacheResult(i,t,f,n){let r=this.generateCacheKey(i,n);On.set(r,t,void 0,f.ttl)}generateCacheKey(i,t){let f=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;f.push(`alias:${n}`)}if(t.cwd)f.push(`cwd:${t.cwd}`);if(t.configDir)f.push(`configDir:${t.configDir}`);if("checkEnv"in t)f.push(`checkEnv:${t.checkEnv}`);return f.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,zi(i,"config"),zi(i,".config"),t?zi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,f,n){let r=[];return r.push(...this.getLocalSearchPaths(i,t,f,n)),r.push(...this.getHomeSearchPaths(i,t)),r.push(zi(f,"package.json")),r}getLocalSearchPaths(i,t,f,n){let r=this.getLocalDirectories(f,n),c=[];for(let l of r)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let f=[zi(qt(),".config",i),zi(qt(),".config"),qt()],n=[];for(let r of f)n.push(...this.fileLoader.generateConfigPaths(i,r,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var Om=new gw;function mn(i,t,f=!1){let n=new cc,r=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${r}_${$.join("_").toUpperCase()}`,`${r}_${$.map((E)=>E.toUpperCase()).join("")}`,`${r}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=dn.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var Gm=zi(dn.cwd(),"config"),am=zi(dn.cwd(),"src/generated"),kw={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:u0.join(w0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:u0.join(w0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:u0.join(w0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var v=kw,Li={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"},Zt={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 sw(i){return s0.readFileSync(i,"utf8")}function D0(i,t){let f=[];function n(r){let c;try{c=s0.readdirSync(r)}catch{return}for(let l of c){let y=ei.join(r,l);try{if(s0.statSync(y).isDirectory())n(y);else if(l===t)f.push(r)}catch{continue}}}return n(i),f}function W(i,t,f){if(f||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var aT=GT(MT);function Dw(){return Vw.env.SUDO_PASSWORD}var gy="[redacted]",HT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),eT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function qT(i){let t=i.toLowerCase();return HT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Vn(i){if(Array.isArray(i))return i.map((f)=>Vn(f));if(typeof i==="string")return eT.test(i)?gy:i;if(!i||typeof i!=="object")return i;let t={};for(let[f,n]of Object.entries(i)){if(qT(f)){t[f]=gy;continue}t[f]=Vn(n)}return t}function vn(i){return JSON.stringify(Vn(i))}function LT(i){let t=Dw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let f=t.replace(/'/g,"'\\''"),n=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${f}' | ${n}`}async function jt(i,t={}){let f=LT(i);try{let{stdout:n,stderr:r}=await aT(f,{cwd:t.cwd||Vw.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:r.trim()}}catch(n){let r=Error(`Failed to execute command: ${i}
65
+ Error: ${n.message}`);throw r.stack=n.stack,r}}function dw(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 lc(i){let t=ei.join(OT.homedir(),".stacks","ssl"),f=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,n=i.certPath?ei.isAbsolute(i.certPath)?i.certPath:ei.join(f,i.certPath):ei.join(f,v.certPath),r=i.keyPath?ei.isAbsolute(i.keyPath)?i.keyPath:ei.join(f,i.keyPath):ei.join(f,v.keyPath),c=i.caCertPath?ei.isAbsolute(i.caCertPath)?i.caCertPath:ei.join(f,i.caCertPath):ei.join(f,v.caCertPath);return{certPath:n,keyPath:r,caCertPath:c,basePath:f}}function bw(i){let t=[],f=new Set;if(i.domain)f.add(i.domain);if(i.domains?.length)i.domains.forEach((n)=>f.add(n));for(let n of f)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 W(S.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function yc(i){let t=i.notBeforeDays??Li.DEFAULT_NOT_BEFORE_DAYS,f=i.validityDays??(i.validityYears?i.validityYears*365:Li.DEFAULT_VALIDITY_DAYS);W(S.CERT,"Calculating certificate validity dates",i.verbose);let n=new Date(Date.now()-86400*t*1000),r=new Date(n.getTime()+f*24*60*60*1000);return n.setUTCHours(0,0,0,0),r.setUTCHours(23,59,59,999),W(S.CERT,`Validity period: ${n.toISOString()} to ${r.toISOString()}`,i.verbose),{notBefore:n,notAfter:r}}var xi={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},Ci={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 Jf(i){if(i<128)return Buffer.from([i]);let t=[],f=i;while(f>0)t.unshift(f&255),f>>=8;return Buffer.from([128|t.length,...t])}function Fi(i,t){let f=Jf(t.length);return Buffer.concat([Buffer.from([i]),f,t])}function zf(i){let t=i.split(".").map(Number),f=[];f.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let r=t[n],c=[];c.unshift(r&127),r>>=7;while(r>0)c.unshift(r&127|128),r>>=7;f.push(...c)}return Fi(xi.OID,Buffer.from(f))}function d0(i){let t;if(typeof i==="bigint"){let f=i.toString(16).padStart(2,"0");t=Buffer.from(f.length%2?`0${f}`:f,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let f=i.toString(16).padStart(2,"0");t=Buffer.from(f.length%2?`0${f}`:f,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Fi(xi.INTEGER,t)}function Pw(i,t=0){return Fi(xi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Zw(i){return Fi(xi.OCTET_STRING,i)}function Ji(...i){return Fi(xi.SEQUENCE,Buffer.concat(i))}function xT(...i){return Fi(xi.SET,Buffer.concat(i))}function gT(i){return Fi(xi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function kT(i){return Fi(xi.UTF8_STRING,Buffer.from(i,"utf8"))}function VT(){return Buffer.from([xi.NULL,0])}function ky(i,t,f=!0){let n=160|i|(f?0:0),r=Jf(t.length);return Buffer.concat([Buffer.from([n]),r,t])}function Vy(i){let t=i.getUTCFullYear();if(t>=2050){let f=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Fi(xi.GENERALIZED_TIME,Buffer.from(f,"ascii"))}else{let f=(t%100).toString().padStart(2,"0"),n=(i.getUTCMonth()+1).toString().padStart(2,"0"),r=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),l=i.getUTCMinutes().toString().padStart(2,"0"),y=i.getUTCSeconds().toString().padStart(2,"0"),w=`${f}${n}${r}${c}${l}${y}Z`;return Fi(xi.UTC_TIME,Buffer.from(w,"ascii"))}}function sT(i,t){return Ji(Vy(i),Vy(t))}function sy(i){let t=[];for(let f of i){let n;switch(f.shortName){case"CN":n=Ci.COMMON_NAME;break;case"C":n=Ci.COUNTRY;break;case"L":n=Ci.LOCALITY;break;case"ST":n=Ci.STATE;break;case"O":n=Ci.ORGANIZATION;break;case"OU":n=Ci.ORGANIZATIONAL_UNIT;break;default:continue}let r=f.shortName==="C"?gT(f.value):kT(f.value),c=Ji(zf(n),r);t.push(xT(c))}return Ji(...t)}function vw(i){return Ji(zf(i),VT())}function DT(i){return i.export({type:"spki",format:"der"})}function dT(i){if(i.includes(":")){let t=i;if(i.includes("::")){let r=i.split("::"),c=r[0]?r[0].split(":"):[],l=r[1]?r[1].split(":"):[],y=8-c.length-l.length,w=Array.from({length:y},()=>"0");t=[...c,...w,...l].join(":")}let f=t.split(":"),n=Buffer.alloc(16);for(let r=0;r<8;r++){let c=Number.parseInt(f[r]||"0",16);n.writeUInt16BE(c,r*2)}return n}else{let t=i.split(".").map((f)=>Number.parseInt(f,10));return Buffer.from(t)}}function bT(i){let t=[];for(let f of i)if(f.type===2&&f.value){let n=Jf(f.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(f.value,"ascii")]))}else if(f.type===7&&f.ip){let n=dT(f.ip),r=Jf(n.length);t.push(Buffer.concat([Buffer.from([135]),r,n]))}else if(f.type===6&&f.value){let n=Jf(f.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(f.value,"ascii")]))}return Ji(...t)}function PT(i,t){if(i){if(t!==void 0)return Ji(Fi(1,Buffer.from([255])),d0(t));return Ji(Fi(1,Buffer.from([255])))}return Ji()}function ZT(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 f=0,n=t;while(n>0&&(n&1)===0)f++,n>>=1;if(t===0)f=7;return Pw(Buffer.from([t]),f)}function vT(i){let t=[];if(i.serverAuth)t.push(zf(Ci.SERVER_AUTH));if(i.clientAuth)t.push(zf(Ci.CLIENT_AUTH));return Ji(...t)}function Nf(i,t,f){let n=[zf(i)];if(t)n.push(Fi(1,Buffer.from([255])));return n.push(Zw(f)),Ji(...n)}function pT(i){let t=[];if(t.push(ky(0,d0(2))),t.push(d0(i.serialNumber)),t.push(vw(Ci.SHA256_WITH_RSA)),t.push(sy(i.issuer)),t.push(sT(i.notBefore,i.notAfter)),t.push(sy(i.subject)),t.push(DT(i.publicKey)),i.extensions){let f=[];if(i.extensions.basicConstraints)f.push(Nf(Ci.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,PT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)f.push(Nf(Ci.KEY_USAGE,i.extensions.keyUsage.critical??!0,ZT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)f.push(Nf(Ci.EXTENDED_KEY_USAGE,!1,vT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)f.push(Nf(Ci.SUBJECT_ALT_NAME,!1,bT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)f.push(Nf(Ci.SUBJECT_KEY_IDENTIFIER,!1,Zw(i.extensions.subjectKeyIdentifier)));if(f.length>0)t.push(ky(3,Ji(...f)))}return Ji(...t)}function oT(i,t){let f=ot.createSign("SHA256");f.update(i);let n=f.sign(t);return Ji(i,vw(Ci.SHA256_WITH_RSA),Pw(n))}function iE(i,t){let f=i.toString("base64"),n=[];for(let r=0;r<f.length;r+=64)n.push(f.slice(r,r+64));return`-----BEGIN ${t}-----
66
+ ${n.join(`
67
+ `)}
68
+ -----END ${t}-----
69
+ `}function wc(){let i=ot.randomBytes(20);return i[0]=i[0]&127||1,i}function pw(i=2048){let{privateKey:t,publicKey:f}=ot.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:f}}function tE(i){let t=i.export({type:"spki",format:"der"});return ot.createHash("sha1").update(t).digest()}function ow(i){let t={serialNumber:i.serialNumber||wc(),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:tE(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 f=pT(t),n=oT(f,i.signingKey);return{certificate:iE(n,"CERTIFICATE"),certificateDer:n}}function iu(i){return i.export({type:"pkcs8",format:"pem"})}function fE(i){return ot.createPrivateKey(i)}function nE(i){let t=new ot.X509Certificate(i),f=t.publicKey,n=[],r=t.subject.split(`
70
+ `);for(let c of r){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)n.push({shortName:l.trim(),value:w.trim()})}return{publicKey:f,subject:n}}async function uc(i={}){W("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Li.DEFAULT_KEY_SIZE;W("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:f,publicKey:n}=pw(t),r=[{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:c,notAfter:l}=yc({validityYears:i.validityYears||Li.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:y}=ow({serialNumber:wc(),notBefore:c,notAfter:l,subject:r,publicKey:n,signingKey:f,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:y,privateKey:iu(f),notBefore:c,notAfter:l}}async function hc(i){if(W("ca","Generating new certificate",i.verbose),W("ca",`Options: ${vn(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}=nE(i.rootCA.certificate),f=fE(i.rootCA.privateKey);W("ca",`Generating ${Li.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let n=Li.DEFAULT_KEY_SIZE,{privateKey:r,publicKey:c}=pw(n),l=i.commonName||dw(i),y=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:l}],{notBefore:w,notAfter:u}=yc({validityDays:i.validityDays||Li.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=bw(i),$=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=ow({serialNumber:wc(),notBefore:w,notAfter:u,subject:y,issuer:t,publicKey:c,signingKey:f,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:A,subjectAltName:h});return{certificate:T,privateKey:iu(r),notBefore:w,notAfter:u}}function tu(i,t){W(S.STORAGE,`Storing certificate and private key with options: ${vn(t)}`,t?.verbose);let{certPath:f,keyPath:n}=lc({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});W(S.STORAGE,`Certificate path: ${f}`,t?.verbose),W(S.STORAGE,`Private key path: ${n}`,t?.verbose);let r=b0.dirname(f);if(!ct.existsSync(r))W(S.STORAGE,`Creating certificate directory: ${r}`,t?.verbose),ct.mkdirSync(r,{recursive:!0});W(S.STORAGE,"Writing certificate file",t?.verbose),ct.writeFileSync(f,i.certificate);let c=b0.dirname(n);if(!ct.existsSync(c))W(S.STORAGE,`Creating private key directory: ${c}`,t?.verbose),ct.mkdirSync(c,{recursive:!0});return W(S.STORAGE,"Writing private key file",t?.verbose),ct.writeFileSync(n,i.privateKey),W(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),f}function fu(i,t){W(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:f}=lc({basePath:t?.basePath,caCertPath:t?.caCertPath});W(S.STORAGE,`CA certificate path: ${f}`,t?.verbose);let n=b0.dirname(f);if(!ct.existsSync(n))W(S.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),ct.mkdirSync(n,{recursive:!0});return W(S.STORAGE,"Writing CA certificate file",t?.verbose),ct.writeFileSync(f,i),W(S.STORAGE,"CA certificate stored successfully",t?.verbose),f}function pn(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=sw(i);return new rE.X509Certificate(t)}function on(i){return pn(i).fingerprint256.replace(/:/g,"").toUpperCase()}function $c(i){return nu(pn(i).subject)}function Ac(i,t,f=443,n=4000){let r;try{r=t.includes("-----BEGIN")?t:cE.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((c)=>{let l=!1,y=(u)=>{if(l)return;l=!0,c(u)},w=lE.connect({host:i,port:f,servername:i,ca:r,rejectUnauthorized:!0},()=>{y(w.authorized),w.end()});w.setTimeout(n,()=>{w.destroy(),y(!1)}),w.on("error",()=>y(!1))})}function yE(i){let t=[],f=i.split(`
71
+ `);for(let n of f){let[r,...c]=n.split("="),l=c.join("=");if(r&&l)t.push({shortName:r.trim(),value:l.trim()})}return t}function nu(i){return yE(i).find((t)=>t.shortName==="CN")?.value||""}function wE(i){let t=[],f=nu(i.subject);if(f&&!/^\d+\.\d+\.\d+\.\d+$/.test(f))t.push(f);let n=i.subjectAltName;if(n){let r=n.split(", ");for(let c of r)if(c.startsWith("DNS:"))t.push(c.slice(4))}return[...new Set(t)]}function Tc(i,t){let f=pn(i),n=wE(f);for(let r of n){if(r===t)return!0;if(r.startsWith("*.")){let c=r.slice(2);if(t.endsWith(c)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function hE(i,t){if(sn.platform()!=="darwin")return!1;try{let f=on(i);if(!f)return W(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(uE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
72
+ `).some((n)=>{let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!r&&r[1].toUpperCase()===f}))return W(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return W(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(f){return W(S.TRUST,`Error checking certificate trust: ${f}`,t),!1}}var $E={platform:"darwin",async addCertificate(i,t){if(await hE(i,t?.verbose)){W(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),Zt.success("Certificate is already trusted in system keychain");return}W(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await jt(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,f){let n=f||v.commonName;W(S.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await jt(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),W(S.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(r){throw W(S.TRUST,`Error removing certificate: ${r}`,t?.verbose),r}}},AE={platform:"win32",async addCertificate(i,t){W(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await jt(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,f){let n=f||v.commonName;W(S.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await jt(`certutil -delstore -enterprise Root "${n}"`),W(S.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(r){throw W(S.TRUST,`Error removing certificate: ${r}`,t?.verbose),r}}},TE={platform:"linux",async addCertificate(i,t){W(S.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let f=sn.homedir(),n=Li.LINUX_CERT_DB_FILENAME,r=Li.LINUX_TRUST_ARGS;W(S.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let c=D0(f,n);if(c.length===0){Zt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){W(S.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{W(S.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await jt(`certutil -d sql:${l} -D -n ${v.commonName}`)}catch(y){W(S.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}W(S.TRUST,`Adding new certificate to ${l}`,t?.verbose),await jt(`certutil -d sql:${l} -A -t ${r} -n ${v.commonName} -i ${i}`),Zt.info(`Cert added to ${l}`)}},async removeCertificate(i,t,f){let n=f||v.commonName;W(S.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let r=sn.homedir(),c=Li.LINUX_CERT_DB_FILENAME;W(S.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let l=D0(r,c);if(l.length===0){Zt.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){W(S.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await jt(`certutil -d sql:${y} -D -n "${n}"`),Zt.info(`Cert removed from ${y}`)}catch(w){W(S.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},EE={darwin:$E,win32:AE,linux:TE};async function Ec(i,t,f){W(S.TRUST,`Adding certificate to system trust store with options: ${vn(f)}`,f?.verbose),W(S.TRUST,"Storing certificate and private key",f?.verbose);let n=tu(i,f);W(S.TRUST,"Storing CA certificate",f?.verbose);let r=fu(t,f),c=sn.platform();W(S.TRUST,`Detected platform: ${c}`,f?.verbose);let l=EE[c];if(!l){let y=`Unsupported platform: ${c}`;throw W(S.TRUST,`Error: ${y}`,f?.verbose),Error(y)}return await l.addCertificate(r,f),W(S.TRUST,"Certificate successfully added to system trust store",f?.verbose),n}import{homedir as fl}from"node:os";import{join as nl,resolve as mX}from"node:path";import{existsSync as ru,statSync as cu}from"fs";import{existsSync as YE,mkdirSync as OR,readdirSync as GR,readFileSync as BE,writeFileSync as aR}from"fs";import{homedir as tf}from"os";import{dirname as qR,resolve as Oi}from"path";import Mr from"process";import{existsSync as lu,statSync as yu}from"fs";import{existsSync as Oc,mkdirSync as CE,readdirSync as UE,writeFileSync as jE}from"fs";import{homedir as ff}from"os";import{dirname as wu,resolve as ji}from"path";import zt from"process";import{join as mE,relative as RE,resolve as uu}from"path";import mr from"process";import{existsSync as Du,mkdirSync as PR,readdirSync as ZR,writeFileSync as vR}from"fs";import{homedir as Yc}from"os";import{dirname as iW,resolve as Ui}from"path";import Of from"process";import{join as WE,relative as XE,resolve as hu}from"path";import Rr from"process";import{existsSync as du,mkdirSync as cW,readdirSync as lW,writeFileSync as yW}from"fs";import{dirname as uW,resolve as Wr}from"path";import Gc from"process";import{Buffer as Wt}from"buffer";import{createCipheriv as NE,createDecipheriv as SE,randomBytes as Bc}from"crypto";import{closeSync as Cc,createReadStream as $u,createWriteStream as JE,existsSync as Uc,fsyncSync as Au,openSync as Tu,writeFileSync as FE}from"fs";import{access as KE,constants as Eu,mkdir as IE,readdir as ir,rename as Yu,stat as nf,unlink as tr,writeFile as jc}from"fs/promises";import{join as rf}from"path";import $i from"process";import{pipeline as _E}from"stream/promises";import{createGzip as Bu}from"zlib";import cf from"process";import ht from"process";import{Buffer as yt}from"buffer";import{createCipheriv as zE,createDecipheriv as QE,randomBytes as mc}from"crypto";import{closeSync as Rc,createReadStream as Cu,createWriteStream as ME,existsSync as fr,fsyncSync as Uu,openSync as ju,writeFileSync as OE}from"fs";import{access as GE,constants as mu,mkdir as aE,readdir as nr,rename as Ru,stat as lf,unlink as rr,writeFile as Wc}from"fs/promises";import{isAbsolute as HE,join as yf,resolve as eE}from"path";import Q from"process";import{pipeline as qE}from"stream/promises";import{createGzip as Wu}from"zlib";import wf from"process";import $t from"process";import cr from"process";import{existsSync as lr}from"fs";import{resolve as Xc}from"path";import{existsSync as LE}from"fs";import{existsSync as xE,readdirSync as gE}from"fs";import{extname as Nc,resolve as Xu}from"path";import kE from"process";import{join as VE,relative as sE,resolve as Nu}from"path";import Xr from"process";import{Buffer as wt}from"buffer";import{createCipheriv as DE,createDecipheriv as dE,randomBytes as Sc}from"crypto";import{closeSync as Jc,createReadStream as Su,createWriteStream as bE,existsSync as yr,fsyncSync as Ju,openSync as Fu,writeFileSync as PE}from"fs";import{access as ZE,constants as Ku,mkdir as vE,readdir as wr,rename as Iu,stat as uf,unlink as ur,writeFile as Fc}from"fs/promises";import{isAbsolute as pE,join as hf,resolve as oE}from"path";import M from"process";import{pipeline as iY}from"stream/promises";import{createGzip as _u}from"zlib";import $f from"process";import At from"process";import $r from"process";import{existsSync as Ar}from"fs";import{resolve as Mc}from"path";import{existsSync as mB}from"fs";class Vu{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 f=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${f}`}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(([,f],[,n])=>f.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let f=0;f<t;f++)this.cache.delete(i[f][0])}set(i,t,f,n){if(!this.options.enabled)return;let r=this.generateKey(i,f),c=n??this.options.ttl,l=this.estimateSize(t);this.cache.set(r,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let f=this.generateKey(i,t),n=this.cache.get(f);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(f),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!ru(i))return!0;return cu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let f=this.get(i,t);if(!f)return;if(this.isFileModified(t,f.fileTimestamp)){this.delete(i,t);return}return f.value}setWithFileCheck(i,t,f,n){try{let r=ru(f)?cu(f):null,c=r?r.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},f,n)}catch{this.set(i,t,f,n)}}delete(i,t){let f=this.generateKey(i,t);return this.cache.delete(f)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,f]of this.cache.entries())if(this.isExpired(f))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,r)=>n+r.size,0),f=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:f[0],newestEntry:f[f.length-1]}}export(){let i={};for(let[t,f]of this.cache.entries())i[t]={value:f.value,timestamp:f.timestamp.toISOString(),ttl:f.ttl,hits:f.hits,size:f.size};return i}import(i){this.cache.clear();for(let[t,f]of Object.entries(i))if(typeof f==="object"&&f!==null){let n=f;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class su{metrics=[];maxMetrics=1000;async track(i,t,f={}){let n=performance.now(),r=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:r,...f}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:r,...f}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((r)=>r.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let f=t.map((r)=>r.duration),n=f.reduce((r,c)=>r+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...f),maxDuration:Math.max(...f),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var jr=new Vu,Dc=new su;var tY=Object.defineProperty,fY=(i)=>i;function nY(i,t){this[i]=fY.bind(null,t)}var rY=(i,t)=>{for(var f in t)tY(i,f,{get:t[f],enumerable:!0,configurable:!0,set:nY.bind(t,f)})},cY=(i,t)=>()=>(i&&(t=i(i=0)),t),bu={};rY(bu,{withErrorRecovery:()=>vu,tryLoadConfig:()=>KY,loadConfigWithResult:()=>JY,loadConfig:()=>fh,isRetryableError:()=>mY,isConfigNotFoundError:()=>jY,isBunfigError:()=>pu,globalPerformanceMonitor:()=>Hf,globalCache:()=>Af,getEnvOrDefault:()=>RY,generateConfigTypes:()=>IY,defaultGeneratedDir:()=>hh,defaultConfigDir:()=>uh,deepMergeWithArrayStrategy:()=>vc,deepMerge:()=>ou,createLibraryConfig:()=>_Y,config:()=>FY,bunfigPlugin:()=>zY,applyEnvVarsToConfig:()=>Mf,TypeGenerationError:()=>gc,SchemaValidationError:()=>af,PluginError:()=>Vc,PerformanceMonitor:()=>bc,FileSystemError:()=>xc,ErrorFactory:()=>Xt,EnvVarError:()=>Ir,EnvProcessor:()=>Or,ConfigValidator:()=>pc,ConfigValidationError:()=>qc,ConfigNotFoundError:()=>Kr,ConfigMergeError:()=>Lc,ConfigLoader:()=>oc,ConfigLoadError:()=>Gf,ConfigFileLoader:()=>Gr,ConfigCache:()=>dc,CacheUtils:()=>rh,BunfigError:()=>Ki,BrowserConfigError:()=>kc,ArrayMergeStrategies:()=>yh});class dc{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 f=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${f}`}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(([,f],[,n])=>f.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let f=0;f<t;f++)this.cache.delete(i[f][0])}set(i,t,f,n){if(!this.options.enabled)return;let r=this.generateKey(i,f),c=n??this.options.ttl,l=this.estimateSize(t);this.cache.set(r,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let f=this.generateKey(i,t),n=this.cache.get(f);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(f),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!lu(i))return!0;return yu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let f=this.get(i,t);if(!f)return;if(this.isFileModified(t,f.fileTimestamp)){this.delete(i,t);return}return f.value}setWithFileCheck(i,t,f,n){try{let r=lu(f)?yu(f):null,c=r?r.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},f,n)}catch{this.set(i,t,f,n)}}delete(i,t){let f=this.generateKey(i,t);return this.cache.delete(f)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,f]of this.cache.entries())if(this.isExpired(f))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,r)=>n+r.size,0),f=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:f[0],newestEntry:f[f.length-1]}}export(){let i={};for(let[t,f]of this.cache.entries())i[t]={value:f.value,timestamp:f.timestamp.toISOString(),ttl:f.ttl,hits:f.hits,size:f.size};return i}import(i){this.cache.clear();for(let[t,f]of Object.entries(i))if(typeof f==="object"&&f!==null){let n=f;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class bc{metrics=[];maxMetrics=1000;async track(i,t,f={}){let n=performance.now(),r=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:r,...f}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:r,...f}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((r)=>r.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let f=t.map((r)=>r.duration),n=f.reduce((r,c)=>r+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...f),maxDuration:Math.max(...f),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function lY(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function yY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function wY(i){return i.getStats().size*2}function Pc(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 r of i)if(D(r)&&"name"in r){if(!n.find((l)=>D(l)&&("name"in l)&&l.name===r.name))n.push(r)}else if(D(r)&&"path"in r){if(!n.find((l)=>D(l)&&("path"in l)&&l.path===r.path))n.push(r)}else if(!n.some((c)=>Nr(c,r)))n.push(r);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}if(!D(t)||!D(i))return t;let f={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(r===null||r===void 0)continue;else if(D(r)&&D(f[n]))f[n]=Pc(f[n],r);else if(Array.isArray(r)&&Array.isArray(f[n]))if(r.length>0&&f[n].length>0&&D(r[0])&&D(f[n][0])){let c=[...r];for(let l of f[n])if(D(l)&&"name"in l){if(!c.find((w)=>D(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(D(l)&&"path"in l){if(!c.find((w)=>D(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Nr(y,l)))c.push(l);f[n]=c}else if(r.every((c)=>typeof c==="string")&&f[n].every((c)=>typeof c==="string")){let c=[...r];for(let l of f[n])if(!c.includes(l))c.push(l);f[n]=c}else f[n]=r;else f[n]=r}return f}function Nr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!Nr(i[f],t[f]))return!1;return!0}if(D(i)&&D(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!Nr(i[r],t[r]))return!1}return!0}return!1}function D(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function uY(i,t){if(!du(i))return null;try{let f=await import(i),n=f.default||f;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Pc(t,n)}catch{return null}}catch{return null}}async function hY({name:i="",cwd:t,defaultConfig:f}){let n=t||Gc.cwd(),r=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of r){let w=Wr(n,`${l}${y}`),u=await uY(w,f);if(u!==null)return u}try{let l=Wr(n,"package.json");if(du(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Pc(f,w)}catch{}}}catch{}return f}function $Y(i,t={}){let f=Rr.cwd();while(f.includes("storage"))f=hu(f,"..");let n=hu(f,i||"");if(t?.relative)return XE(Rr.cwd(),n);return n}async function AY(){try{let i=await hY({name:"clarity",defaultConfig:Yr,cwd:Rr.cwd(),endpoint:"",headers:{}});return{...Yr,...i}}catch{return Yr}}function P(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function TY(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let i=ht.type;if(i==="renderer"||i==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class Pu{async format(i){let t=await TY(),f=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:f})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:cf.pid,hostname:t(),environment:cf.env.NODE_ENV||"development",platform:cf.platform,version:cf.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cf.env.NODE_ENV||cf.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Sr{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={...Hc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Pu,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 f={...t},n=t.timestamp!==void 0;if(n)delete f.timestamp;if(this.config={...this.config,...f,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),c=this.generateKey();this.currentKeyId=r,this.keys.set(r,c),this.encryptionKeys.set(r,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Br,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Br};return{...Br,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Hc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},f={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!f.level||!["debug","info","success","warning","error"].includes(f.level))f.level=t.level;return f}async writeToFile(i){let f=(async()=>{let r,c=0,l=3,y=1000;while(c<l)try{try{try{await KE(this.config.logDirectory,Eu.F_OK|Eu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await IE(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 w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Wt.from(i);try{if(!Uc(this.currentLogFile))await jc(this.currentLogFile,"",{mode:420});if(r=Tu(this.currentLogFile,"a",420),FE(r,w,{flag:"a"}),Au(r),r!==void 0)Cc(r),r=void 0;if((await nf(this.currentLogFile)).size===0){if(await jc(this.currentLogFile,w,{flag:"w",mode:420}),(await nf(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(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;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(r!==void 0)try{Cc(r)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(f);let n=this.pendingOperations.length-1;try{await f}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return rf(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 rf(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return rf(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(P())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 f=typeof t.interval==="number"?t.interval:60,n=Math.max(f,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,f=this.generateKeyId(),n=this.generateKey();this.currentKeyId=f,this.keys.set(f,n),this.encryptionKeys.set(f,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(r.length>l)for(let[y]of r.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Bc(16).toString("hex")}generateKey(){return Bc(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(),f=Bc(16),n=NE("aes-256-gcm",t,f),r=Wt.concat([n.update(i,"utf8"),n.final()]),c=n.getAuthTag();return{encrypted:Wt.concat([f,r,c]),iv:f}}async compressData(i){return new Promise((t,f)=>{let n=Bu(),r=[];n.on("data",(c)=>r.push(c)),n.on("end",()=>t(Wt.from(Wt.concat(r)))),n.on("error",f),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(P())return;let i=await nf(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 f=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await ir(this.config.logDirectory),c=r.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${f}.${l}`;if(await nf(f).catch(()=>null))try{if(await Yu(f,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await tr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!r.some((w)=>w.endsWith(".log.1")))try{let w=`${f}.1`;await jc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),c=f.replace(/\.log$/,`-${r}.log`);if(await nf(f).catch(()=>null))await Yu(f,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await ir(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await tr(rf(this.config.logDirectory,l))}}}async compressLogFile(i,t){let f=$u(i),n=JE(t),r=Bu();await _E(f,r,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let f of this.logBuffer){let n=await this.formatter.format(f);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 f={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(f)}}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()})),Uc(this.currentLogFile))try{let i=Tu(this.currentLogFile,"r+");Au(i),Cc(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(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ir(this.config.logDirectory)).filter((f)=>(f.includes("temp")||f.includes(".tmp"))&&f.includes(this.name));for(let f of t)try{await tr(rf(this.config.logDirectory,f))}catch(n){console.error(`Failed to delete temp file ${f}:`,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?V.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:f="",tag:n="",message:r,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(f)T.push(f.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(r),T.join(" ")}let w=$i.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${f} ${r}`;else if(c==="info"||c==="success")u=`${f} ${n} ${r}`;else u=`${f} ${n} ${V.cyan(r)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let f=/%([sdijfo%])/g,n=0,r=i.replace(f,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)r+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return r}async log(i,t,...f){let n=new Date,r=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,f);if(this.fancy&&!P()){let u=ch[i],h=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:V.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:V.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:r,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
73
+ `);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:r,message:V.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let w=`${c} ${this.environment}.${i.toUpperCase()}: ${l}
74
+ `;if(y)w+=`${y}
75
+ `;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!P()){let f=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:V.blue("◐"),tag:f,message:`${V.cyan(i)}...`}))}return async(f)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),c=`${i} completed in ${r}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(f)u+=` ${JSON.stringify(f)}`;if(u+=`
76
+ `,u=u.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let h=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:V.green("✓"),tag:h,message:`${c}${f?` ${JSON.stringify(f)}`:""}`}))}else if(!P())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}`,f=new Sr(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(f),f}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Uc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $u(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 f=this.keys.get(this.currentKeyId);try{let n=Wt.isBuffer(i)?i:Wt.from(i,"base64"),r=n.slice(0,16),c=n.slice(-16),l=n.slice(16,-16),y=SE("aes-256-gcm",f,r);return y.setAuthTag(c),Wt.concat([y.update(l),y.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 P()}isServerMode(){return!P()}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,f=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!P()){let c=i.split(`
77
+ `),l=Math.max(...c.map((h)=>h.length))+2,y=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,u=c.map((h)=>{let $=" ".repeat(l-h.length-2);return`│ ${h}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:f,message:V.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:f,message:V.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:f,message:V.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:f,message:V.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let r=`${n} ${this.environment}.INFO: [BOX] ${i}
78
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}async prompt(i){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${V.cyan("?")} ${i} (y/n) `);let f=(n)=>{let r=n.toString().trim().toLowerCase();$i.stdin.removeListener("data",f);try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!1)}catch{}$i.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!0)}catch{}$i.stdin.resume(),$i.stdin.once("data",f)})}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 f=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(f=i.replace(l,(w,u)=>{if(u==="%")return"%";if(y>=t.length)return w;let h=t[y++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),y<t.length)f+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}if(this.fancy&&!P()){let l=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",y=V.blue("◐");console.error(`${y} ${l} ${V.cyan(f)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
79
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(c)}progress(i,t=""){if(!this.enabled||!this.fancy||P()||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 f=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:f,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(l,y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,l)),y!==void 0)this.activeProgressBar.message=y;let w=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,w)},finish:(l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=this.activeProgressBar.total,l!==void 0)this.activeProgressBar.message=l;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(l,y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;$i.stdout.write(`${"\r".padEnd($i.stdout.columns||80)}\r`),this.log(y,l),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!$i.stdout.isTTY)return;let f=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*f/100),r=i.barLength-n,c=V.green("━".repeat(n)),l=V.gray("━".repeat(r)),y=`[${c}${l}]`,w=`${f}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||f===100?V.green("✓"):V.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=$i.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,$i.stdout.write(i.lastRenderedLine),t)$i.stdout.write(`
80
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!$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(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ir(this.config.logDirectory),f=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=rf(this.config.logDirectory,n);if(i.before)try{if((await nf(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}f.push(c)}if(f.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${f.length} log file(s)...`);for(let n of f)try{await tr(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Er(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let n=[...t];for(let r of i)if(g(r)&&"name"in r){if(!n.find((l)=>g(l)&&("name"in l)&&l.name===r.name))n.push(r)}else if(g(r)&&"path"in r){if(!n.find((l)=>g(l)&&("path"in l)&&l.path===r.path))n.push(r)}else if(!n.some((c)=>Jr(c,r)))n.push(r);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}if(!g(t)||!g(i))return t;let f={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(r===null||r===void 0)continue;else if(g(r)&&g(f[n]))f[n]=Er(f[n],r);else if(Array.isArray(r)&&Array.isArray(f[n]))if(r.length>0&&f[n].length>0&&g(r[0])&&g(f[n][0])){let c=[...r];for(let l of f[n])if(g(l)&&"name"in l){if(!c.find((w)=>g(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(g(l)&&"path"in l){if(!c.find((w)=>g(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Jr(y,l)))c.push(l);f[n]=c}else if(r.every((c)=>typeof c==="string")&&f[n].every((c)=>typeof c==="string")){let c=[...r];for(let l of f[n])if(!c.includes(l))c.push(l);f[n]=c}else f[n]=r;else f[n]=r}return f}function Zc(i,t,f="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return f==="replace"?t:Er(i,t);if(Array.isArray(i))return f==="replace"?t:Er(i,t);if(!g(t)||!g(i))return t;let n={...i};for(let r of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let c=t[r],l=n[r];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(f==="replace")n[r]=c;else n[r]=Er(l,c);else if(g(c)&&g(l))n[r]=Zc(l,c,f);else n[r]=c}return n}function Jr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!Jr(i[f],t[f]))return!1;return!0}if(g(i)&&g(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!Jr(i[r],t[r]))return!1}return!0}return!1}function g(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function hr(i,t,f="replace"){if(!Du(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return Zc(t,r,f)}catch{return null}}catch{return null}}function EY(i,t,f=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),r={...t};function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${n}_${$.map(A).join("_")}`,C=`${n}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(f)Ti.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let E=Of.env[T]||Of.env[C];if(E!==void 0){if(f)Ti.info(`Using environment variable ${E?T:C} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(E);else if(typeof h==="boolean")w[u]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let B=JSON.parse(E);if(Array.isArray(B))w[u]=B;else w[u]=E.split(",").map((U)=>U.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(r)}async function YY({name:i="",alias:t,cwd:f,configDir:n,defaultConfig:r,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof r==="object"&&r!==null&&!Array.isArray(r)?EY(i,r,c):r,u=f||Of.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)Ti.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Ui(u,"config"),Ui(u,".config"),n?Ui(u,n):void 0].filter(Boolean)));for(let B of E){if(c)Ti.info(`Searching for configuration in: ${B}`);let R=[Ui(u,"config"),Ui(u,".config")].concat(n?[Ui(u,n)]:[]).includes(B)?[...$,...A,...T,...C]:[...A,...$,...C,...T];for(let N of R)for(let J of h){let I=Ui(B,`${N}${J}`),z=await hr(I,w,y);if(z!==null){if(c)Ti.success(`Configuration loaded from: ${I}`);return z}}}if(i){let B=Ui(Yc(),".config",i),U=["config",`${i}.config`];if(t)U.push(`${t}.config`);if(c)Ti.info(`Checking user config directory: ${B}`);for(let R of U)for(let N of h){let J=Ui(B,`${R}${N}`),I=await hr(J,w,y);if(I!==null){if(c)Ti.success(`Configuration loaded from user config directory: ${J}`);return I}}}if(i){let B=Ui(Yc(),".config"),U=[`.${i}.config`];if(t)U.push(`.${t}.config`);if(c)Ti.info(`Checking user config directory for dotfile configs: ${B}`);for(let R of U)for(let N of h){let J=Ui(B,`${R}${N}`),I=await hr(J,w,y);if(I!==null){if(c)Ti.success(`Configuration loaded from user config directory dotfile: ${J}`);return I}}}if(i){let B=Yc(),U=[`.${i}.config`,`.${i}`];if(t)U.push(`.${t}.config`),U.push(`.${t}`);if(c)Ti.info(`Checking user home directory for dotfile configs: ${B}`);for(let R of U)for(let N of h){let J=Ui(B,`${R}${N}`),I=await hr(J,w,y);if(I!==null){if(c)Ti.success(`Configuration loaded from user home directory: ${J}`);return I}}}try{let B=Ui(u,"package.json");if(Du(B)){let U=await import(B),R=U[i];if(!R&&t){if(R=U[t],R&&c)Ti.success(`Using alias "${t}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(c)Ti.success(`Configuration loaded from package.json: ${R===U[i]?i:t}`);return Zc(w,R,y)}catch(N){if(c)Ti.warn("Failed to merge package.json config:",N)}}}catch(B){if(c)Ti.warn("Failed to load package.json:",B)}if(c)Ti.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function BY(i,t={}){let f=mr.cwd();while(f.includes("storage"))f=uu(f,"..");let n=uu(f,i||"");if(t?.relative)return RE(mr.cwd(),n);return n}async function CY(){try{let i=await YY({name:"clarity",alias:"logging",defaultConfig:Cr,cwd:mr.cwd()});return{...Cr,...i||{}}}catch{return Cr}}function ti(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UY(){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 Zu{async format(i){let t=await UY(),f=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:f})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:wf.pid,hostname:t(),environment:wf.env.NODE_ENV||"development",platform:wf.platform,version:wf.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wf.env.NODE_ENV||wf.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Fr{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={...ec},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zu,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??Q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let f={...t},n=t.timestamp!==void 0;if(n)delete f.timestamp;if(this.config={...this.config,...f,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),c=this.generateKey();this.currentKeyId=r,this.keys.set(r,c),this.encryptionKeys.set(r,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},f=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[f]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Ur,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Ur};return{...Ur,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:ec.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},f={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!f.level||!["debug","info","success","warning","error"].includes(f.level))f.level=t.level;return f}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let f=(async()=>{let r,c=0,l=3,y=1000;while(c<l)try{try{try{await GE(this.config.logDirectory,mu.F_OK|mu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await aE(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 w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:yt.from(i);try{if(!fr(this.currentLogFile))await Wc(this.currentLogFile,"",{mode:420});if(r=ju(this.currentLogFile,"a",420),OE(r,w,{flag:"a"}),Uu(r),r!==void 0)Rc(r),r=void 0;if((await lf(this.currentLogFile)).size===0){if(await Wc(this.currentLogFile,w,{flag:"w",mode:420}),(await lf(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(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;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(r!==void 0)try{Rc(r)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(f);let n=this.pendingOperations.length-1;try{await f}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yf(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 yf(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yf(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 f=typeof t.interval==="number"?t.interval:60,n=Math.max(f,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,f=this.generateKeyId(),n=this.generateKey();this.currentKeyId=f,this.keys.set(f,n),this.encryptionKeys.set(f,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(r.length>l)for(let[y]of r.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return mc(16).toString("hex")}generateKey(){return mc(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(),f=mc(16),n=zE("aes-256-gcm",t,f),r=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=n.update(r),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=yt.allocUnsafe(16+y+16);return f.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:f}}async compressData(i){return new Promise((t,f)=>{let n=Wu(),r=[];n.on("data",(c)=>r.push(c)),n.on("end",()=>t(yt.from(yt.concat(r)))),n.on("error",f),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 lf(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 f=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await nr(this.config.logDirectory),c=r.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${f}.${l}`;if(await lf(f).catch(()=>null))try{if(await Ru(f,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await rr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!r.some((w)=>w.endsWith(".log.1")))try{let w=`${f}.1`;await Wc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),c=f.replace(/\.log$/,`-${r}.log`);if(await lf(f).catch(()=>null))await Ru(f,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await nr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await rr(yf(this.config.logDirectory,l))}}}async compressLogFile(i,t){let f=Cu(i),n=ME(t),r=Wu();await qE(f,r,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let f of this.logBuffer){let n=await this.formatter.format(f);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()})),fr(this.currentLogFile))try{let i=ju(this.currentLogFile,"r+");Uu(i),Rc(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 nr(this.config.logDirectory)).filter((f)=>(f.includes("temp")||f.includes(".tmp"))&&f.includes(this.name));for(let f of t)try{await rr(yf(this.config.logDirectory,f))}catch(n){console.error(`Failed to delete temp file ${f}:`,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()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof Q.env.NO_COLOR<"u",t=Q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof Q.stderr<"u"&&Q.stderr.isTTY||typeof Q.stdout<"u"&&Q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:f="",tag:n="",message:r,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(f)T.push(f.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(r),T.join(" ")}let w=Q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${f} ${r}`;else if(c==="info"||c==="success")u=`${f} ${n} ${r}`;else u=`${f} ${n} ${G.cyan(r)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let f=/%([sdijfo%])/g,n=0,r=i.replace(f,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)r+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return r}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(f,n,r)=>{let c=G.underline(G.blue(n)),l=this.toAbsoluteFilePath(r);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(f,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(f,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(f,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(f,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(f,n)=>G.strikethrough(n)),t}supportsHyperlinks(){if(ti())return!1;let i=Q.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 f=Q.env.HOME||"";if(f)t=t.replace(/^~(?=$|\/)/,f)}if(HE(t)||t.startsWith("./")||t.startsWith("../"))t=eE(t);else return null;return fr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,f=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:f}}async log(i,t,...f){let n=new Date,r=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,f);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":lh[i],A=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:G.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:G.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
81
+ `);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:r,message:G.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
82
+ `;if(y)h+=`${y}
83
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let f={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return f;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(y,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,y),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ti()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ti()&&Q.stdout.isTTY)Q.stdout.write(`
84
+ `);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:f,message:`${G.cyan(i)}...`}))}return async(f)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),c=`${i} completed in ${r}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(f)u+=` ${JSON.stringify(f)}`;if(u+=`
85
+ `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":G.green("✓"),tag:h,message:`${c}${f?` ${JSON.stringify(f)}`:""}`}))}else if(!ti())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}`,f=new Fr(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(f),f}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!fr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Cu(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 f=this.keys.get(this.currentKeyId);try{let n=yt.isBuffer(i)?i:yt.from(i,"base64"),r=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=QE("aes-256-gcm",f,r);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=yt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.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,f=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:r,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=r.split(`
86
+ `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:f,message:G.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:f,message:G.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:f,message:G.cyan(h),showTimestamp:!1}))}else if(!ti())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
87
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${i} (y/n) `);let f=(n)=>{let r=n.toString().trim().toLowerCase();Q.stdin.removeListener("data",f);try{if(typeof Q.stdin.setRawMode==="function")Q.stdin.setRawMode(!1)}catch{}Q.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof Q.stdin.setRawMode==="function")Q.stdin.setRawMode(!0)}catch{}Q.stdin.resume(),Q.stdin.once("data",f)})}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 f=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(f=i.replace(w,(h,$)=>{if($==="%")return"%";if(u>=t.length)return h;let A=t[u++];switch($){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return h}}),u<t.length)f+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:r}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${u}${w} ${G.cyan(n)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
88
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Q.stdout.isTTY)return;let f=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*f/100),r=i.barLength-n,c=G.green("━".repeat(n)),l=G.gray("━".repeat(r)),y=`[${c}${l}]`,w=`${f}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||f===100?G.green("✓"):G.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=Q.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,Q.stdout.write(i.lastRenderedLine),t)Q.stdout.write(`
89
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!Q.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 nr(this.config.logDirectory),f=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=yf(this.config.logDirectory,n);if(i.before)try{if((await lf(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}f.push(c)}if(f.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${f.length} log file(s)...`);for(let n of f)try{await rr(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function vu(i,t={}){let{maxRetries:f=3,retryDelay:n=1000,isRetryable:r=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=f;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===f||!r(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function pu(i){return i instanceof Ki}function jY(i){return i instanceof Kr}function mY(i){if(pu(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((f)=>i.message.toLowerCase().includes(f.toLowerCase()))}class Or{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,f={}){let{prefix:n,useCamelCase:r=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=f,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:r,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Hf.track("applyEnvironmentVariables",u,{configName:i});return u()}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,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${f}_${y.join("_")}`,u=n.useBackwardCompatibility?`${f}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,f,n);else{let h=cr.env[w]||(u?cr.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=cr.env[w]?w:u}try{i[r]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof Ir)throw $;throw Xt.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,f,n,r){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Xt.envVar(f,i,`${t} (via ${c.name} parser)`,r)}return i}getEnvironmentVariables(i){let t={},f=i.toUpperCase();for(let[n,r]of Object.entries(cr.env))if(n.startsWith(f)&&r!==void 0)t[n]=r;return t}validateEnvironmentVariable(i,t,f){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(f)try{this.parseEnvironmentValue(i,t,f,{})}catch(r){n.push(`Cannot parse value "${t}" as ${f}: ${r}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,f={}){let{prefix:n,format:r="text"}=f,c=n||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),r){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=`${f}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,f,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}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 f=`Environment Variables for ${t}:
90
+
91
+ `;for(let n of i)f+=`${n.key}
92
+ `,f+=` Type: ${n.type}
93
+ `,f+=` Description: ${n.description}
94
+ `,f+=` Example: ${n.example}
95
+
96
+ `;return f}formatAsMarkdown(i,t){let f=`# Environment Variables for ${t}
97
+
98
+ `;f+=`| Variable | Type | Description | Example |
99
+ `,f+=`|----------|------|-------------|----------|
100
+ `;for(let n of i)f+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
101
+ `;return f}}function RY(i,t){let f=nh("process");if(typeof f>"u"||!f.env)return t;let n=f.env[i];return n!==void 0?n:t}function ou(i,t,f={}){return ih(i,t,f,new WeakMap)}function ih(i,t,f,n){let{arrayMergeMode:r="replace",skipNullish:c=!1,customMerger:l}=f;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return th(i,t,r,n);if(!Gi(t)||!Gi(i))return t;return SY(i,t,f,n)}function th(i,t,f,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(f){case"replace":return t;case"concat":return WY(i,t);case"smart":return XY(i,t,n);default:return t}return t}function WY(i,t){let f=[...t];for(let n of i)if(!f.some((r)=>ac(r,n)))f.push(n);return f}function XY(i,t,f){if(t.length===0)return i;if(i.length===0)return t;if(Gi(t[0])&&Gi(i[0]))return NY(i,t,f);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}function NY(i,t,f){let n=[...t];for(let r of i){if(!Gi(r)){n.push(r);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in r){if(n.find((u)=>Gi(u)&&(y in u)&&u[y]===r[y])){l=!0;break}}if(!l)n.push(r)}return n}function SY(i,t,f,n){let r=t;if(Gi(r)&&n.has(r))return n.get(r);let c={...i};if(Gi(r))n.set(r,c);for(let l in r){if(!Object.prototype.hasOwnProperty.call(r,l))continue;let y=r[l],w=c[l];if(f.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Gi(y)&&Gi(w))c[l]=ih(w,y,f,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=th(w,y,f.arrayMergeMode||"smart",n);else c[l]=y}return c}function vc(i,t,f="replace"){return ou(i,t,{arrayMergeMode:f==="replace"?"replace":"smart",skipNullish:!0})}function ac(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!ac(i[f],t[f]))return!1;return!0}if(Gi(i)&&Gi(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!ac(i[r],t[r]))return!1}return!0}return!1}function Gi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Gr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,f={}){let{arrayStrategy:n="replace",useCache:r=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=f;if(r){let u=Af.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!lr(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new Gf(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Gf(i,Error("Configuration must export a valid object"),"unknown");let B={config:vc(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(r)Af.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Xt.configLoad(i,u):Xt.configLoad(i,Error(String(u)))}};if(l)return Hf.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,f={}){for(let n of i)try{let r=await this.loadFromPath(n,t,f);if(r)return r}catch(r){if(r instanceof Error&&r.name==="ConfigLoadError")throw r;if(f.verbose)console.warn(`Failed to load config from ${n}:`,r)}return null}generateConfigPaths(i,t,f){let n=this.generateNamePatterns(i,f),r=[];for(let c of n)for(let l of this.extensions)r.push(Xc(t,`${c}${l}`));return r}generateNamePatterns(i,t){let f=[];if(f.push("config",".config"),i)f.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(f.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)f.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return f.filter(Boolean)}checkFileAccess(i){return vu(async()=>{return lr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,f){let n=[];if(!lr(i))return n;if(t||f){let r=this.generateNamePatterns(t||"",f);for(let c of r)for(let l of this.extensions){let y=Xc(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:r}=await import("fs"),c=r(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Xc(i,l);if(await this.checkFileAccess(y))n.push(y)}}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((f)=>f.test(i))}async validateConfigFile(i){let t=[];try{if(!lr(i))return t.push("Configuration file does not exist"),t;let f=await import(i),n=f.default||f;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:r}=await import("fs"),c=r(i,"utf8");JSON.parse(c)}catch(r){t.push(`Invalid JSON syntax: ${r}`)}}catch(f){t.push(`Failed to load configuration file: ${f}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let f=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let r=await this.loadFromPath(n,{},t);if(r)f.set(n,r.config)}catch(r){if(t.verbose)console.warn(`Failed to preload ${n}:`,r)}})),f}}class pc{async validateConfiguration(i,t,f={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=f,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,validateRequired:r,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Hf.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,f){try{if(!LE(t))throw new af(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),r=n.default||n;if(Array.isArray(r))return this.validateWithRules(i,r,f);else return this.validateWithJSONSchema(i,r,f)}catch(n){throw new af(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,f){let n=[],r=[];return this.validateObjectAgainstSchema(i,t,"",n,r,f),{isValid:n.length===0,errors:n,warnings:r}}validateObjectAgainstSchema(i,t,f,n,r,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:f,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:f,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:f,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:f,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:f,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:f,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:f,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=f?`${f}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,r,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:f?`${f}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=f?`${f}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,r,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))r.push({path:f?`${f}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,f){let n=[],r=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),f.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:r}}validateWithRule(i,t,f){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:f,message:t.message||`Property '${f}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let r=Array.isArray(i)?"array":typeof i;if(r!==t.type)n.push({path:f,message:t.message||`Expected type ${t.type}, got ${r}`,expected:t.type,actual:r,rule:"type"})}if(t.min!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r<t.min)n.push({path:f,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:r,rule:"min"})}if(t.max!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r>t.max)n.push({path:f,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:r,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:f,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:f,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let r=t.validator(i);if(r)n.push({path:f,message:t.message||r,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let f=t.split("."),n=i;for(let r of f)if(n&&typeof n==="object"&&r in n)n=n[r];else return;return n}generateRulesFromInterface(i){let t=[],f=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of f){let[,r,c,l]=n;t.push({path:r,required:!c,type:this.mapTypeScriptType(l)})}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:wh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oc{fileLoader=new Gr;envProcessor=new Or;validator=new pc;async loadConfig(i){let t=Date.now(),{cache:f,performance:n,schema:r,validate:c,...l}=i;try{if(f?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,f)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(r||c)await this.validateConfiguration(y.config,r,c,l.name);if(f?.enabled&&y)this.cacheResult(l.name||"",y,f,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)ki.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw ki.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,f){let{name:n="",alias:r,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||zt.cwd(),A=[],T=await this.loadLocalConfiguration(n,r,$,l,y,u,h,w,f);if(T)return A.push(...this.getLocalSearchPaths(n,r,$,l)),this.finalizeResult(T,A,w,n,h);let C=await this.loadHomeConfiguration(n,r,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(C,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,r,$,y,u,h,w);if(E)return A.push(ji($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,r,$,l)),t)throw Xt.configNotFound(n,A,r);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${r?` or alias "${r}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,f,n,r,c,l,y,w){let u=y?Mf(i,r,l):r,h=this.getLocalDirectories(f,n);for(let $ of h){if(l)ki.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)ki.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,f,n,r,c){if(!i)return null;let l=c?Mf(i,f,r):f,y=[ji(ff(),".config",i),ji(ff(),".config"),ff()];for(let w of y){if(r)ki.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:r});if(h){if(r)ki.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,f,n,r,c,l){let y=l?Mf(i,n,c):n;try{let w=ji(f,"package.json");if(!Oc(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)ki.success(`Configuration loaded from package.json: ${$}`);return{config:vc(y,h,r),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)ki.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,f,n){if(!f||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Mf(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,f,n,r){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,f,n){let r=[];if(f){let c=f(i);if(c)r.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)r.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(r.length>0)throw Xt.configValidation(n||"unknown",r,n)}checkCache(i,t){let f=this.generateCacheKey(i,t);return Af.get(f)||null}cacheResult(i,t,f,n){let r=this.generateCacheKey(i,n);Af.set(r,t,void 0,f.ttl)}generateCacheKey(i,t){let f=[i];if(t.alias)f.push(`alias:${t.alias}`);if(t.cwd)f.push(`cwd:${t.cwd}`);if(t.configDir)f.push(`configDir:${t.configDir}`);if("checkEnv"in t)f.push(`checkEnv:${t.checkEnv}`);return f.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,f,n){let r=[];return r.push(...this.getLocalSearchPaths(i,t,f,n)),r.push(...this.getHomeSearchPaths(i,t)),r.push(ji(f,"package.json")),r}getLocalSearchPaths(i,t,f,n){let r=this.getLocalDirectories(f,n),c=[];for(let l of r)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let f=[ji(ff(),".config",i),ji(ff(),".config"),ff()],n=[];for(let r of f)n.push(...this.fileLoader.generateConfigPaths(i,r,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function zu(i){let f=!(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 f||n}async function JY(i){return Tt.loadConfig({...i,__strictErrorHandling:!0})}async function fh(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},f="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(f)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 r=n instanceof Error?n.name:"UnknownError",c=n instanceof Error?n.message:String(n);if(!(r==="ConfigNotFoundError"||r==="ConfigLoadError"||r==="ConfigValidationError"||c.includes("config"))&&i.verbose)ki.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let y=f?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await Tt.applyEnvironmentVariables(y.name||"",t,!0,y.verbose||!1))?.config??t;return t}}async function FY(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(f){if(f instanceof Error&&(f.name==="ConfigNotFoundError"||f.name==="ConfigLoadError"&&zu(f)))return(await Tt.applyEnvironmentVariables(i,{},!0,!1)).config;throw f}}try{return(await Tt.loadConfig({...i,cwd:i.cwd||zt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&zu(t)))return(await Tt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function KY(i,t,f="replace"){let n=new Gr;try{let r=await n.loadFromPath(i,t,{arrayStrategy:f,useCache:!1,trackPerformance:!1});return r?r.config:null}catch{return null}}function Mf(i,t,f=!1){let n=new Or,r=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${r}_${$.join("_").toUpperCase()}`,`${r}_${$.map((E)=>E.toUpperCase()).join("")}`,`${r}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=zt.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function IY(i){let t=ji(zt.cwd(),i.configDir),f=ji(zt.cwd(),i.generatedDir),n=ji(f,"config-types.ts");if(!Oc(wu(n)))CE(wu(n),{recursive:!0,mode:511});let r=Oc(t)?UE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${rB}
102
+ export type ConfigNames = ${r.length?`'${r.join("' | '")}'`:"string"}
103
+ `;jE(n,c,{mode:438})}function _Y(i){let t=null,f=null,n=()=>{if(!f)f=fh(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)ki.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return f},r="defaultConfig"in i?i.defaultConfig:{};return t=r,n(),new Proxy({},{get(c,l){if(t)return t[l];let y=r[l];return n(),y},has(c,l){return l in(t||r)},ownKeys(){return Object.keys(t||r)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||r,l)},set(c,l,y){if(!t)t={...r};return t[l]=y,!0}})}function zY(i){let t=Xu(kE.cwd(),i?.configDir||"./config");function f(){if(!xE(t))return[];let r=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=gE(t).filter((w)=>r.has(Nc(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),y=new Map;for(let{base:w,file:u}of l){let h=Nc(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=Nc($).toLowerCase();if(c.indexOf(h)<c.indexOf(A))y.set(w,u)}return Array.from(y.entries()).map(([w,u])=>({base:w,file:u})).sort((w,u)=>w.base.localeCompare(u.base))}function n(){let r=f(),c=r.map((u)=>u.base),l=c.length?c.map((u)=>`'${u}'`).join(" | "):"string",y=r.length?`{
104
+ ${r.map((u)=>{let h=Xu(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
105
+ `)}
106
+ }`:"Record<string, any>";return`export type ConfigNames = ${l}
107
+ export type ConfigByName = ${y}
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(r){r.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),r.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var nh,Af,Hf,rh,QY,MY,Qu,Yr,Hc,Ai,V,OY,Mu,GY,Ou,aY,HY,Kc,eY,Gu,au,Ic,qY,LY,xY,gY,Br,ch,kY,Ti,VY,sY,Hu,Cr,ec,fi,G,DY,eu,dY,qu,bY,PY,_c,ZY,Lu,xu,vY,zc,pY,oY,iB,tB,fB,Ur,lh,nB,rB="0.15.6",Ki,Kr,Gf,qc,Lc,Ir,xc,gc,af,kc,Vc,Xt,yh,wh,ki,Tt,uh,hh,cB=cY(async()=>{nh=import.meta.require,Af=new dc,Hf=new bc,rh={createKey:lY,isEquivalent:yY,estimateMemoryUsage:wY},QY=Wr(Gc.cwd(),"config"),MY=Wr(Gc.cwd(),"src/generated"),Qu=Rr.env.CLARITY_LOG_DIR||WE($Y(),"logs"),Yr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Qu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hc=await AY(),Ai={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"},V=Ai,OY=Ai.red,Mu=Ai.green,GY=Ai.yellow,Ou=Ai.blue,aY=Ai.magenta,HY=Ai.cyan,Kc=Ai.white,eY=Ai.gray,Gu=Ai.bgRed,au=Ai.bgYellow,Ic=Ai.bold,qY=Ai.dim,LY=Ai.italic,xY=Ai.underline,gY=Ai.reset,Br={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ch={debug:"\uD83D\uDD0D",info:Ou("ℹ"),success:Mu("✓"),warning:au(Kc(Ic(" WARN "))),error:Gu(Kc(Ic(" ERROR ")))},kY=new Sr("stacks"),Ti=new Sr("bunfig",{showTags:!0}),VY=Ui(Of.cwd(),"config"),sY=Ui(Of.cwd(),"src/generated"),Hu=mr.env.CLARITY_LOG_DIR||mE(BY(),"logs"),Cr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Hu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ec=await CY(),fi={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"},G=fi,DY=fi.red,eu=fi.green,dY=fi.yellow,qu=fi.blue,bY=fi.magenta,PY=fi.cyan,_c=fi.white,ZY=fi.gray,Lu=fi.bgRed,xu=fi.bgYellow,vY=fi.bgGray,zc=fi.bold,pY=fi.dim,oY=fi.italic,iB=fi.underline,tB=fi.strikethrough,fB=fi.reset,Ur={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lh={debug:"\uD83D\uDD0D",info:qu("ℹ"),success:eu("✓"),warning:xu(_c(zc(" WARN "))),error:Lu(_c(zc(" ERROR ")))},nB=new Fr("stacks"),Ki=class extends Error{timestamp;context;constructor(t,f={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=f,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(([f,n])=>`${f}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Kr=class extends Ki{code="CONFIG_NOT_FOUND";constructor(t,f,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${t}"${r} not found`,{configName:t,alias:n,searchPaths:f,searchPathCount:f.length})}},Gf=class extends Ki{code="CONFIG_LOAD_ERROR";constructor(t,f,n){super(`Failed to load configuration from "${t}": ${f.message}`,{configPath:t,configName:n,originalError:f.name,originalMessage:f.message});this.cause=f}},qc=class extends Ki{code="CONFIG_VALIDATION_ERROR";constructor(t,f,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:f,errorCount:f.length})}},Lc=class extends Ki{code="CONFIG_MERGE_ERROR";constructor(t,f,n,r){super(`Failed to merge configuration from "${t}" with "${f}": ${n.message}`,{sourcePath:t,targetPath:f,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Ir=class extends Ki{code="ENV_VAR_ERROR";constructor(t,f,n,r){super(`Failed to parse environment variable "${t}" with value "${f}" as ${n}`,{envKey:t,envValue:f,expectedType:n,configName:r})}},xc=class extends Ki{code="FILE_SYSTEM_ERROR";constructor(t,f,n){super(`File system ${t} failed for "${f}": ${n.message}`,{operation:t,path:f,originalError:n.name,originalMessage:n.message});this.cause=n}},gc=class extends Ki{code="TYPE_GENERATION_ERROR";constructor(t,f,n){super(`Failed to generate types from "${t}" to "${f}": ${n.message}`,{configDir:t,outputPath:f,originalError:n.name,originalMessage:n.message});this.cause=n}},af=class extends Ki{code="SCHEMA_VALIDATION_ERROR";constructor(t,f,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:f,errorCount:f.length})}},kc=class extends Ki{code="BROWSER_CONFIG_ERROR";constructor(t,f,n,r){super(`Failed to fetch configuration from "${t}": ${f} ${n}`,{endpoint:t,status:f,statusText:n,configName:r})}},Vc=class extends Ki{code="PLUGIN_ERROR";constructor(t,f,n){super(`Plugin "${t}" failed during ${f}: ${n.message}`,{pluginName:t,operation:f,originalError:n.name,originalMessage:n.message});this.cause=n}},Xt={configNotFound(i,t,f){return new Kr(i,t,f)},configLoad(i,t,f){return new Gf(i,t,f)},configValidation(i,t,f){return new qc(i,t,f)},configMerge(i,t,f,n){return new Lc(i,t,f,n)},envVar(i,t,f,n){return new Ir(i,t,f,n)},fileSystem(i,t,f){return new xc(i,t,f)},typeGeneration(i,t,f){return new gc(i,t,f)},schemaValidation(i,t,f){return new af(i,t,f)},browserConfig(i,t,f,n){return new kc(i,t,f,n)},plugin(i,t,f){return new Vc(i,t,f)}},yh={replace:"replace",concat:"concat",smart:"smart"},wh=/^https?:\/\//,ki=new Fr("bunfig",{showTags:!0}),Tt=new oc,uh=ji(zt.cwd(),"config"),hh=ji(zt.cwd(),"src/generated")});function lB(i,t={}){let f=Xr.cwd();while(f.includes("storage"))f=Nu(f,"..");let n=Nu(f,i||"");if(t?.relative)return sE(Xr.cwd(),n);return n}var yB=Xr.env.CLARITY_LOG_DIR||VE(lB(),"logs"),$h={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_r={...$h},ZW=(async()=>{try{let{loadConfig:i}=await cB().then(()=>bu),t=await i({name:"clarity",alias:"logging",defaultConfig:$h,cwd:Xr.cwd()});if(t)Object.assign(_r,t)}catch{}return _r})();function ni(){if(At.env.NODE_ENV==="test"||At.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wB(){if(At.env.NODE_ENV==="test"||At.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof At<"u"){let i=At.type;if(i==="renderer"||i==="worker")return!1;return!!(At.versions&&(At.versions.node||At.versions.bun))}return!1}class Ah{async format(i){let t=await wB(),f=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:f})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$f.pid,hostname:t(),environment:$f.env.NODE_ENV||"development",platform:$f.platform,version:$f.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$f.env.NODE_ENV||$f.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"},H=ci,vW=ci.red,uB=ci.green,pW=ci.yellow,hB=ci.blue,oW=ci.magenta,iX=ci.cyan,gu=ci.white,tX=ci.gray,$B=ci.bgRed,AB=ci.bgYellow,fX=ci.bgGray,ku=ci.bold,nX=ci.dim,rX=ci.italic,cX=ci.underline,lX=ci.strikethrough,yX=ci.reset,Qc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},TB={debug:"\uD83D\uDD0D",info:hB("ℹ"),success:uB("✓"),warning:AB(gu(ku(" WARN "))),error:$B(gu(ku(" ERROR ")))};class ar{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={..._r},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ah,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??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let f={...t},n=t.timestamp!==void 0;if(n)delete f.timestamp;if(this.config={...this.config,...f,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),c=this.generateKey();this.currentKeyId=r,this.keys.set(r,c),this.encryptionKeys.set(r,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},f=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[f]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Qc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Qc};return{...Qc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:_r.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},f={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!f.level||!["debug","info","success","warning","error"].includes(f.level))f.level=t.level;return f}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let f=(async()=>{let r,c=0,l=3,y=1000;while(c<l)try{try{try{await ZE(this.config.logDirectory,Ku.F_OK|Ku.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await vE(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 w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:wt.from(i);try{if(!yr(this.currentLogFile))await Fc(this.currentLogFile,"",{mode:420});if(r=Fu(this.currentLogFile,"a",420),PE(r,w,{flag:"a"}),Ju(r),r!==void 0)Jc(r),r=void 0;if((await uf(this.currentLogFile)).size===0){if(await Fc(this.currentLogFile,w,{flag:"w",mode:420}),(await uf(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(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;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(r!==void 0)try{Jc(r)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(f);let n=this.pendingOperations.length-1;try{await f}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return hf(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 hf(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return hf(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 f=typeof t.interval==="number"?t.interval:60,n=Math.max(f,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,f=this.generateKeyId(),n=this.generateKey();this.currentKeyId=f,this.keys.set(f,n),this.encryptionKeys.set(f,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(r.length>l)for(let[y]of r.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Sc(16).toString("hex")}generateKey(){return Sc(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(),f=Sc(16),n=DE("aes-256-gcm",t,f),r=wt.isBuffer(i)?i:wt.from(i,"utf8"),c=n.update(r),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=wt.allocUnsafe(16+y+16);return f.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:f}}async compressData(i){return new Promise((t,f)=>{let n=_u(),r=[];n.on("data",(c)=>r.push(c)),n.on("end",()=>t(wt.from(wt.concat(r)))),n.on("error",f),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 uf(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 f=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await wr(this.config.logDirectory),c=r.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${f}.${l}`;if(await uf(f).catch(()=>null))try{if(await Iu(f,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await ur(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!r.some((w)=>w.endsWith(".log.1")))try{let w=`${f}.1`;await Fc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),c=f.replace(/\.log$/,`-${r}.log`);if(await uf(f).catch(()=>null))await Iu(f,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await wr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await ur(hf(this.config.logDirectory,l))}}}async compressLogFile(i,t){let f=Su(i),n=bE(t),r=_u();await iY(f,r,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let f of this.logBuffer){let n=await this.formatter.format(f);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()})),yr(this.currentLogFile))try{let i=Fu(this.currentLogFile,"r+");Ju(i),Jc(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 wr(this.config.logDirectory)).filter((f)=>(f.includes("temp")||f.includes(".tmp"))&&f.includes(this.name));for(let f of t)try{await ur(hf(this.config.logDirectory,f))}catch(n){console.error(`Failed to delete temp file ${f}:`,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()?H.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof M.env.NO_COLOR<"u",t=M.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:f="",tag:n="",message:r,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(f)T.push(f.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(r),T.join(" ")}let w=M.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${f} ${r}`;else if(c==="info"||c==="success")u=`${f} ${n} ${r}`;else u=`${f} ${n} ${H.cyan(r)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let f=/%([sdijfo%])/g,n=0,r=i.replace(f,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)r+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return r}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(f,n,r)=>{let c=H.underline(H.blue(n)),l=this.toAbsoluteFilePath(r);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(f,n)=>H.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(f,n)=>H.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(f,n)=>H.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(f,n)=>H.italic(n)),t=t.replace(/~([^~]+)~/g,(f,n)=>H.strikethrough(n)),t}supportsHyperlinks(){if(ni())return!1;let i=M.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 f=M.env.HOME||"";if(f)t=t.replace(/^~(?=$|\/)/,f)}if(pE(t)||t.startsWith("./")||t.startsWith("../"))t=oE(t);else return null;return yr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,f=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:f}}async log(i,t,...f){if(!this.shouldLog(i))return;let n=new Date,r=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,f);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":TB[i],A=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:H.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:H.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:r,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
111
+ `);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:r,message:H.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
112
+ `;if(y)h+=`${y}
113
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let f={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return f;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(y,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,y),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ni()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ni()&&M.stdout.isTTY)M.stdout.write(`
114
+ `);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":H.blue("◐"),tag:f,message:`${H.cyan(i)}...`}))}return async(f)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),c=`${i} completed in ${r}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(f)u+=` ${JSON.stringify(f)}`;if(u+=`
115
+ `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":H.green("✓"),tag:h,message:`${c}${f?` ${JSON.stringify(f)}`:""}`}))}else if(!ni())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}`,f=new ar(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(f),f}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Su(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 f=this.keys.get(this.currentKeyId);try{let n=wt.isBuffer(i)?i:wt.from(i,"base64"),r=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=dE("aes-256-gcm",f,r);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=wt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.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,f=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:r,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=r.split(`
116
+ `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:f,message:H.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:f,message:H.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:f,message:H.cyan(h),showTimestamp:!1}))}else if(!ni())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
117
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${H.cyan("?")} ${i} (y/n) `);let f=(n)=>{let r=n.toString().trim().toLowerCase();M.stdin.removeListener("data",f);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",f)})}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 f=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(f=i.replace(w,(h,$)=>{if($==="%")return"%";if(u>=t.length)return h;let A=t[u++];switch($){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return h}}),u<t.length)f+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:r}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${H.blue("◐")} `;console.error(`${u}${w} ${H.cyan(n)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
118
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let f=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*f/100),r=i.barLength-n,c=H.green("━".repeat(n)),l=H.gray("━".repeat(r)),y=`[${c}${l}]`,w=`${f}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||f===100?H.green("✓"):H.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=M.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,M.stdout.write(i.lastRenderedLine),t)M.stdout.write(`
119
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!M.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 wr(this.config.logDirectory),f=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=hf(this.config.logDirectory,n);if(i.before)try{if((await uf(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}f.push(c)}if(f.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${f.length} log file(s)...`);for(let n of f)try{await ur(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var wX=new ar("stacks");class Vi 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,f])=>`${t}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Th extends Vi{code="CONFIG_NOT_FOUND";constructor(i,t,f){let n=f===void 0?[]:Array.isArray(f)?f.filter(Boolean):[f],r="";if(n.length===1)r=` or alias "${n[0]}"`;else if(n.length>1)r=` or aliases ${n.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${r} not found`,{configName:i,alias:f,searchPaths:t,searchPathCount:t.length})}}class zr extends Vi{code="CONFIG_LOAD_ERROR";constructor(i,t,f){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:f,originalError:t.name,originalMessage:t.message});this.cause=t}}class Eh extends Vi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,f){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:f,validationErrors:t,errorCount:t.length})}}class Yh extends Vi{code="CONFIG_MERGE_ERROR";constructor(i,t,f,n){super(`Failed to merge configuration from "${i}" with "${t}": ${f.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:f.name,originalMessage:f.message});this.cause=f}}class il extends Vi{code="ENV_VAR_ERROR";constructor(i,t,f,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${f}`,{envKey:i,envValue:t,expectedType:f,configName:n})}}class Bh extends Vi{code="FILE_SYSTEM_ERROR";constructor(i,t,f){super(`File system ${i} failed for "${t}": ${f.message}`,{operation:i,path:t,originalError:f.name,originalMessage:f.message});this.cause=f}}class Ch extends Vi{code="TYPE_GENERATION_ERROR";constructor(i,t,f){super(`Failed to generate types from "${i}" to "${t}": ${f.message}`,{configDir:i,outputPath:t,originalError:f.name,originalMessage:f.message});this.cause=f}}class Qr extends Vi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:i,configName:f,validationErrors:t,errorCount:t.length})}}class Uh extends Vi{code="BROWSER_CONFIG_ERROR";constructor(i,t,f,n){super(`Failed to fetch configuration from "${i}": ${t} ${f}`,{endpoint:i,status:t,statusText:f,configName:n})}}class jh extends Vi{code="PLUGIN_ERROR";constructor(i,t,f){super(`Plugin "${i}" failed during ${t}: ${f.message}`,{pluginName:i,operation:t,originalError:f.name,originalMessage:f.message});this.cause=f}}var Tf={configNotFound(i,t,f){return new Th(i,t,f)},configLoad(i,t,f){return new zr(i,t,f)},configValidation(i,t,f){return new Eh(i,t,f)},configMerge(i,t,f,n){return new Yh(i,t,f,n)},envVar(i,t,f,n){return new il(i,t,f,n)},fileSystem(i,t,f){return new Bh(i,t,f)},typeGeneration(i,t,f){return new Ch(i,t,f)},schemaValidation(i,t,f){return new Qr(i,t,f)},browserConfig(i,t,f,n){return new Uh(i,t,f,n)},plugin(i,t,f){return new jh(i,t,f)}};async function EB(i,t={}){let{maxRetries:f=3,retryDelay:n=1000,isRetryable:r=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=f;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===f||!r(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class tl{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,f={}){let{prefix:n,useCamelCase:r=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=f,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:r,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Dc.track("applyEnvironmentVariables",u,{configName:i});return u()}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,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${f}_${y.join("_")}`,u=n.useBackwardCompatibility?`${f}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,f,n);else{let h=$r.env[w]||(u?$r.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=$r.env[w]?w:u}try{i[r]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof il)throw $;throw Tf.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,f,n,r){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Tf.envVar(f,i,`${t} (via ${c.name} parser)`,r)}return i}getEnvironmentVariables(i){let t={},f=i.toUpperCase();for(let[n,r]of Object.entries($r.env))if(n.startsWith(f)&&r!==void 0)t[n]=r;return t}validateEnvironmentVariable(i,t,f){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(f)try{this.parseEnvironmentValue(i,t,f,{})}catch(r){n.push(`Cannot parse value "${t}" as ${f}: ${r}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,f={}){let{prefix:n,format:r="text"}=f,c=n||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),r){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,f,n){for(let[r,c]of Object.entries(i)){let l=[...t,r],y=`${f}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,f,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}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 f=`Environment Variables for ${t}:
120
+
121
+ `;for(let n of i)f+=`${n.key}
122
+ `,f+=` Type: ${n.type}
123
+ `,f+=` Description: ${n.description}
124
+ `,f+=` Example: ${n.example}
125
+
126
+ `;return f}formatAsMarkdown(i,t){let f=`# Environment Variables for ${t}
127
+
128
+ `;f+=`| Variable | Type | Description | Example |
129
+ `,f+=`|----------|------|-------------|----------|
130
+ `;for(let n of i)f+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
131
+ `;return f}}function YB(i,t,f={}){return mh(i,t,f,new WeakMap)}function mh(i,t,f,n){let{arrayMergeMode:r="replace",skipNullish:c=!1,customMerger:l}=f;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Rh(i,t,r,n);if(!ai(t)||!ai(i))return t;return jB(i,t,f,n)}function Rh(i,t,f,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(f){case"replace":return t;case"concat":return BB(i,t);case"smart":return CB(i,t,n);default:return t}return t}function BB(i,t){let f=[...t];for(let n of i)if(!f.some((r)=>sc(r,n)))f.push(n);return f}function CB(i,t,f){if(t.length===0)return i;if(i.length===0)return t;if(ai(t[0])&&ai(i[0]))return UB(i,t,f);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let r of i)if(!n.includes(r))n.push(r);return n}return t}function UB(i,t,f){let n=[...t];for(let r of i){if(!ai(r)){n.push(r);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in r){if(n.find((u)=>ai(u)&&(y in u)&&u[y]===r[y])){l=!0;break}}if(!l)n.push(r)}return n}function jB(i,t,f,n){let r=t;if(ai(r)&&n.has(r))return n.get(r);let c={...i};if(ai(r))n.set(r,c);for(let l in r){if(!Object.prototype.hasOwnProperty.call(r,l))continue;let y=r[l],w=c[l];if(f.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(ai(y)&&ai(w))c[l]=mh(w,y,f,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=Rh(w,y,f.arrayMergeMode||"smart",n);else c[l]=y}return c}function Wh(i,t,f="replace"){return YB(i,t,{arrayMergeMode:f==="replace"?"replace":"smart",skipNullish:!0})}function sc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let f=0;f<i.length;f++)if(!sc(i[f],t[f]))return!1;return!0}if(ai(i)&&ai(t)){let f=Object.keys(i),n=Object.keys(t);if(f.length!==n.length)return!1;for(let r of f){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!sc(i[r],t[r]))return!1}return!0}return!1}function ai(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Xh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,f={}){let{arrayStrategy:n="replace",useCache:r=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=f;if(r){let u=jr.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Ar(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new zr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new zr(i,Error("Configuration must export a valid object"),"unknown");let B={config:Wh(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(r)jr.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Tf.configLoad(i,u):Tf.configLoad(i,Error(String(u)))}};if(l)return Dc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,f={}){for(let n of i)try{let r=await this.loadFromPath(n,t,f);if(r)return r}catch(r){if(r instanceof Error&&r.name==="ConfigLoadError")throw r;if(f.verbose)console.warn(`Failed to load config from ${n}:`,r)}return null}generateConfigPaths(i,t,f){let n=this.generateNamePatterns(i,f),r=[];for(let c of n)for(let l of this.extensions)r.push(Mc(t,`${c}${l}`));return r}generateNamePatterns(i,t){let f=[];if(f.push("config",".config"),i)f.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of n){if(!c)continue;if(f.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)f.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let r=new Set;return f.filter((c)=>{if(!c||r.has(c))return!1;return r.add(c),!0})}checkFileAccess(i){return EB(async()=>{return Ar(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,f){let n=[];if(!Ar(i))return n;if(t||f){let r=this.generateNamePatterns(t||"",f);for(let c of r)for(let l of this.extensions){let y=Mc(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:r}=await import("fs"),c=r(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Mc(i,l);if(await this.checkFileAccess(y))n.push(y)}}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((f)=>f.test(i))}async validateConfigFile(i){let t=[];try{if(!Ar(i))return t.push("Configuration file does not exist"),t;let f=await import(i),n=f.default||f;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:r}=await import("fs"),c=r(i,"utf8");JSON.parse(c)}catch(r){t.push(`Invalid JSON syntax: ${r}`)}}catch(f){t.push(`Failed to load configuration file: ${f}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let f=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let r=await this.loadFromPath(n,{},t);if(r)f.set(n,r.config)}catch(r){if(t.verbose)console.warn(`Failed to preload ${n}:`,r)}})),f}}var RB=/^https?:\/\//;class Nh{async validateConfiguration(i,t,f={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=f,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,validateRequired:r,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Dc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,f){try{if(!mB(t))throw new Qr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),r=n.default||n;if(Array.isArray(r))return this.validateWithRules(i,r,f);else return this.validateWithJSONSchema(i,r,f)}catch(n){throw new Qr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,f){let n=[],r=[];return this.validateObjectAgainstSchema(i,t,"",n,r,f),{isValid:n.length===0,errors:n,warnings:r}}validateObjectAgainstSchema(i,t,f,n,r,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:f,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:f,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:f,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:f,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:f,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:f,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:f,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=f?`${f}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,r,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:f?`${f}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=f?`${f}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,r,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))r.push({path:f?`${f}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,f){let n=[],r=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),f.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:r}}validateWithRule(i,t,f){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:f,message:t.message||`Property '${f}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let r=Array.isArray(i)?"array":typeof i;if(r!==t.type)n.push({path:f,message:t.message||`Expected type ${t.type}, got ${r}`,expected:t.type,actual:r,rule:"type"})}if(t.min!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r<t.min)n.push({path:f,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:r,rule:"min"})}if(t.max!==void 0){let r=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(r>t.max)n.push({path:f,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:r,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:f,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:f,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let r=t.validator(i);if(r)n.push({path:f,message:t.message||r,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let f=t.split("."),n=i;for(let r of f)if(n&&typeof n==="object"&&r in n)n=n[r];else return;return n}generateRulesFromInterface(i){let t=[],f=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of f){let[,r,c,l]=n;t.push({path:r,required:!c,type:this.mapTypeScriptType(l)})}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:RB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ut=new ar("bunfig",{showTags:!0});function WB(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((f)=>`"${f}"`).join(", ")}`}class Sh{fileLoader=new Xh;envProcessor=new tl;validator=new Nh;async loadConfig(i){let t=Date.now(),{cache:f,performance:n,schema:r,validate:c,...l}=i;try{if(f?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,f)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(r||c)await this.validateConfiguration(y.config,r,c,l.name);if(f?.enabled&&y)this.cacheResult(l.name||"",y,f,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)ut.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw ut.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,f){let{name:n="",alias:r,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Mr.cwd(),A=[],T=await this.loadLocalConfiguration(n,r,$,l,y,u,h,w,f);if(T)return A.push(...this.getLocalSearchPaths(n,r,$,l)),this.finalizeResult(T,A,w,n,h);let C=await this.loadHomeConfiguration(n,r,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(C,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,r,$,y,u,h,w);if(E)return A.push(Oi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,r,$,l)),t)throw Tf.configNotFound(n,A,r);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${WB(r)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,f,n,r,c,l,y,w){let u=y?Tr(i,r,l):r,h=this.getLocalDirectories(f,n);for(let $ of h){if(l)ut.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)ut.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,f,n,r,c){if(!i)return null;let l=c?Tr(i,f,r):f,y=[Oi(tf(),".config",i),Oi(tf(),".config"),tf()];for(let w of y){if(r)ut.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:r});if(h){if(r)ut.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,f,n,r,c,l){let y=l?Tr(i,n,c):n;try{let w=Oi(f,"package.json");if(!YE(w))return null;let u={};try{u=JSON.parse(BE(w,"utf8"))}catch(A){if(c)ut.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)ut.success(`Configuration loaded from package.json: ${$}`);return{config:Wh(y,h,r),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)ut.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,f,n){if(!f||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Tr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,f,n,r){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,f,n){let r=[];if(f){let c=f(i);if(c)r.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)r.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(r.length>0)throw Tf.configValidation(n||"unknown",r,n)}checkCache(i,t){let f=this.generateCacheKey(i,t);return jr.get(f)||null}cacheResult(i,t,f,n){let r=this.generateCacheKey(i,n);jr.set(r,t,void 0,f.ttl)}generateCacheKey(i,t){let f=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;f.push(`alias:${n}`)}if(t.cwd)f.push(`cwd:${t.cwd}`);if(t.configDir)f.push(`configDir:${t.configDir}`);if("checkEnv"in t)f.push(`checkEnv:${t.checkEnv}`);return f.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Oi(i,"config"),Oi(i,".config"),t?Oi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,f,n){let r=[];return r.push(...this.getLocalSearchPaths(i,t,f,n)),r.push(...this.getHomeSearchPaths(i,t)),r.push(Oi(f,"package.json")),r}getLocalSearchPaths(i,t,f,n){let r=this.getLocalDirectories(f,n),c=[];for(let l of r)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let f=[Oi(tf(),".config",i),Oi(tf(),".config"),tf()],n=[];for(let r of f)n.push(...this.fileLoader.generateConfigPaths(i,r,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var TX=new Sh;function Tr(i,t,f=!1){let n=new tl,r=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${r}_${$.join("_").toUpperCase()}`,`${r}_${$.map((E)=>E.toUpperCase()).join("")}`,`${r}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=Mr.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var EX=Oi(Mr.cwd(),"config"),YX=Oi(Mr.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",XB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:nl(fl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:nl(fl(),".stacks","ssl","stacks.localhost.crt"),keyPath:nl(fl(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Jh=XB;import{execSync as ef}from"node:child_process";import{homedir as FB}from"node:os";import{join as KB}from"node:path";function NB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Qt(i){try{return on(i)}catch{return null}}function rl(i){try{return $c(i)||null}catch{return null}}function cl(i,t){try{return t.every((f)=>Tc(i,f))}catch{return!1}}function SB(i,t,f=443){return Ac(i,t,f)}function JB(i){let t=[];for(let f of i.split(`
132
+ `)){let n=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)t.push(n[1].toUpperCase())}return t}var Pi="-d -r trustRoot -p ssl -p basic",Et="/Library/Keychains/System.keychain",ll="rpx.localhost";function qf(){return KB(FB(),"Library/Keychains/login.keychain-db")}function yl(){return[Et,qf()]}function Fh(i,t=ll){let f=ef(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let r of f.split(`
133
+ `)){let c=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)n.push(c[1].toUpperCase())}return n}function Hr(i){if(process.platform!=="darwin")return;let t=Qt(i.caPath);if(!t)return;let f=i.commonName??ll,n=i.keychains??yl();for(let r of n)for(let c of Fh(r,f)){if(c===t)continue;try{if(r.startsWith("/Library"))Nt(`security delete-certificate -Z ${c} "${r}"`);else ef(`security delete-certificate -Z ${c} "${r}"`,{stdio:"ignore"});Y("ssl",`Removed stale Root CA ${c} from ${r}`,i.verbose)}catch{}}}function Lf(i,t,f){if(process.platform!=="darwin")return xf(i,f);try{let r=ef(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return Y("ssl",`verify-cert ${t}: ${r?"trusted":"not trusted"}`,f?.verbose),r}catch{return!1}}function xf(i,t){let f=Qt(i);if(!f)return!1;for(let n of yl())try{let r=ef(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let c of r.split(`
134
+ `))if(c.toUpperCase().includes("SHA-256")){if(c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===f)return Y("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}function wl(i,t){if(process.platform!=="darwin")return!1;let f=t.serverName;Hr({caPath:i,commonName:t.commonName,verbose:t.verbose});let n=qf();try{ef(`security add-trusted-cert ${Pi} -k "${n}" "${i}"`,{stdio:"ignore"})}catch{}try{Nt(`security add-trusted-cert ${Pi} -k ${Et} "${i}"`)}catch{return!1}return Lf(i,f,{verbose:t.verbose})||xf(i,{verbose:t.verbose})}var St=null,Al=d(Ef(),".stacks","ssl","rpx.localhost.crt");function Oh(i,t){return[...new Set(i.filter(Boolean))].map((f)=>({serverName:f,cert:t.cert,key:t.key}))}function Gh(i,t,f){let n=d(Ef(),".stacks","ssl"),r=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:Al,keyPath:d(n,"rpx.localhost.key"),caCertPath:d(n,"rpx.localhost.ca.crt"),commonName:t},verbose:f,regenerateUntrustedCerts:!0,proxies:r.map((c)=>({from:"localhost:1",to:c,cleanUrls:!1}))}}var IB="rpx-root-ca.crt",_B="rpx-root-ca.key";function Tl(i){return{caCertPath:d(i,IB),caKeyPath:d(i,_B)}}function gX(i){return{certPath:d(i,"rpx.localhost.crt"),keyPath:d(i,"rpx.localhost.key"),caCertPath:d(i,"rpx.localhost.ca.crt"),rootCA:Tl(i)}}async function zB(i,t){try{let[f,n]=await Promise.all([Z.readFile(i.caCertPath,"utf8"),Z.readFile(i.caKeyPath,"utf8")]);if(!f.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return Y("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:f,privateKey:n}}catch(f){return Y("ssl",`No existing Root CA at ${i.caCertPath} (${f.code||f}), will create one`,t),null}}function Kh(i){let t=new Set;t.add(i);let f=i.split(".");if(f.length>=3){let n=f[f.length-1],r=f[f.length-2],c=new Set(["co","com","org","net","ac","gov","edu"]);if(!(f.length===3&&n.length===2&&c.has(r)))t.add(`*.${f.slice(1).join(".")}`)}return Array.from(t)}function ah(i){let f=$l(i).replace(/\*/g,"wildcard"),n=d(Ef(),".stacks","ssl"),r=n;if(typeof i?.https==="object")return r=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:n,{caCertPath:i.https.caCertPath||d(r,`${f}.ca.crt`),certPath:i.https.certPath||d(r,`${f}.crt`),keyPath:i.https.keyPath||d(r,`${f}.key`)};return{caCertPath:d(r,`${f}.ca.crt`),certPath:d(r,`${f}.crt`),keyPath:d(r,`${f}.key`)}}function Ih(i){let t=new Set;if(er(i))i.proxies.forEach((f)=>{let n=f.to||"rpx.localhost";Kh(n).forEach((r)=>t.add(r))});else if(zh(i)){let f=i.to||"rpx.localhost";Kh(f).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function kX(i){Y("ssl","Loading SSL configuration",i.verbose);let t={...Jh,...i};if(i.https=Bl(t),!i.https?.keyPath&&!i.https?.certPath)return Y("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let f=!i.https?.keyPath?"keyPath":"certPath";throw Y("ssl",`Invalid SSL configuration - missing ${f}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${f}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{Y("ssl","Reading SSL certificate files",i.verbose);let f=await Z.readFile(i.https?.keyPath,"utf8"),n=await Z.readFile(i.https?.certPath,"utf8");return Y("ssl","SSL configuration loaded successfully",i.verbose),{key:f,cert:n}}catch(f){return Y("ssl",`Failed to read certificates: ${f}`,i.verbose),null}}catch(f){throw Y("ssl",`SSL configuration error: ${f}`,i.verbose),f}}async function VX(i,t){if(si.platform==="darwin")return QB(i,t);if(si.platform==="linux")try{let{exec:f}=await import("node:child_process");return await new Promise((n)=>{f(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(r)=>{if(!r)n(!0);else f(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(c)=>{n(!c)})})})}catch{return!1}return!1}async function QB(i,t){if(si.platform!=="darwin")return!1;let f=t?.serverName??"rpx.localhost",n=t?.verbose??!1;try{if(Lf(i,f,{verbose:n}))return Y("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return Y("ssl","Trusting Root CA for browsers (login + system keychains)",n),wl(i,{serverName:f,verbose:n})}catch{return!1}}async function Hh(i){if(St&&!i.forceRegenerate){Y("ssl","Using cached SSL configuration",i.verbose);return}El();let t=er(i)?i.proxies.map((h)=>h.to):[i.to];Y("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let f=Bl(i,i.verbose),n=f.basePath||d(Ef(),".stacks","ssl");await Z.mkdir(n,{recursive:!0});let r=Tl(n),c=await zB(r,i.verbose),l=!1;if(!c){if(i.verbose)F.info("Generating Root CA certificate (one-time)...");c=await uc(f);try{await Promise.all([Z.writeFile(r.caCertPath,c.certificate),Z.writeFile(r.caKeyPath,c.privateKey,{mode:384})]),l=!0,Y("ssl",`Persisted Root CA at ${r.caCertPath}`,i.verbose)}catch(h){throw Y("ssl",`Error saving Root CA files: ${h}`,i.verbose),Error(`Failed to save Root CA files: ${h}`)}}else Y("ssl",`Reusing existing Root CA from ${r.caCertPath}`,i.verbose);if(i.verbose)F.info(`Generating host certificate for: ${t.join(", ")}`);let y=await hc({...f,rootCA:{certificate:c.certificate,privateKey:c.privateKey}});try{await Promise.all([Z.writeFile(f.certPath,y.certificate),Z.writeFile(f.keyPath,y.privateKey),Z.writeFile(f.caCertPath,c.certificate)]),Y("ssl","Certificate files saved successfully",i.verbose)}catch(h){throw Y("ssl",`Error saving certificate files: ${h}`,i.verbose),Error(`Failed to save certificate files: ${h}`)}if(l?!1:await eh(r.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(Y("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)F.success("Root CA is already trusted in system trust store");if(St={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)F.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)F.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(si.platform==="darwin")try{Hr({caPath:r.caCertPath,verbose:i.verbose});let h=qf();try{ul(`security add-trusted-cert ${Pi} -k "${h}" "${r.caCertPath}"`,{stdio:"ignore"})}catch{}if(Nt(`security add-trusted-cert ${Pi} -k ${Et} "${r.caCertPath}"`),i.verbose)F.success("Successfully added Root CA to system trust store");u=!0;let $=d(n,"trust-rpx-cert.sh"),A=`#!/bin/bash
135
+ echo "Trusting RPX Root CA"
136
+ # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
137
+ # non-interactive. Without it, fall back to a normal sudo prompt.
138
+ if [ -n "$SUDO_PASSWORD" ]
139
+ then
140
+ printf '%s
141
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pi} -k ${Et} "${r.caCertPath}"
142
+ else
143
+ sudo security add-trusted-cert ${Pi} -k ${Et} "${r.caCertPath}"
144
+ fi
145
+ echo "Root CA trusted! Please restart your browser."
146
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
147
+ `;await Z.writeFile($,A,{mode:493})}catch(h){if(i.verbose)F.warn(`Could not add Root CA to trust store automatically: ${h}`);let $=d(n,"trust-rpx-cert.sh"),A=`#!/bin/bash
148
+ echo "Trusting RPX Root CA"
149
+ # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
150
+ # non-interactive. Without it, fall back to a normal sudo prompt.
151
+ if [ -n "$SUDO_PASSWORD" ]
152
+ then
153
+ printf '%s
154
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pi} -k ${Et} "${r.caCertPath}"
155
+ else
156
+ sudo security add-trusted-cert ${Pi} -k ${Et} "${r.caCertPath}"
157
+ fi
158
+ echo "Root CA trusted! Please restart your browser."
159
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
160
+ `;if(await Z.writeFile($,A,{mode:493}),i.verbose)F.info(`Created a trust helper script at: ${$}`),F.info(`If you're still having certificate issues, run: sh ${$}`)}else if(si.platform==="linux")try{let{exec:h}=await import("node:child_process"),$="/usr/local/share/ca-certificates/rpx",A=`
161
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
162
+ cp "${r.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
163
+ update-ca-certificates
164
+ echo "RPX Root CA installed. Please restart your browser."
165
+ `,T=d(hl.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((C)=>{h(`sudo bash "${T}"`,(E)=>{if(E){if(i.verbose)F.warn(`Could not trust certificates: ${E}`);C(!1)}else{if(i.verbose)F.success("Successfully added certificates to system trust store");C(!0)}})}),await Z.unlink(T).catch(()=>{}),u=!0}catch(h){if(i.verbose)F.warn(`Failed to trust certificates: ${h}`)}else if(si.platform==="win32")try{let h=`
166
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${r.caCertPath.replace(/\//g,"\\")}")
167
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
168
+ $store.Open("ReadWrite")
169
+ $store.Add($cert)
170
+ $store.Close()
171
+ Write-Host "Root CA trusted successfully!"
172
+ `,$=d(hl.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),ul(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)F.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)F.warn(`Could not trust certificate: ${h}`)}else try{await Ec(y,c.certificate,f),u=!0}catch(h){if(i.verbose)F.warn(`Could not add certificate to trust store: ${h}`)}if(St={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)F.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)F.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),F.warn("This will bypass the warning and you should only need to do it once")}function El(){St=null}async function Yl(i){if(!i)return null;if(St)return St;let t=Bl(i);try{let[f,n,r]=await Promise.all([Z.access(t.keyPath).then(()=>!0).catch(()=>!1),Z.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?Z.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!f||!n)return Y("ssl",`Certificate files don't exist: key=${f}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let c="regenerateUntrustedCerts"in i,l=i.regenerateUntrustedCerts,y=c?l!==!1:!0;Y("ssl",`Trust check: hasFlag=${c}, flagValue=${l}, shouldCheckTrust=${y}`,i.verbose);let w=t.basePath||d(Ef(),".stacks","ssl"),u=Tl(w);if(!(y?await eh(u.caCertPath,i):!0))return Y("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[$,A,T]=await Promise.all([Z.readFile(t.keyPath,"utf8"),Z.readFile(t.certPath,"utf8"),r&&t.caCertPath?Z.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(T&&!T.includes("-----BEGIN CERTIFICATE-----"))return Y("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(er(i))try{let{X509Certificate:C}=await import("node:crypto"),B=new C(A).subjectAltName||"",R=i.proxies.map((N)=>N.to).filter((N)=>!B.includes(`DNS:${N}`));if(R.length>0)return Y("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,i.verbose),null}catch(C){Y("ssl",`Could not verify cert SANs: ${C}`,i.verbose)}return Y("ssl","Successfully loaded existing certificates",i.verbose),St={key:$,cert:A,ca:T},St}catch(f){return Y("ssl",`Error checking existing certificates: ${f}`,i.verbose),null}}function Bl(i,t){let f=$l(i);Y("ssl",`Primary domain: ${f}`,t);let n=ah(i),r=d(Ef(),".stacks","ssl");if(typeof i.https==="object"){let c=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:r,l={domain:f,hostCertCN:f,basePath:c,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||f,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(Ih(i)).map((y)=>({type:2,value:y}))};if(_h(i.https.rootCA))l.rootCA=i.https.rootCA;return l}return{domain:f,hostCertCN:f,basePath:r,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:f,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Ih(i)).map((c)=>({type:2,value:c}))}}async function sX(i,t){let f=ah({to:i,verbose:t}),n=[f.caCertPath,f.certPath,f.keyPath];Y("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((r)=>Qh(r,t)))}async function eh(i,t){try{if(Y("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),si.platform==="darwin"){if(t?.serverName)return Lf(i,t.serverName,{verbose:t?.verbose});return xf(i,{verbose:t?.verbose})}else if(si.platform==="win32")try{let f=rl(i)||"";if(!f)return Y("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${f}*' } | Select-Object Subject"`;if(ul(n).toString().includes(f))return Y("ssl","Certificate found in trusted root store",t?.verbose),!0;return Y("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(f){return Y("ssl",`Error checking certificate trust on Windows: ${f}`,t?.verbose),!1}else if(si.platform==="linux")try{let f=Qt(i);if(!f)return Y("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let r of n){let c;try{c=await Z.readdir(r)}catch{continue}for(let l of c){let y=Qt(Mh.join(r,l));if(y&&y===f)return Y("ssl",`Certificate fingerprint found in ${r}`,t?.verbose),!0}}return Y("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(f){return Y("ssl",`Error checking certificate trust on Linux: ${f}`,t?.verbose),!1}return Y("ssl",`Platform ${si.platform} not supported for certificate trust check`,t?.verbose),!1}catch(f){return Y("ssl",`Error checking if certificate is trusted: ${f}`,t?.verbose),!1}}function MB(i){return{enabled:i?.enabled??!1,path:i?.path??"/",interval:i?.interval??1e4,timeout:i?.timeout??2000,healthyThreshold:i?.healthyThreshold??2,unhealthyThreshold:i?.unhealthyThreshold??3}}function OB(i){return(Array.isArray(i)?i:[i]).map((f)=>{let n=typeof f==="string"?{url:f}:f;return{url:n.url,weight:n.weight&&n.weight>0?n.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function qh(i){return(Array.isArray(i)?i:[i]).map((f)=>typeof f==="string"?f:f.url)}function Lh(i){if(!i)return"localhost:5173";let t=Array.isArray(i)?i[0]:i;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function xh(i,t){return{upstreams:OB(i),strategy:t?.strategy??"round-robin",healthCheck:MB(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function GB(i){let t=i.upstreams.filter((f)=>f.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function aB(i,t){let f=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[f]}function HB(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let f=t.reduce((r,c)=>r+c.weight,0),n=0;for(let r=0;r<t.length;r++)if(i.wrrCurrentWeights[r]+=t[r].weight,i.wrrCurrentWeights[r]>i.wrrCurrentWeights[n])n=r;return i.wrrCurrentWeights[n]-=f,t[n]}function eB(i){let t=i[0];for(let f=1;f<i.length;f++)if(i[f].activeConnections<t.activeConnections)t=i[f];return t}function gh(i){let t=GB(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return HB(i,t);case"least-connections":return eB(t);case"round-robin":default:return aB(i,t)}}function qr(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function gf(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function qB(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let f=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(f)?f:80}}async function LB(i,t){let{hostname:f,port:n}=qB(t.url),r=new AbortController,c=setTimeout(()=>r.abort(),i.healthCheck.timeout);try{(await fetch(`http://${f}:${n}${i.healthCheck.path}`,{signal:r.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),qr(i,t)}catch{gf(i,t)}finally{clearTimeout(c)}}function kh(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let f of i.upstreams)LB(i,f)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function Cl(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as sh,timingSafeEqual as Vh}from"node:crypto";import{readFileSync as xB}from"node:fs";var gB="/.well-known/acme-challenge/";function kf(i,t){let f=Buffer.from(i,"utf8"),n=Buffer.from(t,"utf8");if(f.length!==n.length)return Vh(f,f),!1;return Vh(f,n)}function kB(i,t){let f=(A)=>sh("md5").update(A).digest(),n=Buffer.from(i,"utf8"),r=Buffer.from(t,"utf8"),c=f(Buffer.concat([n,r,n])),l=[n,Buffer.from("$apr1$","utf8"),r];for(let A=n.length;A>0;A-=16)l.push(c.subarray(0,Math.min(A,16)));for(let A=n.length;A>0;A>>=1)l.push(A&1?Buffer.from([0]):n.subarray(0,1));let y=f(Buffer.concat(l));for(let A=0;A<1000;A++){let T=[];if(T.push(A&1?n:y.subarray(0,16)),A%3)T.push(r);if(A%7)T.push(n);T.push(A&1?y.subarray(0,16):n),y=f(Buffer.concat(T))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",u=(A,T)=>{let C="",E=A;for(let B=0;B<T;B++)C+=w[E&63],E>>=6;return C},h=y,$="";return $+=u(h[0]<<16|h[6]<<8|h[12],4),$+=u(h[1]<<16|h[7]<<8|h[13],4),$+=u(h[2]<<16|h[8]<<8|h[14],4),$+=u(h[3]<<16|h[9]<<8|h[15],4),$+=u(h[4]<<16|h[10]<<8|h[5],4),$+=u(h[11],2),`$apr1$${t}$${$}`}function VB(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 kf(kB(i,n),t)}if(t.startsWith("{SHA}")){let f=sh("sha1").update(i,"utf8").digest("base64");return kf(`{SHA}${f}`,t)}return kf(i,t)}function sB(i){let t=new Map;for(let f of i.split(`
173
+ `)){let n=f.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf(":");if(r<=0)continue;t.set(n.slice(0,r),n.slice(r+1))}return t}function Dh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",f=[];if(i.username)f.push({username:i.username,password:i.password??""});for(let c of i.users??[])if(c?.username)f.push({username:c.username,password:c.password??""});let n;if(i.htpasswdFile)try{n=sB(xB(i.htpasswdFile,"utf8"))}catch{n=void 0}if(f.length===0&&(!n||n.size===0))return;return{realm:t,verify:(c,l)=>{let y=!1;for(let w of f)if(kf(c,w.username)&&kf(l,w.password))y=!0;if(n){let w=n.get(c);if(w&&VB(l,w))y=!0}return y}}}function dh(i,t,f){if(t.startsWith(gB))return;let n=i.headers.get("authorization")??"",r=n.indexOf(" "),c=r===-1?n:n.slice(0,r),l=r===-1?"":n.slice(r+1).trim();if(c.toLowerCase()==="basic"&&l){let w="";try{w=Buffer.from(l,"base64").toString("utf8")}catch{w=""}let u=w.indexOf(":");if(u>=0&&f.verify(w.slice(0,u),w.slice(u+1)))return}let y=f.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${y}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:DB}=Bun,Vf=Symbol("rpx.pool.fallback"),Lr=Symbol("rpx.pool.stale");var dB=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function bB(i){return dB.has(i.toUpperCase())}var jl=Symbol("rpx.pool.timeout"),Mt=Symbol("rpx.pool.busy");function PB(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function ZB(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function vB(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function pB(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Ph=1048576;function oB(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var Ul=30000,iC=16384,Zh=262144,tC=2097152,fC=524288,nC=8192,rC=4096,cC=new TextEncoder,vh=new TextDecoder,lC=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class ph{socket=null;buf=new Uint8Array(iC);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,f=t.write(i);while(f<i.length){if(this.closed)throw Lr;await new Promise((n)=>{this.drainWaiter=n}),f+=t.write(i.subarray(f))}}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()>tC)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=fC)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 f=new Uint8Array(Math.max(this.buf.length*2,t));f.set(this.buf.subarray(0,this.len)),this.buf=f}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 oh{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=PB();maxWaiters;checkoutIdleMs=vB();inUse=new Set;constructor(i,t,f,n=""){this.host=i;this.port=t;this.maxTotal=f;this.key=n;this.maxWaiters=ZB(f)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new ph;return DB({hostname:this.host,port:this.port,socket:{data:(t,f)=>i.push(f),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let f=t;f.setNoDelay?.(!0);let n=pB();if(n>0)f.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 Mt;let i=await this.waitForSlot();if(i===Mt)throw Mt;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,f=(c)=>{if(t)return;t=!0,clearTimeout(r),i(c)},n=(c)=>f(c),r=setTimeout(()=>{let c=this.waiters.indexOf(n);if(c!==-1)this.waiters.splice(c,1);f(Mt)},this.queueWaitMs);r.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(Ul,this.checkoutIdleMs):Ul;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-Ul;if(this.idle.length){let f=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else f.push(n);this.idle=f}if(this.checkoutIdleMs>0&&this.inUse.size){let f=i-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=f)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&xr.get(this.key)===this)xr.delete(this.key)}}}var xr=new Map;function yC(i,t){let f=xr.get(i);if(!f){let n=i.lastIndexOf(":"),r=n===-1?i:i.slice(0,n),c=n===-1?80:Number(i.slice(n+1));f=new oh(r,c,t??oB(),i),xr.set(i,f)}return f}function bh(i,t,f){for(let n=f+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 wC(i,t,f){let n=vh.decode(i.subarray(t,f)),r=n.indexOf(`\r
174
+ `),c=r===-1?n:n.slice(0,r),l=c.indexOf(" "),y=Number.parseInt(c.slice(l+1,l+5),10),w=c.startsWith("HTTP/1.0"),u=[],h=-1,$=!1,A=w,T=!1,C=!1,E=r===-1?n.length:r+2;while(E<n.length){let B=n.indexOf(`\r
175
+ `,E);if(B===-1)B=n.length;let U=n.slice(E,B);if(E=B+2,U==="")continue;let R=U.indexOf(":");if(R===-1)continue;let N=U.slice(0,R),J=U.slice(R+1).trim(),I=N.charCodeAt(0)|32;if(I===99||I===116||I===107){let z=N.toLowerCase();if(z==="content-length"){let X=/^\d+$/.test(J)?Number(J):Number.NaN;if(!Number.isSafeInteger(X)||h>=0&&h!==X)C=!0;else h=X;continue}if(z==="transfer-encoding"){if(J.toLowerCase().includes("chunked"))$=!0;continue}if(z==="connection"){let X=J.toLowerCase();if(X.includes("close"))A=!0;if(X.includes("keep-alive"))T=!0;continue}if(z==="keep-alive")continue}u.push([N,J])}if(w&&T)A=!1;if($&&h>=0)h=-1;return{status:y,headerEnd:f,headers:u,contentLength:h,chunked:$,closeConn:A,malformed:C}}function uC(i,t){return t||i===204||i===304}async function i$(i){let{hostPort:t,method:f,path:n,reqHeaders:r,forwardedHost:c,originOverride:l,body:y}=i,w=f==="HEAD",u=r.get("accept")?.toLowerCase()??"";if(r.get("expect")||r.get("upgrade")||u.includes("text/event-stream"))throw Vf;let h=null;if(y){let C=r.get("content-length"),E=C?Number.parseInt(C,10):Number.NaN;if(Number.isNaN(E)||E>Ph)throw Vf;if(h=await BC(y),h===null)throw Vf}let $=YC(f,n,r,t,c,l,h),A=$;if(h&&h.length)A=new Uint8Array($.length+h.length),A.set($),A.set(h,$.length);let T=yC(t,i.maxPerHost);for(let C=0;;C++){if(C>0)await new Promise((B)=>{setTimeout(B,C)});let E;try{E=T.acquireIdleSync()??await T.acquireOrDial()}catch(B){if(B!==Mt&&C<4)continue;throw B}try{let B=E.socket.write(A);if(B<A.length)await E.writeAll(A.subarray(B));return await $C(T,E,w,i.signal)}catch(B){let U=B===Lr&&C<4&&(E.fresh||bB(f));if(T.destroy(E),U)continue;if(B===Lr)throw Error("upstream closed connection");throw B}}}async function hC(i){let t=bh(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw jl;if(i.len===i.pos)throw Lr;throw Error("upstream closed mid-header")}if(i.len-i.pos>Zh)throw Error("upstream header block too large");await i.waitForData(i.len),t=bh(i.buf,i.len,i.pos)}return t}async function $C(i,t,f,n){let r;for(;;){let l=await hC(t);if(r=wC(t.buf,t.pos,l),t.pos=l+4,r.status>=100&&r.status<200)continue;break}if(r.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let c=r.headers;if(uC(r.status,f))return t$(i,t,r.closeConn),new Response(null,{status:r.status,headers:c});if(r.chunked)return new Response(EC(i,t,r.closeConn,n),{status:r.status,headers:c});if(r.contentLength>=0){if(t.len-t.pos>=r.contentLength){let y=t.pos+r.contentLength,w=t.len>y,u=null;if(r.contentLength>=nC)u=t.buf.subarray(t.pos,y),t.buf=new Uint8Array(rC);else if(r.contentLength>0)u=t.buf.slice(t.pos,y);if(t.pos=0,t.len=0,r.closeConn||w)i.destroy(t);else i.release(t);return new Response(u,{status:r.status,headers:c})}return new Response(AC(i,t,r.contentLength,r.closeConn),{status:r.status,headers:c})}return new Response(TC(t),{status:r.status,headers:c})}function t$(i,t,f){if(f||t.pos!==t.len)i.destroy(t);else i.release(t)}function AC(i,t,f,n){let r=t.len-t.pos,c=r>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=f-r,t.queuedBytes=0,t.streamingBody=!0;let l=(y)=>{if(t.bodyQueue=null,n||t.len>0)i.destroy(t);else i.release(t);y.close()};return new ReadableStream({start(y){if(c)y.enqueue(c);if(t.bodyRemaining===0&&t.bodyQueue.length===0)l(y)},async pull(y){for(;;){let w=t.bodyQueue;if(w&&w.length>0){let u=w.shift();if(t.queuedBytes-=u.length,t.resumeIfDrained(),y.enqueue(u),t.bodyRemaining===0&&w.length===0)l(y);return}if(t.bodyRemaining===0){if(t.bodyQueue)l(y);return}if(t.closed){t.bodyQueue=null,i.destroy(t),y.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function TC(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 EC(i,t,f,n){t.streamingBody=!0;let r=0,c=!1,l=!1,y,w=()=>n?.removeEventListener("abort",u),u=()=>{if(l)return;l=!0,i.destroy(t);try{y?.close()}catch{}};async function h($=!1){for(;;){for(let A=t.pos;A+1<t.len;A++)if(t.buf[A]===13&&t.buf[A+1]===10){let T=vh.decode(t.buf.subarray(t.pos,A));return t.pos=A+2,T}if(t.closed){if($&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>Zh)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start($){if(y=$,n?.aborted)u();else n?.addEventListener("abort",u,{once:!0})},async pull($){try{for(;;){if(r>0){if(t.len===t.pos){if(t.closed){i.destroy(t),$.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let E=Math.min(r,t.len-t.pos);if($.enqueue(t.buf.slice(t.pos,t.pos+E)),t.pos+=E,r-=E,t.resumeIfDrained(),r===0)c=!0;return}if(c)await h(),c=!1;let A=await h(!0);if(A===null){i.destroy(t),w(),$.close();return}let T=A.indexOf(";"),C=Number.parseInt(T===-1?A:A.slice(0,T),16);if(!Number.isInteger(C)||C<0){i.destroy(t),$.error(Error("upstream sent malformed chunk size"));return}if(C===0){for(;;)if(await h()==="")break;t$(i,t,f),w(),$.close();return}r=C}}catch(A){if(i.destroy(t),w(),!l)$.error(A)}},cancel(){l=!0,w(),i.destroy(t)}})}function YC(i,t,f,n,r,c,l){let y=`${i} ${t} HTTP/1.1\r
176
+ host: ${n}\r
177
+ x-forwarded-for: 127.0.0.1\r
178
+ x-forwarded-proto: https\r
179
+ x-forwarded-host: ${r}\r
180
+ `;if(c!==void 0)y+=`origin: ${c}\r
181
+ `;let w=!1;for(let[u,h]of f){let $=u.toLowerCase();if(lC.has($))continue;if(c!==void 0&&$==="origin")continue;if($==="content-length")w=!0;y+=`${u}: ${h}\r
182
+ `}if(y+=`connection: keep-alive\r
183
+ `,l&&!w)y+=`content-length: ${l.length}\r
184
+ `;return y+=`\r
185
+ `,cC.encode(y)}async function BC(i){let t=i.getReader(),f=[],n=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(n+=y.length,n>Ph)return t.cancel().catch(()=>{}),null;f.push(y)}}if(f.length===1)return f[0];let r=new Uint8Array(n),c=0;for(let l of f)r.set(l,c),c+=l.length;return r}function iN(i){let t=typeof i==="string"?{to:i}:i,f=(t.to??"").trim();if(f&&!/^[a-z][\w+.-]*:\/\//i.test(f))f=`https://${f}`;return f=f.replace(/\/+$/,""),{to:f,status:t.status??301,preservePath:t.preservePath??!0}}function f$(i,t,f){if(!i.preservePath)return i.to||"/";let n=`${t}${f}`;return n==="/"?`${i.to}/`:`${i.to}${n}`}import*as Hi from"node:path";function n$(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 CC={".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 UC(i){let t=Hi.extname(i).toLowerCase();return CC[t]??"application/octet-stream"}function jC(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let f=Hi.posix.normalize(`/${t}`);if(f.split("/").includes(".."))return null;return f.replace(/^\/+/,"")}function mC(i,t){let f=jC(i);if(f===null)return null;let n=Hi.posix.extname(f);if(t.cleanUrls&&n===".html"){let r=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Hi.join(t.dir,f),redirectTo:r||"/"}}if(f===""||i.endsWith("/"))return{filePath:Hi.join(t.dir,f,"index.html")};if(n!=="")return{filePath:Hi.join(t.dir,f)};if(t.pathRewriteStyle==="flat")return{filePath:Hi.join(t.dir,`${f}.html`)};return{filePath:Hi.join(t.dir,f,"index.html")}}async function r$(i,t){let f=mC(i,t);if(!f)return new Response("Forbidden",{status:403});if(f.redirectTo)return new Response(null,{status:301,headers:{Location:f.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",r=Bun.file(f.filePath);if(await r.exists())return new Response(r,{status:200,headers:{"Content-Type":UC(f.filePath),"Cache-Control":n}});if(t.spa){let c=Hi.join(t.dir,"index.html"),l=Bun.file(c);if(await l.exists())return new Response(l,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}function RC(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var WC=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),XC=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],NC=1024;function SC(i){if(!i)return!1;let t=null;for(let f of i.split(",")){let[n,...r]=f.trim().split(";"),c=n.trim().toLowerCase();if(c!=="gzip"&&c!=="*")continue;let l=1;for(let y of r){let w=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(y);if(w)l=Number.parseFloat(w[1])}if(c==="gzip")return Number.isFinite(l)&&l>0;t=l}return t!==null&&Number.isFinite(t)&&t>0}function JC(i){let t=i.get("vary");if(!t){i.set("vary","Accept-Encoding");return}if(!t.split(",").some((f)=>f.trim().toLowerCase()==="accept-encoding"))i.set("vary",`${t}, Accept-Encoding`)}function FC(i,t){if(i.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||i.headers.has("range")||!SC(i.headers.get("accept-encoding")))return t;let f=t.headers.get("content-type")?.toLowerCase()??"";if(!XC.some((c)=>f.startsWith(c)))return t;let n=t.headers.get("content-length");if(n!==null){let c=Number.parseInt(n,10);if(Number.isFinite(c)&&c<NC)return t}let r=new Headers(t.headers);return r.set("content-encoding","gzip"),JC(r),r.delete("content-length"),r.delete("content-md5"),r.delete("content-digest"),r.delete("accept-ranges"),r.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:r})}function KC(i){let t=i.headers.get("host")||"",f=t.indexOf(":");return f===-1?t:t.slice(0,f)}function w$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let f=i.slice(t.length);return f===""?"/":f}return i}function c$(i){if(i.upstreamPool)return gh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function l$(i,t,f,n){let r=f?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?w$(i,t.basePath):i,y=y$(l,t.pathRewrites);if(y)r=y.targetHost,l=y.targetPath,Y("request",`Path rewrite: ${i} → ${r}${l}`,n);return{targetHost:r,targetPath:l}}function IC(i){let t=i.indexOf("://"),f=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(f===-1)return{pathname:"/",search:""};let n=i.indexOf("?",f);if(n===-1)return{pathname:i.slice(f),search:""};return{pathname:i.slice(f,n),search:i.slice(n)}}function ml(i,t,f){let n=async(r,c)=>{let{pathname:l,search:y}=IC(r.url),w=KC(r),u=i(w,l);if(!u&&f){let B=await f(w,l,r);if(B instanceof Response)return B;if(B&&B.retry)u=i(w,l)}if(!u)return Y("request",`No route found for host: ${w}`,t),new Response(`No proxy configured for ${w}`,{status:404});if(u.auth){let B=dh(r,l,u.auth);if(B)return Y("request",`401 challenge for ${w}${l}`,t),B}if(u.redirect){let B=f$(u.redirect,l,y);return Y("request",`${u.redirect.status} redirect ${w}${l} → ${B}`,t),new Response(null,{status:u.redirect.status,headers:{location:B}})}if(u.static){let U=u.stripBasePathPrefix??!0?w$(l,u.basePath):l;return r$(U,u.static)}if(r.headers.get("upgrade")?.toLowerCase()==="websocket"){let B=c$(u);if(!c||!B)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:U,targetPath:R}=l$(l,u,B,t),N=`ws://${U}${R}${y}`,J={};for(let[X,li]of r.headers)if(!WC.has(X.toLowerCase())&&X.toLowerCase()!=="host")J[X]=li;J.host=U,J["x-forwarded-for"]="127.0.0.1",J["x-forwarded-proto"]="https",J["x-forwarded-host"]=w;let I={targetUrl:N,forwardHeaders:J};if(c.upgrade(r,{data:I})){Y("ws",`upgraded ${w}${R} → ${N}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=c$(u);if(!h)return new Response(`No upstream configured for ${w}`,{status:502});if(u.cleanUrls&&l.endsWith(".html")){let B=l.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:B}})}let{targetHost:$,targetPath:A}=l$(l,u,h,t),T=u.changeOrigin?`http://${$}`:void 0,C=r.body!=null&&r.method!=="GET"&&r.method!=="HEAD",E=u.upstreamPool;if(E)h.activeConnections++;try{let B=await i$({hostPort:$,method:r.method,path:`${A}${y}`,reqHeaders:r.headers,forwardedHost:w,originOverride:T,body:r.body,signal:r.signal});if(E)qr(E,h);return B}catch(B){if(B===jl){if(Y("request",`Upstream timeout for ${w}`,t),E)gf(E,h);return new Response("Gateway Timeout",{status:504})}if(B===Mt)return Y("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(B===Vf||!C)try{let U=new Headers(r.headers);if(U.set("host",$),U.set("x-forwarded-for","127.0.0.1"),U.set("x-forwarded-proto","https"),U.set("x-forwarded-host",w),T!==void 0)U.set("origin",T);let R=await fetch(`http://${$}${A}${y}`,{method:r.method,headers:U,body:r.body,redirect:"manual"});if(E)qr(E,h);return R}catch(U){if(Y("request",`Proxy error for ${w}: ${U}`,t),E)gf(E,h);return new Response(`Proxy Error: ${U}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)gf(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)h.activeConnections--}};return async(r,c)=>{try{let l=await n(r,c);return l?FC(r,l):l}catch(l){return Y("request",`Unhandled proxy handler error: ${l}`,t),new Response("Bad Gateway",{status:502})}}}function Rl(i){let t=new WeakMap,f=RC();return{open(n){let{targetUrl:r,forwardHeaders:c}=n.data,l;try{l=new WebSocket(r,{headers:c})}catch(w){Y("ws",`failed to open upstream ${r}: ${w}`,i),n.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,y),l.addEventListener("open",()=>{y.upstreamOpen=!0;for(let w of y.pending)l.send(w);y.pending=[],y.pendingBytes=0}),l.addEventListener("message",(w)=>{n.send(w.data)}),l.addEventListener("close",(w)=>{try{n.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{Y("ws",`upstream error for ${r}`,i);try{n.close(1011,"upstream error")}catch{}})},message(n,r){let c=t.get(n);if(!c)return;let l=typeof r==="string"?r:new Uint8Array(r);if(c.upstreamOpen){c.upstream.send(l);return}let y=typeof l==="string"?Buffer.byteLength(l):l.byteLength;if(c.pendingBytes+y>f){Y("ws",`pending buffer would exceed ${f}B before upstream open; closing socket`,i);try{n.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}c.pending.push(l),c.pendingBytes+=y},close(n,r,c){let l=t.get(n);if(!l)return;t.delete(n);try{l.upstream.close(r||1000,c||"")}catch{}}}}import*as h$ from"node:fs";import*as $$ from"node:path";var u$="/.well-known/acme-challenge/";function A$(i,t){if(!i||!t.startsWith(u$))return null;let f=t.slice(u$.length);if(!f||!/^[A-Za-z0-9_-]+$/.test(f))return null;try{return h$.readFileSync($$.join(i,f),"utf8")}catch{return null}}function gr(i){return i.startsWith("*.")}function Wl(i,t){if(!gr(t))return!1;let f=t.slice(1);return i.length>f.length&&i.endsWith(f)}function T$(i,t){let f=i.get(t);if(f!==void 0)return f;let n,r=-1;for(let[c,l]of i){if(!gr(c))continue;if(Wl(t,c)){let y=c.length-1;if(y>r)r=y,n=l}}return n}function Ot(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function _C(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Xl(i){let t=new Map;for(let n of i){let r=Ot(n.path),c=t.get(n.host);if(!c)c=new Map,t.set(n.host,c);c.set(r,n.route)}let f=new Map;for(let[n,r]of t){let c=[];for(let[l,y]of r)c.push({path:l,route:y});c.sort((l,y)=>y.path.length-l.path.length),f.set(n,c)}return f}function Nl(i,t){let f=i.get(t);if(f!==void 0)return f;let n,r=-1;for(let[c,l]of i){if(!gr(c))continue;if(Wl(t,c)){let y=c.length-1;if(y>r)r=y,n=l}}return n}function Sl(i,t,f){let n=Nl(i,t);if(!n)return;for(let r of n)if(_C(f,r.path))return r.route;return}import*as sf from"node:fs/promises";import*as Jl from"node:path";function Df(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function zC(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 QC(i,t,f,n){try{let[r,c]=await Promise.all([sf.readFile(t,"utf8"),sf.readFile(f,"utf8")]);return{serverName:i,cert:r,key:c}}catch(r){return Y("sni",`skipping ${i}: ${r.message}`,n),null}}async function Fl(i,t){let f=new Map,n=i.certsDirServerNames?new Set(i.certsDirServerNames):void 0;if(i.certsDir){let c=[];try{c=await sf.readdir(i.certsDir)}catch(l){Y("sni",`certsDir read failed (${i.certsDir}): ${l.message}`,t)}for(let l of c){let y=zC(l);if(!y)continue;if(n&&!n.has(y))continue;let w=l.slice(0,-4);f.set(y,{certPath:Jl.join(i.certsDir,l),keyPath:Jl.join(i.certsDir,`${w}.key`)})}}if(i.domains)for(let[c,l]of Object.entries(i.domains))f.set(c,l);let r=[];for(let[c,l]of f){let y=await QC(c,l.certPath,l.keyPath,t);if(y)r.push(y)}return r}import*as Di from"node:fs/promises";import*as kr from"node:path";function Kl(i=process.env){let t=i.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return i.INVOCATION_ID?"restart":"rebind"}var MC="acme-account.key",OC=60000,E$=4096;function GC(i,t){if(!t||t.length===0)return!1;return t.some((f)=>{let n=f.startsWith(".")?f.slice(1):f;return i===n||i.endsWith(`.${n}`)})}function Y$(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 Vr{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??Dn,this.issuer=i.issuer??P0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??OC;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(!Y$(i))return!1;if(GC(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return Y("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(!Y$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let f=this.negativeCache.get(i);if(f!==void 0&&Date.now()<f){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return Y("on-demand",`${i} negatively cached for ${f-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 Y("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{Y("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(i,t.fullChainPem,t.keyPem);let f={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,f),this.negativeCache.delete(i),Y("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),Y("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=E$){let t=Date.now();for(let[f,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(f);if(this.negativeCache.size>=E$){let f=this.negativeCache.keys().next().value;if(f!==void 0)this.negativeCache.delete(f)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:f}=this.pathsFor(i);try{let[n,r]=await Promise.all([Di.readFile(t,"utf8"),Di.readFile(f,"utf8")]),c={serverName:i,cert:n,key:r};return this.certs.set(i,c),Y("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:kr.join(this.certsDir,`${i}.crt`),keyPath:kr.join(this.certsDir,`${i}.key`)}}async persist(i,t,f){await Di.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:r}=this.pathsFor(i);await Promise.all([Di.writeFile(n,t,"utf8"),Di.writeFile(r,f,{encoding:"utf8",mode:384})])}get accountKeyPath(){return kr.join(this.certsDir,MC)}async loadAccountKey(){try{return await Di.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(i){if(!i||this.accountKeyPem===i)return;this.accountKeyPem=i,await Di.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Di.writeFile(this.accountKeyPath,i,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as aC,readdirSync as HC,readFileSync as eC,statSync as qC}from"node:fs";import{homedir as U$}from"node:os";import{isAbsolute as LC,join as Yf}from"node:path";var j$=["~/Code"],m$=["localhost","test"],xC=1800000,Il={dirExists:(i)=>{try{return qC(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return aC(i)}catch{return!1}},readText:(i)=>{try{return eC(i,"utf8")}catch{return null}}};function _l(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Yf(t,i.slice(2));return i}function gC(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function B$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function kC(i,t){for(let f of t){let n=`.${f}`;if(i.endsWith(n)){let r=i.slice(0,-n.length);if(r.length>0&&!r.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(r))return r}}return null}function VC(i,t){let f=t.readText(Yf(i,"rpx.site.json"));if(f)try{let r=JSON.parse(f);if(r&&typeof r==="object")return r}catch{}let n=t.readText(Yf(i,"package.json"));if(n)try{let r=JSON.parse(n);if(r.rpx&&typeof r.rpx==="object")return r.rpx}catch{}return null}function sC(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 DC(i,t){let f=VC(i,t);if(f?.command)return sC(f);let n=t.fileExists(Yf(i,"buddy")),r=t.readText(Yf(i,"package.json")),c=null;if(r)try{c=JSON.parse(r)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(n||Object.keys(l).some((w)=>w==="stacks"||w.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(c?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function zl(i,t={}){let f={dirExists:t.dirExists??Il.dirExists,fileExists:t.fileExists??Il.fileExists,readText:t.readText??Il.readText},n=t.detect??DC,r=t.homeDir??U$(),c=i.tlds??m$,l=(i.roots??j$).map((A)=>_l(A,r)),y=i.idleTimeoutMs??xC,w=new Map;for(let A of i.sites??[])w.set(A.to,A);let u=(A)=>A.idleTimeoutMs??y;function h(A){let T=T$(w,A);if(!T)return null;let C=LC(T.dir)?T.dir:_l(T.dir,r),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=n(C,f)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let U=C$({...T.env??{}},void 0,A);return{host:A,id:B$(A),dir:C,command:T.command,env:U,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=kC(A,c);if(!T)return null;for(let C of l){let E=Yf(C,T);if(!f.dirExists(E))continue;let B=n(E,f);if(!B)continue;let U=B.selfRegisters??!1;return{host:A,id:B$(A),dir:E,command:B.command,env:C$({...B.env??{}},B.urlEnv,A),routes:U?[]:B.routes??[],selfRegisters:U,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=gC(A);if(!T)return null;return h(T)??$(T)}}}function dC(i){try{return HC(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function XN(i,t={}){let f=t.homeDir??U$(),n=i.tlds??m$,r=(i.roots??j$).map(($)=>_l($,f)),c=t.readdir??dC,l=zl(i,t),y=[],w=new Set,u=($)=>{if($&&!w.has($.host))w.add($.host),y.push($)};for(let $ of i.sites??[])if(!$.to.includes("*"))u(l.resolve($.to));let h=n[0]??"localhost";for(let $ of r)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function C$(i,t,f){if(!t)return i;let n=`https://${f}`;for(let r of t)if(i[r]===void 0)i[r]=n;return i}import{closeSync as J$,openSync as pC,readFileSync as oC}from"node:fs";import*as F$ from"node:fs/promises";import{spawn as iU}from"node:child_process";import{homedir as tU}from"node:os";import*as bf from"node:path";import*as di from"node:process";import*as sr from"node:net";function W$(i,t,f){return Y("port",`Checking if port ${i} is in use on ${t}`,f),new Promise((n)=>{let r=sr.createServer(),c=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,f),r.close(),n(!0)},3000);r.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,f),n(!0);else Y("port",`Error checking port ${i}: ${l.message}`,f),n(!0)}),r.once("listening",()=>{clearTimeout(c),Y("port",`Port ${i} is available`,f),r.close(),n(!1)});try{r.listen(i,t)}catch(l){clearTimeout(c),Y("port",`Exception checking port ${i}: ${l}`,f),n(!0)}})}async function Ql(i,t,f,n=50){Y("port",`Finding available port starting from ${i} (max attempts: ${n})`,f);let r=i,c=0;while(c<n){if(c++,!await W$(r,t,f))return Y("port",`Found available port: ${r} after ${c} attempts`,f),r;Y("port",`Port ${r} is in use, trying ${r+1} (attempt ${c}/${n})`,f),r++}throw Error(`Unable to find available port after ${n} attempts starting from ${i}`)}function R$(i,t,f=5000,n){return Y("port",`Testing connection to ${t}:${i}`,n),new Promise((r)=>{let c=sr.connect({host:t,port:i,timeout:f});c.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,n),c.end(),r(!0)}),c.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,n),c.destroy(),r(!1)}),c.once("error",(l)=>{Y("port",`Failed to connect to ${t}:${i}: ${l.message}`,n),c.destroy(),r(!1)})})}class X${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,f=50){this.hostname=i,this.verbose=t,this.maxRetries=f}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await W$(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await R$(i,this.hostname,3000,this.verbose))return Y("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 f=await Ql(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await R$(f,this.hostname,3000,this.verbose))if(f<i+this.maxRetries)return this.findNextAvailablePort(f+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(f),f}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var JN=new X$;import*as Dr from"node:fs";import*as mi from"node:fs/promises";import{homedir as bC}from"node:os";import*as Ml from"node:path";import*as dr from"node:process";var PC=/^[a-zA-Z0-9._-]+$/;function Jt(){return Ml.join(bC(),".stacks","rpx","registry.d")}function Ol(i){return typeof i==="string"&&i.length>0&&i.length<=128&&PC.test(i)}function Gl(i,t){if(!Ol(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Ml.join(i,`${t}.json`)}function Ri(i){if(!Number.isInteger(i)||i<=0)return!1;try{return dr.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function N$(i){if(!i||typeof i!=="object")return!1;let t=i,f=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,r=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",c=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&Ol(t.id)&&(n||r)&&typeof t.to==="string"&&t.to.length>0&&c&&f&&typeof t.createdAt==="string"}async function ZC(i){await mi.mkdir(i,{recursive:!0})}async function S$(i,t=Jt(),f){if(!N$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await ZC(t);let n=Gl(t,i.id),r=`${n}.tmp.${dr.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await mi.writeFile(r,c,{encoding:"utf8",mode:420}),await mi.rename(r,n),Y("registry",`wrote entry ${i.id} → ${n}`,f)}catch(l){throw await mi.unlink(r).catch(()=>{}),l}}async function al(i,t=Jt(),f){let n=Gl(t,i);try{await mi.unlink(n),Y("registry",`removed entry ${i}`,f)}catch(r){if(r.code!=="ENOENT")throw r}}async function vC(i,t=Jt(),f){let n=Gl(t,i);try{let r=await mi.readFile(n,"utf8"),c=JSON.parse(r);if(!N$(c))return Y("registry",`entry ${i} failed validation, removing`,f),await mi.unlink(n).catch(()=>{}),null;return c}catch(r){if(r.code==="ENOENT")return null;if(r instanceof SyntaxError)return Y("registry",`entry ${i} has invalid JSON, removing`,f),await mi.unlink(n).catch(()=>{}),null;throw r}}async function Yt(i=Jt(),t){let f;try{f=await mi.readdir(i)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of f){if(!r.endsWith(".json"))continue;let c=r.slice(0,-5);if(!Ol(c))continue;let l=await vC(c,i,t);if(l)n.push(l)}return n}async function df(i=Jt(),t){let f=await Yt(i,t),n=0;for(let r of f){if(r.pid===void 0)continue;if(!Ri(r.pid))Y("registry",`GC: pid ${r.pid} for ${r.id} is dead, removing`,t),await al(r.id,i,t).catch(()=>{}),n++}return n}function br(i,t={}){let f=t.dir??Jt(),n=t.debounceMs??100,r=t.pollMs??Math.max(n*2,250),c=t.verbose;Dr.mkdirSync(f,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((U)=>({id:U.id,from:U.from,to:U.to,path:U.path,pid:U.pid,pathRewrites:U.pathRewrites,cleanUrls:U.cleanUrls,changeOrigin:U.changeOrigin,static:U.static,loadBalancer:U.loadBalancer})).sort((U,R)=>U.id.localeCompare(R.id)))},$=()=>{if(l=null,y)return;Yt(f,c).then((B)=>{return w=h(B),i(B)}).catch((B)=>{Y("registry",`watcher onChange failed: ${B}`,c)})},A=()=>{if(y)return;if(l)clearTimeout(l);l=setTimeout($,n)},C=setInterval(()=>{if(y||u)return;u=!0,Yt(f,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},r),E=Dr.watch(f,{persistent:!0},(B,U)=>{if(U&&/\.tmp\.\d+\.\d+$/.test(U))return;A()});return E.on("error",(B)=>{Y("registry",`watcher error: ${B}`,c)}),A(),{close:()=>{if(y=!0,l)clearTimeout(l);clearInterval(C),E.close()}}}var fU=120000,nU=200,rU=30000,cU=3000,lU=4000;class el{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??Jt(),this.rpxDir=i.rpxDir??bf.join(tU(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??fU,this.pollIntervalMs=i.pollIntervalMs??nU,this.restartDelayMs=i.restartDelayMs??cU,this.killGraceMs=i.killGraceMs??lU,this.launch=i.launcher??wU(this.verbose),this.probePort=i.probePort??yU,this.pickPort=i.pickPort??((f)=>Ql(f,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??S$,this.removeEntry=i.removeEntry??al;let t=i.reapIntervalMs??rU;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 f=this.resolver.resolve(i);if(!f)return{kind:"unknown"};t=await this.start(f)}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 y of i.routes){if(t.has(y.portEnv))continue;let w=await this.pickPort(y.defaultPort??3000);t.set(y.portEnv,w)}let f=bf.join(this.rpxDir,"sites",`${i.id}.log`);await F$.mkdir(bf.dirname(f),{recursive:!0}).catch(()=>{});let n=this.buildEnv(i,t),r=null,c;try{r=this.launch({command:i.command,cwd:i.dir,env:n,logPath:f})}catch(y){c=`failed to spawn: ${y.message}`}let l={site:i,status:c?"failed":"starting",handle:r,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:c?this.now():0,error:c,logPath:f,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,l),c)return F.warn(`rpx: site ${i.host} ${c}`),l;return F.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),r.exited.then((y)=>this.onProcessExit(l,y)).catch(()=>{}),l.ready=this.driveReadiness(l).catch((y)=>{Y("sites",`readiness loop for ${i.host} threw: ${y}`,this.verbose)}),l}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){F.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let f of i.routeIds)await this.removeEntry(f,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,f=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<f&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await n()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",F.success(`rpx: ${t.host} ready`);return}await Hl(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 f=i.routes.filter((r)=>r.readyGate??Ot(r.path)==="/").map((r)=>t.get(r.portEnv)).filter((r)=>typeof r==="number"),n=f.length>0?f:[...t.values()];return async()=>{for(let r of n)if(!await this.probePort(r))return!1;return n.length>0}}async publishRoutes(i){let{site:t,ports:f}=i;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((w)=>Ot(w.path)==="/")??t.routes[0],r=f.get(n.portEnv);if(r===void 0)return;let c=[];for(let w of t.routes){if(w===n)continue;let u=f.get(w.portEnv);if(u===void 0)continue;c.push({from:Ot(w.path),to:`localhost:${u}`,stripPrefix:w.stripPrefix??!1})}let l={id:t.id,from:`localhost:${r}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:c.length>0?c:void 0,pid:i.handle?.pid};await this.writeEntry(l,this.registryDir,this.verbose),i.routeIds=[t.id];let y=this.now()+2000;while(this.now()<y&&!this.isHostRoutable(t.host))await Hl(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),F.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let f={};for(let[n,r]of Object.entries(di.env))if(typeof r==="string")f[n]=r;Object.assign(f,i.env);for(let[n,r]of t)f[n]=String(r);return f.RPX_SITE_HOST=i.host,f.RPX_SITE_URL=`https://${i.host}`,f}readLogTail(i,t=40){try{return oC(i.logPath,"utf8").split(`
186
+ `).slice(-t).join(`
187
+ `).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let f of t.routeIds)await this.removeEntry(f,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),F.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let f=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof f.unref==="function")f.unref();await Promise.race([t.exited.catch(()=>{}),Hl(this.killGraceMs+500)]),clearTimeout(f)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,f]of this.sites){let n=f.site.idleTimeoutMs;if(n<=0)continue;let r=i-f.lastAccess;if((f.status==="ready"||i-f.startedAt>this.startupTimeoutMs)&&r>n)Y("sites",`reaping ${t} (idle ${Math.round(r/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 Hl(i){return new Promise((t)=>setTimeout(t,i))}async function yU(i){let t=new AbortController,f=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(f)}}function wU(i){let t=uU();return({command:f,cwd:n,env:r,logPath:c})=>{let l=pC(c,"a");try{let y=iU("sh",["-c",f],{cwd:n,env:r,detached:!0,stdio:["ignore",l,l],...t?{uid:t.uid,gid:t.gid}:{}}),w=y.pid;if(w===void 0)throw Error("spawn returned no pid");let u=new Promise((h)=>{y.once("exit",($)=>{h($)}),y.once("error",()=>{h(null)})}).finally(()=>{try{J$(l)}catch{}});return Y("sites",`spawned pid ${w}: sh -c ${f} (cwd ${n})`,i),{pid:w,exited:u,stop:(h="SIGTERM")=>{try{di.kill(-w,h)}catch{try{y.kill(h)}catch{}}}}}catch(y){try{J$(l)}catch{}throw y}}}function uU(){if(di.platform==="win32")return null;if(!(typeof di.getuid==="function"&&di.getuid()===0))return null;let t=Number.parseInt(di.env.SUDO_UID??"",10),f=Number.parseInt(di.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(f)||f<=0)return null;return{uid:t,gid:f}}function Bf(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var hU=`
188
+ :root { color-scheme: light dark }
189
+ * { box-sizing: border-box }
190
+ body {
191
+ margin: 0; min-height: 100vh; display: grid; place-items: center;
192
+ font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
193
+ background: #0b0c0f; color: #e7e9ee;
194
+ }
195
+ .card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
196
+ .row { display: flex; align-items: center; gap: .75rem; }
197
+ h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
198
+ p { margin: .5rem 0 0; color: #9aa1ad }
199
+ code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
200
+ pre {
201
+ margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
202
+ background: #16181d; border: 1px solid #23262d; border-radius: 8px;
203
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
204
+ white-space: pre-wrap; word-break: break-word;
205
+ }
206
+ .spinner {
207
+ width: 16px; height: 16px; border-radius: 50%;
208
+ border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
209
+ animation: spin .8s linear infinite;
210
+ }
211
+ .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
212
+ @keyframes spin { to { transform: rotate(360deg) } }
213
+ `;function K$(i,t,f){return`<!doctype html>
214
+ <html lang="en">
215
+ <head>
216
+ <meta charset="utf-8">
217
+ <meta name="viewport" content="width=device-width, initial-scale=1">
218
+ ${f>0?`<meta http-equiv="refresh" content="${f}">`:""}
219
+ <title>${Bf(i)}</title>
220
+ <style>${hU}</style>
221
+ </head>
222
+ <body><main class="card">${t}</main></body>
223
+ </html>`}function I$(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),f=i.logTail?`<pre>${Bf(i.logTail)}</pre>`:"",n=`
224
+ <div class="row"><div class="spinner"></div><h1>Starting ${Bf(i.host)}…</h1></div>
225
+ <p>rpx is booting this site's dev server on demand. This page reloads itself —
226
+ it'll switch to the app as soon as it's ready (usually a few seconds).</p>
227
+ <p>Booting for ${t}s.</p>
228
+ ${f}`;return new Response(K$(`Starting ${i.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function _$(i){let t=i.logTail?`<pre>${Bf(i.logTail)}</pre>`:"<p>No output was captured.</p>",f=`
229
+ <div class="row"><div class="dot"></div><h1>${Bf(i.host)} failed to start</h1></div>
230
+ <p>${Bf(i.error)}</p>
231
+ ${t}
232
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(K$(`${i.host} failed`,f,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as $U}from"node:child_process";import Zf from"node:fs";import AU from"node:os";import O$ from"node:path";import*as Gt from"node:process";import{promisify as TU}from"node:util";var Pf=TU($U);function z$(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var Zi=Gt.platform==="win32"?O$.join(Gt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Q$="# rpx",EU="# Added by rpx",vf=new Set(["127.0.0.1","::1"]),ql=!1;async function G$(i){if(Gt.platform==="win32")throw Error("Administrator privileges required on Windows");if(M$()){let{stdout:n}=await Pf(i);return n}let t=Ll(),f=i.replace(/'/g,"'\\''");try{if(t){let{stdout:n}=await Pf(`echo '${t}' | sudo -S sh -c '${f}' 2>/dev/null`);return ql=!0,n}if(ql)try{let{stdout:n}=await Pf(`sudo -n sh -c '${f}'`);return n}catch(n){Y("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:n}=await Pf(`sudo -n sh -c '${f}'`);return ql=!0,n}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(n){throw Error(`Failed to execute sudo command: ${n.message}`)}}function pf(i){let t=i.indexOf("#"),f=(t===-1?i:i.slice(0,t)).trim();if(!f)return null;let n=t===-1?"":i.slice(t+1).trim(),[r,...c]=f.split(/\s+/);if(!r||c.length===0)return null;let l=/^rpx(?::pid=(\d+))?$/.exec(n);return{address:r,names:c,comment:n,rpxPid:l?.[1]?Number.parseInt(l[1],10):null,rpxManaged:l!==null}}function a$(i,t){let f=pf(i);return f!==null&&vf.has(f.address)&&f.names.includes(t)}function YU(i,t){let f=new Set(t),n=new Set,r=i.split(`
233
+ `),c=[],l=0;while(l<r.length){let y=r[l];if(y.trim()===EU){let u=[],h=l+1;while(h<r.length){let A=r[h];if(A.trim()===""||A.trim().startsWith("#"))break;u.push(A),h++}let $=u.filter((A)=>{let T=pf(A),C=T!==null&&vf.has(T.address)&&T.names.some((E)=>f.has(E));if(C){for(let E of T.names)if(f.has(E))n.add(E)}return!C});if($.length>0||u.length===0)c.push(y,...$);l=h;continue}let w=pf(y);if(w?.rpxManaged&&vf.has(w.address)&&w.names.some((u)=>f.has(u))){for(let u of w.names)if(f.has(u))n.add(u);l++;continue}c.push(y),l++}while(c.length>0&&c[c.length-1].trim()==="")c.pop();return{content:`${c.join(`
234
+ `)}
235
+ `,removed:[...n]}}function BU(i,t){let f=[],n=new Set,r=[];for(let c of i.split(`
236
+ `)){let l=pf(c);if(l?.rpxManaged&&l.rpxPid!==null&&vf.has(l.address)&&!t(l.rpxPid)){f.push(...l.names),n.add(l.rpxPid);continue}r.push(c)}while(r.length>0&&r[r.length-1].trim()==="")r.pop();return{content:`${r.join(`
237
+ `)}
238
+ `,removed:f,stalePids:[...n]}}async function xl(i){try{return await Zf.promises.readFile(Zi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),G$(`cat "${Zi}"`)}}async function gl(i,t){let f=O$.join(AU.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Zf.promises.writeFile(f,i,"utf8"),await G$(`cat "${f}" | tee "${Zi}" > /dev/null`)}finally{await Zf.promises.unlink(f).catch((n)=>{Y("hosts",`Failed to remove temporary file: ${n}`,t)})}}async function bN(i,t){let f=i.filter((r)=>!z$(r)),n=i.filter((r)=>z$(r));if(n.length>0)Y("hosts",`Skipping /etc/hosts for loopback dev names: ${n.join(", ")}`,t);if(f.length===0)return;Y("hosts",`Adding hosts: ${f.join(", ")}`,t),Y("hosts",`Using hosts file at: ${Zi}`,t);try{let r;try{r=await xl(t)}catch(u){throw console.log(" Could not read hosts file — skipping hosts setup"),Y("hosts",`sudo read also failed: ${u}`,t),Error(`Cannot read hosts file: ${u}`)}let c=r.split(`
239
+ `),l=f.filter((u)=>!c.some((h)=>a$(h,u)));if(l.length===0){Y("hosts","All hosts already exist in hosts file",t);return}let y=Gt.pid,w=l.map((u)=>`
240
+ 127.0.0.1 ${u} ${Q$}:pid=${y}
241
+ ::1 ${u} ${Q$}:pid=${y}`).join(`
242
+ `);try{await gl(r+w,t),console.log(` Hosts updated: ${l.join(", ")}`)}catch(u){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),l.forEach((h)=>{console.log(` 127.0.0.1 ${h}`),console.log(` ::1 ${h}`)}),console.log(` Or run: sudo nano ${Zi}`)}}catch(r){Y("hosts",`Failed to manage hosts file: ${r.message}`,t)}}async function PN(i,t){Y("hosts",`Removing hosts: ${i.join(", ")}`,t);try{let f;try{f=await xl(t)}catch(c){throw Y("hosts",`sudo read also failed: ${c}`,t),Error(`Cannot read hosts file: ${c}`)}let{content:n,removed:r}=YU(f,i);if(r.length===0){Y("hosts","No matching rpx-managed hosts found to remove",t);return}try{await gl(n,t),Y("hosts",`Hosts removed successfully: ${r.join(", ")}`,t)}catch(c){Y("hosts","Could not clean up hosts file automatically",t)}}catch(f){Y("hosts",`Failed to clean up hosts file: ${f.message}`,t)}}async function ZN(i,t){Y("hosts",`Checking hosts: ${i}`,t);let f;try{f=await Zf.promises.readFile(Zi,"utf-8")}catch(r){Y("hosts",`Error reading hosts file: ${r}`,t);try{let c=Ll(),l;if(c)l=`echo '${c}' | sudo -S cat "${Zi}" 2>/dev/null`;else l=`sudo -n cat "${Zi}" 2>/dev/null || cat "${Zi}" 2>/dev/null || echo ""`;let{stdout:y}=await Pf(l);f=y}catch(c){return Y("hosts",`Cannot read hosts file, assuming entries don't exist: ${c}`,t),i.map(()=>!1)}}let n=f.split(`
243
+ `);return i.map((r)=>n.some((c)=>a$(c,r)))}async function vN(i=Ri){let t;try{t=await Zf.promises.readFile(Zi,"utf-8")}catch{return[]}let f=[];for(let n of t.split(`
244
+ `)){let r=pf(n);if(r?.rpxManaged&&r.rpxPid!==null&&vf.has(r.address)&&!i(r.rpxPid))f.push(...r.names)}return[...new Set(f)]}async function of(i={}){let t=i.isAlive??Ri,f;try{f=await xl(i.verbose)}catch(l){return Y("hosts",`stale hosts GC: cannot read hosts file: ${l}`,i.verbose),[]}let{content:n,removed:r,stalePids:c}=BU(f,t);if(r.length===0)return[];try{return await gl(n,i.verbose),Y("hosts",`stale hosts GC: removed ${r.join(", ")} (dead pid(s): ${c.join(", ")})`,i.verbose),[...new Set(r)]}catch(l){return Y("hosts",`stale hosts GC: write failed: ${l}`,i.verbose),[]}}var CU=5000;function Wi(){return vi.join(g$(),".stacks","rpx")}function pr(i=Wi()){return vi.join(i,"daemon.pid")}async function Uf(i=Wi()){try{let t=await Ei.readFile(pr(i),"utf8"),f=Number.parseInt(t.trim(),10);if(!Number.isFinite(f)||f<=0)return null;return f}catch(t){if(t.code==="ENOENT")return null;throw t}}async function UU(i=Wi()){let t=await Uf(i);return t!==null&&Ri(t)}async function k$(i=Wi()){await Ei.mkdir(i,{recursive:!0});let t=pr(i);while(!0){try{let n=await Ei.open(t,"wx");try{await n.write(`${m.pid}
245
+ `)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let f=await Uf(i);if(f!==null&&Ri(f))throw Error(`rpx daemon already running (pid=${f})`);await Ei.unlink(t).catch(()=>{})}}async function Cf(i=Wi()){await Ei.unlink(pr(i)).catch(()=>{})}var Zr=new Map;function vr(i){for(let[t,f]of Zr)if(!i.has(t))Cl(f),Zr.delete(t)}function jU(i,t){let f=qh(t??"localhost:1");if(i.upstreams.length!==f.length)return!1;return i.upstreams.every((n,r)=>n.url===f[r])}function V$(i){let t=i.cleanUrls??!1,f=Ot(i.path),n=Dh(i.auth);if(i.static)return{static:n$(i.static,t),cleanUrls:t,basePath:f,auth:n};let r=i.from??"localhost:1",c=Lh(r),l=new URL(c.startsWith("http")?c:`http://${c}`),y=Zr.get(i.id);if(y&&!jU(y,r))Cl(y),y=void 0;if(!y)y=xh(r,i.loadBalancer),kh(y),Zr.set(i.id,y);return{sourceHost:l.host,upstreamPool:y,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:f,auth:n}}function mU(i){return i.find((f)=>!/^api\./.test(f)&&!/^docs\./.test(f)&&!/^dashboard\./.test(f))??i[0]??"rpx.localhost"}async function Pr(i,t,f=[],n=!1){let r=await Yt(t,i.verbose),c=[...new Set([...r.map((h)=>h.to).filter(Boolean),...f])],l=mU(c),y=[...new Set([l,...c,"rpx.localhost"])],w=Gh(c,l,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let u=await Yl(w);if(u&&(n||!cl(Al,y)))Y("daemon",`regenerating shared cert for host(s): ${y.join(", ")}`,i.verbose),El(),u=null;if(!u)Y("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Hh({...w,forceRegenerate:!0}),u=await Yl(w);if(!u)throw Error("failed to bootstrap TLS for rpx daemon");return u}async function RU(i,t,f,n){let r=m.env.SUDO_PASSWORD,c=m.env.HOME??g$(),l=[m.execPath,...m.argv.slice(1)],y=[`HOME=${c}`,`PATH=${m.env.PATH??""}`];if(n)y.push("RPX_VERBOSE=1");for(let[C,E]of Object.entries(m.env))if(E!==void 0&&C!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(C))y.push(`${C}=${E}`);let w=r?["-S","-p","","env",...y,...l]:["-n","env",...y,...l];Y("daemon",`elevating daemon via sudo for privileged ports ${t}/${f}`,n);let u=x$("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,$=null;if(u.once("error",(C)=>{h=C}),u.once("exit",(C)=>{$=C??0}),r&&u.stdin)u.stdin.write(`${r}
246
+ `),u.stdin.end();u.unref();let A=pr(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let C=await Uf(i);if(C!==null&&Ri(C)){if(n)F.success(`rpx daemon elevated to root (pid=${C}, https on :${t})`);return{httpsPort:t,httpPort:f,pidPath:A,done:Promise.resolve(),stop:async()=>{try{m.kill(C,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if($!==null&&$!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${$}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((E)=>setTimeout(E,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var H$=!1;function kl(){if(H$)return;H$=!0,m.on("uncaughtException",(i)=>{F.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),m.on("unhandledRejection",(i)=>{F.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function s$(i,t,f){let n;try{n=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let r=(i.headers.get("host")??n.hostname).split(":")[0];if(n.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let c=t.challengeStore.handlePath(n.pathname);if(c!==void 0)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(f){let c=A$(f,n.pathname);if(c!=null)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(r))t.ensureCert(r).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${r}${n.pathname}${n.search}`}})}async function j8(i={}){kl();let t=i.verbose??!1,f=i.rpxDir??Wi(),n=i.registryDir??vi.join(f,"registry.d"),r=i.httpsPort??443,c=i.httpPort??80,l=i.hostname??"::",y=i.hostname==null,w=i.gcIntervalMs??CU;if(m.env.RPX_DAEMON_WORKER==="1")return NU({rpxDir:m.env.RPX_WORKER_RPXDIR??f,registryDir:m.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(m.env.RPX_WORKER_HTTPSPORT??"",10)||r,hostname:m.env.RPX_WORKER_HOSTNAME??l,verbose:m.env.RPX_WORKER_VERBOSE==="1"||t});let u=r>0&&r<1024||c>0&&c<1024,h=typeof m.getuid==="function"&&m.getuid()===0;if(m.platform!=="win32"&&u&&!h)return RU(f,r,c,t);let $=Math.max(1,i.workers??(Number.parseInt(m.env.RPX_WORKERS??"",10)||1));if($>1){if(i.onDemandSites?.enabled)F.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return SU(i,{rpxDir:f,registryDir:n,httpsPort:r,httpPort:c,hostname:l,verbose:t,gcIntervalMs:w,workers:$})}let A=await k$(f),T=new Map,C=(j,K)=>Sl(T,j,K);function E(j){T=Xl(j.map((Ni)=>({host:Ni.to,path:Ni.path,route:V$(Ni)}))),vr(new Set(j.map((Ni)=>Ni.id)));let K=Array.from(T.keys());Y("daemon",`routing table now covers ${K.length} host(s): ${K.join(", ")||"<empty>"}`,t)}await df(n,t).catch((j)=>{Y("daemon",`initial gc failed: ${j}`,t)}),await of({verbose:t}).catch((j)=>{Y("daemon",`stale hosts GC on start failed: ${j}`,t)});let B=await Yt(n,t);E(B),await mf({rpxDir:f,verbose:t}).catch((j)=>{Y("daemon",`DNS reconcile on start failed: ${j}`,t)}),await tn(B,{rpxDir:f,verbose:t,ownerPid:m.pid}).catch((j)=>{Y("daemon",`DNS setup on start failed: ${j}`,t)});let U=[];if(i.productionCerts){if(U=await Fl(i.productionCerts,t),t&&U.length>0)F.info(`SNI: serving ${U.length} real cert(s): ${U.map((j)=>j.serverName).join(", ")}`)}let R=new Set,N=null,J;if(i.onDemandSites?.enabled){if(N=new el({resolver:zl(i.onDemandSites),registryDir:n,rpxDir:f,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(j)=>Nl(T,j)!==void 0,onSiteActivating:(j)=>{cn(j)}}),J=async(j)=>{let K=await N.onRequest(j);switch(K.kind){case"ready":return{retry:!0};case"starting":return I$({host:K.host,sinceMs:K.sinceMs,logTail:K.logTail});case"failed":return _$({host:K.host,error:K.error,logTail:K.logTail});case"unknown":default:return}},t)F.info("rpx: on-demand sites enabled")}let I=ml(C,t,J),z=Rl(t),X=null;if(U.length===0)X=await Pr(i,n);let li=i.onDemandTls,yi=li?.enabled?new Vr({config:li,certsDir:li.certsDir??i.productionCerts?.certsDir??vi.join(f,"on-demand-certs"),initial:U,verbose:t,onCertAdded:(j)=>{if(Kl()==="restart")Y("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>m.kill(m.pid,"SIGTERM"),10).unref();else _(j)}}):null;function Rf(j){if(j.length>0)return Df(j.map((K)=>({serverName:K.serverName,cert:K.cert,key:K.key})));return Df({key:X.key,cert:X.cert,ca:X.ca,requestCert:!1,rejectUnauthorized:!1})}function Ct(j){try{return Bun.serve(j)}catch(K){let Ni=K instanceof Error?K.message:String(K),Xf=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(Ni);if(!y||j.hostname!=="::"||!Xf)throw K;return Y("daemon",`no IPv6 on this host (${Ni}); binding 0.0.0.0`,i.verbose),Bun.serve({...j,hostname:"0.0.0.0"})}}function Wf(j){return Ct({port:r,hostname:l,reusePort:L$(),tls:Rf(j),fetch(K,Ni){return I(K,Ni)},websocket:z,error(K){return Y("daemon",`https server error: ${K}`,t),new Response(`Server Error: ${K.message}`,{status:500})}})}let rn=(j)=>[...new Set(j.map((K)=>K.to).filter(Boolean))],at=(j)=>{if(!X)return U;return Oh([...rn(j),...R,"rpx.localhost"],X)},pi=Wf(yi?yi.sniEntries():U.length>0?U:at(B)),Kt=null,Ht=!1;async function _(j){if(bi)return;if(Kt=j,Ht)return;Ht=!0;try{while(!bi&&Kt){let K=Kt;Kt=null,Y("daemon",`rebuilding :443 with ${K.length} SNI cert(s)`,t),pi.stop(!1);let Ni,Xf=!1,iy=60,l1=500;for(let l0=0;!bi&&!Xf;l0++)try{pi=Wf(K),Xf=!0;break}catch(y1){if(Ni=y1,l0>=iy)break;await new Promise((w1)=>setTimeout(w1,Math.min(25*2**Math.min(l0,4),l1)))}if(!Xf)F.error(`rpx: CRITICAL — could not rebind :443 after ${iy} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Ni?.message}`)}}finally{Ht=!1}}let Ii=null;if(c>0)Ii=Ct({port:c,hostname:l,fetch(j){return s$(j,yi,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)F.success(`rpx daemon listening on https://${l}:${r}${Ii?` (http→https on :${c})`:""}`),F.info(`pid file: ${A}`),F.info(`registry: ${n}`);async function n0(j){if(bi||U.length>0||yi||!X)return;try{X=await Pr(i,n,[...R]),await _(at(j))}catch(K){Y("daemon",`TLS sync on registry change failed: ${K}`,t)}}async function cn(j){if(bi||U.length>0||yi||!X||!j)return;if(R.has(j))return;R.add(j);try{X=await Pr(i,n,[...R],!0);let K=await Yt(n,t);await _(at(K))}catch(K){Y("daemon",`dev cert refresh for ${j} failed: ${K}`,t)}}let ln=br((j)=>{E(j),n0(j),tn(j,{rpxDir:f,verbose:t,ownerPid:m.pid}).catch((K)=>{Y("daemon",`DNS sync on registry change failed: ${K}`,t)})},{dir:n,verbose:t}),et=setInterval(()=>{df(n,t).then((j)=>{if(j>0)Y("daemon",`gc reaped ${j} stale entries`,t)}).catch((j)=>{Y("daemon",`periodic gc failed: ${j}`,t)}),of({verbose:t}).then((j)=>{if(j.length>0)Y("daemon",`gc reaped stale hosts entries: ${j.join(", ")}`,t)}).catch((j)=>{Y("daemon",`periodic hosts gc failed: ${j}`,t)})},w);if(typeof et.unref==="function")et.unref();let bi=!1,r0,c0=new Promise((j)=>{r0=j});async function pl(){if(bi)return c0;if(bi=!0,clearInterval(et),ln.close(),await N?.stopAll().catch((j)=>{Y("daemon",`site supervisor stopAll failed: ${j}`,t)}),pi.stop(!1),Ii?.stop(!1),await jf({rpxDir:f,verbose:t}).catch((j)=>{Y("daemon",`DNS teardown failed: ${j}`,t)}),vr(new Set),await Cf(f),t)F.info("rpx daemon stopped");return r0(),c0}let ol=(j)=>{Y("daemon",`received ${j}, shutting down`,t),pl().catch(()=>{})};return m.once("SIGINT",ol),m.once("SIGTERM",ol),{stop:pl,done:c0,httpsPort:typeof pi.port==="number"?pi.port:r,httpPort:Ii&&typeof Ii.port==="number"?Ii.port:c,pidPath:A,ensureCert:(j)=>yi?yi.ensureCert(j):Promise.resolve(!1),listSites:()=>N?.list()??[]}}function Vl(i){return vi.join(i,"cluster-sni.json")}async function e$(i,t,f){let n=Vl(i),r=`${n}.${m.pid}.tmp`;await Ei.writeFile(r,JSON.stringify({sni:t,dev:f}),"utf8"),await Ei.rename(r,n)}async function q$(i){try{return JSON.parse(await Ei.readFile(Vl(i),"utf8"))}catch{return{sni:[],dev:null}}}function WU(i){if(i.sni.length>0)return Df(i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(i.dev)return Df({key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function XU(){let i=m.execPath,t=m.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let f=vi.basename(i).toLowerCase();if((f==="bun"||f==="node"||f.startsWith("bun-"))&&m.argv[1])return[i,m.argv[1],"daemon:start"];return[i,"daemon:start"]}async function NU(i){kl();let{rpxDir:t,registryDir:f,httpsPort:n,hostname:r,verbose:c}=i,l=new Map,y=(z,X)=>Sl(l,z,X),w=(z)=>{l=Xl(z.map((X)=>({host:X.to,path:X.path,route:V$(X)}))),vr(new Set(z.map((X)=>X.id)))};w(await Yt(f,c));let u=ml(y,c),h=Rl(c),$=!1,A=(z)=>Bun.serve({port:n,hostname:r,reusePort:!0,tls:WU(z),fetch(X,li){return u(X,li)},websocket:h,error(X){return Y("daemon",`worker https error: ${X}`,c),new Response(`Server Error: ${X.message}`,{status:500})}}),T=A(await q$(t));async function C(){if($)return;let z=await q$(t),X=null;for(let yi=0;yi<20&&!$;yi++)try{X=A(z);break}catch{await new Promise((Rf)=>setTimeout(Rf,25))}if(!X){Y("daemon","worker reloadTls: could not bind new listener; keeping current",c);return}let li=T;T=X,li.stop(!1)}let E=br((z)=>w(z),{dir:f,verbose:c}),B=()=>{C().catch(()=>{})};m.on("SIGHUP",B);let U=()=>{let z=m.removeListener??m.off;if(typeof z==="function")z.call(m,"SIGHUP",B)},R,N=new Promise((z)=>{R=z});async function J(){if($)return N;return $=!0,U(),E.close(),T.stop(!1),vr(new Set),R(),N}let I=()=>{J().then(()=>m.exit(0)).catch(()=>m.exit(0))};if(m.once("SIGTERM",I),m.once("SIGINT",I),c)F.success(`rpx worker (pid ${m.pid}) serving :${n}`);return{stop:J,done:N,httpsPort:typeof T.port==="number"?T.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function SU(i,t){kl();let{rpxDir:f,registryDir:n,httpsPort:r,httpPort:c,hostname:l,verbose:y,gcIntervalMs:w,workers:u}=t,h=await k$(f),$=[];if(i.productionCerts)$=await Fl(i.productionCerts,y);let A=null;if($.length===0)A=await Pr(i,n);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
247
+ `):A.ca}:null,C=!1,E=[];function B(_){for(let Ii of E)try{Ii.kill(_)}catch{}}async function U(_){await e$(f,_,T),B("SIGHUP")}let R=i.onDemandTls,N=R?.enabled?new Vr({config:R,certsDir:R.certsDir??i.productionCerts?.certsDir??vi.join(f,"on-demand-certs"),initial:$,verbose:y,onCertAdded:(_)=>{if(Kl()==="restart")Y("on-demand","certificate installed; restarting supervised gateway to reload TLS",y),setTimeout(()=>m.kill(m.pid,"SIGTERM"),10).unref();else U(_)}}):null;await e$(f,N?N.sniEntries():$,T);let J=await Yt(n,y);await mf({rpxDir:f,verbose:y}).catch((_)=>{Y("daemon",`DNS reconcile on start failed: ${_}`,y)}),await tn(J,{rpxDir:f,verbose:y,ownerPid:m.pid}).catch((_)=>{Y("daemon",`DNS setup on start failed: ${_}`,y)}),await df(n,y).catch(()=>{}),await of({verbose:y}).catch(()=>{});let I=br((_)=>{tn(_,{rpxDir:f,verbose:y,ownerPid:m.pid}).catch((Ii)=>{Y("daemon",`DNS sync on registry change failed: ${Ii}`,y)})},{dir:n,verbose:y}),z=setInterval(()=>{df(n,y).catch(()=>{}),of({verbose:y}).catch(()=>{})},w);z.unref?.();let X=null;if(c>0)X=Bun.serve({port:c,hostname:l,fetch(_){return s$(_,N,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let li=10,yi=60000,Rf=30000,Ct=0,Wf=Date.now();function rn(){if(C)return;let _={...m.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:f,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(r),RPX_WORKER_HOSTNAME:l,RPX_WORKER_VERBOSE:y?"1":"0"},Ii=Bun.spawn(XU(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n0,cn){if(C)return;let ln=E.indexOf(n0);if(ln!==-1)E.splice(ln,1);let et=Date.now();if(et-Wf>yi)Wf=et,Ct=0;if(Ct++,Ct>li){F.error(`rpx: worker keeps exiting (code ${cn}); giving up after ${li} restarts in ${Math.round(yi/1000)}s`);return}let bi=Math.min(Rf,100*2**Math.min(Ct,8));Y("daemon",`worker exited (code ${cn}); respawning in ${bi}ms (restart ${Ct}/${li})`,y),setTimeout(rn,bi).unref?.()}});E.push(Ii)}for(let _=0;_<u;_++)rn();if(y)F.success(`rpx coordinator listening on https://${l}:${r} via ${u} worker(s)${X?` (http→https on :${c})`:""}`),F.info(`pid file: ${h}`);let at,pi=new Promise((_)=>{at=_});async function Kt(){if(C)return pi;if(C=!0,clearInterval(z),I.close(),X?.stop(!1),B("SIGTERM"),await Promise.race([Promise.all(E.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),B("SIGKILL"),await jf({rpxDir:f,verbose:y}).catch((_)=>{Y("daemon",`DNS teardown failed: ${_}`,y)}),await Cf(f),await Ei.unlink(Vl(f)).catch(()=>{}),y)F.info("rpx coordinator stopped");return at(),pi}let Ht=(_)=>{Y("daemon",`coordinator received ${_}, shutting down`,y),Kt().catch(()=>{})};return m.once("SIGINT",Ht),m.once("SIGTERM",Ht),{stop:Kt,done:pi,httpsPort:r,httpPort:c,pidPath:h,ensureCert:(_)=>N?N.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function JU(){let i=m.execPath,t=vi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&m.argv[1])return[i,m.argv[1],"daemon:start"];return[i,"daemon:start"]}async function m8(i={}){let t=i.rpxDir??Wi(),f=i.verbose??!1;await mf({rpxDir:t,verbose:f}).catch((h)=>{Y("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,f)});let n=await Uf(t);if(n!==null&&Ri(n))return Y("daemon",`ensureDaemonRunning: already running pid=${n}`,f),{pid:n,spawned:!1};if(n!==null)Y("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,f),await Cf(t);await Ei.mkdir(t,{recursive:!0});let r=i.spawnCommand??JU();if(r.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");Y("daemon",`spawning daemon: ${r.join(" ")}`,f);let c=x$(r[0],r.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??m.cwd(),env:i.spawnEnv?{...m.env,...i.spawnEnv}:m.env});c.unref();let l=null;c.once("error",(h)=>{l=h});let y=i.startupTimeoutMs??5000,w=i.pollIntervalMs??50,u=Date.now()+y;while(Date.now()<u){if(l)throw l;let h=await Uf(t);if(h!==null&&Ri(h))return Y("daemon",`daemon registered with pid=${h}`,f),{pid:h,spawned:!0};await new Promise(($)=>setTimeout($,w))}if(l)throw l;throw Error(`rpx daemon failed to start within ${y}ms (rpxDir=${t})`)}async function R8(i={}){let t=i.rpxDir??Wi(),f=i.verbose??!1,n=i.timeoutMs??5000,r=i.pollIntervalMs??50,c=i.forceAfterTimeout??!0,l=await Uf(t);if(l===null||!Ri(l)){if(l!==null)await Cf(t);return await mf({rpxDir:t,verbose:f}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{m.kill(l,"SIGTERM")}catch(w){let u=w.code;if(u==="ESRCH")return await Cf(t),{stopped:!1,pid:l,forced:!1};if(u==="EPERM")Nt(`kill -TERM ${l}`);else throw w}let y=Date.now()+n;while(Date.now()<y){if(!Ri(l))return Y("daemon",`daemon pid=${l} stopped cleanly`,f),{stopped:!0,pid:l,forced:!1};await new Promise((w)=>setTimeout(w,r))}if(!c)throw Error(`rpx daemon (pid=${l}) did not exit within ${n}ms`);Y("daemon",`daemon pid=${l} did not exit, escalating to SIGKILL`,f);try{m.kill(l,"SIGKILL")}catch(w){let u=w.code;if(u==="EPERM")Nt(`kill -KILL ${l}`);else if(u!=="ESRCH")throw w}return await Cf(t),await jf({rpxDir:t,verbose:f}).catch((w)=>{Y("daemon",`DNS teardown after SIGKILL: ${w}`,f)}),{stopped:!0,pid:l,forced:!0}}async function W8(i={}){let t=i.rpxDir??Wi();if(await UU(t))return;await mf({rpxDir:t,verbose:i.verbose})}import*as Ft from"node:fs/promises";import{homedir as FU}from"node:os";import*as sl from"node:path";var or=1,KU="dns-state.json",D$=["com","test","dev","app","page","local","localhost","example","invalid"];function d$(){return sl.join(FU(),".stacks","rpx")}function Dl(i=d$()){return sl.join(i,KU)}async function i0(i=d$()){try{let t=await Ft.readFile(Dl(i),"utf8"),f=JSON.parse(t);if(f.version!==or||!Array.isArray(f.resolvers))return null;return{version:or,resolvers:f.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(f.domains)?f.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof f.ownerPid==="number"?f.ownerPid:null,updatedAt:typeof f.updatedAt==="string"?f.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function b$(i,t){await Ft.mkdir(i,{recursive:!0}),await Ft.writeFile(Dl(i),`${JSON.stringify(t,null,2)}
248
+ `,"utf8")}async function dl(i){await Ft.rm(Dl(i),{force:!0})}function P$(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}var IU=new Set(["test","localhost","local","example","invalid","internal","home","lan"]);function _U(i){let t=P$(i);if(!t)return null;let f=t.split(".");if(f.length<2)return null;let n=f[f.length-1];if(IU.has(n))return f.slice(-2).join(".");return t}function bl(i){let t=new Set;for(let f of i){let n=_U(f);if(n)t.add(n)}return Array.from(t).sort()}function Pl(i){let t=new Set;for(let f of i){let n=P$(f);if(n)t.add(n)}return Array.from(t).sort()}var f0=15353,zU="# managed-by: rpx",o$="/etc/resolver",Xi=null,t0=new Set;function i1(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 t1(i,t,f=0){let n=[],r=t,c=0;while(!0){if(r>=i.length||++c>128)break;let l=i[r];if(l===0){r++;break}if((l&192)===192){if(r+1>=i.length||f>=10)break;let y=i.readUInt16BE(r)&16383,{name:w}=t1(i,y,f+1);if(w)n.push(w);r+=2;break}if(r++,r+l>i.length)break;n.push(i.subarray(r,r+l).toString("ascii")),r+=l}return{name:n.join("."),newOffset:r}}function QU(i,t){let{name:f,newOffset:n}=t1(i,t),r=i.readUInt16BE(n),c=i.readUInt16BE(n+2);return{question:{name:f,type:r,class:c},newOffset:n+4}}function fn(i){let t=i.split("."),f=[];for(let n of t)f.push(Buffer.from([n.length])),f.push(Buffer.from(n,"ascii"));return f.push(Buffer.from([0])),Buffer.concat(f)}function MU(i,t,f){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(i,0),r.writeUInt16BE(33152,2),r.writeUInt16BE(1,4),r.writeUInt16BE(1,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(fn(t.name));let c=Buffer.alloc(4);c.writeUInt16BE(t.type,0),c.writeUInt16BE(t.class,2),n.push(c),n.push(fn(t.name));let l=Buffer.alloc(10);if(l.writeUInt16BE(t.type,0),l.writeUInt16BE(1,2),l.writeUInt32BE(300,4),t.type===1){l.writeUInt16BE(4,8),n.push(l);let y=f.split(".").map((w)=>Number.parseInt(w,10));n.push(Buffer.from(y))}else if(t.type===28)l.writeUInt16BE(16,8),n.push(l),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return r.writeUInt16BE(33155,2),r.writeUInt16BE(0,6),Buffer.concat([r,fn(t.name),c]);return Buffer.concat(n)}function OU(i,t){let f=[],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),f.push(n),f.push(fn(t.name));let r=Buffer.alloc(4);return r.writeUInt16BE(t.type,0),r.writeUInt16BE(t.class,2),f.push(r),Buffer.concat(f)}async function GU(i,t){if(Bt.platform!=="darwin")return!1;let f=Pl(i);if(f.length===0)return!1;if(Xi){for(let n of f)t0.add(n);return Y("dns","DNS server already running — merged domains",t),!0}return t0=new Set(f),new Promise((n)=>{Xi=Z$.createSocket("udp4"),Xi.on("error",(r)=>{Y("dns",`DNS server error: ${r.message}`,t),Xi?.close(),Xi=null,n(!1)}),Xi.on("message",(r,c)=>{try{let l=i1(r),{question:y}=QU(r,12);Y("dns",`Query for ${y.name} type ${y.type} from ${c.address}`,t);let w=y.name.toLowerCase(),u=!1;for(let $ of t0)if(w===$||w.endsWith(`.${$}`)){u=!0;break}let h;if(u&&(y.type===1||y.type===28))h=MU(l.id,y,"127.0.0.1"),Y("dns",`Responding with localhost for ${y.name}`,t);else h=OU(l.id,y),Y("dns",`NXDOMAIN for ${y.name}`,t);Xi?.send(h,c.port,c.address)}catch(l){Y("dns",`Error processing DNS query: ${l}`,t)}}),Xi.on("listening",()=>{let r=Xi?.address();Y("dns",`DNS server listening on ${r?.address}:${r?.port}`,t),n(!0)});try{Xi.bind(f0,"127.0.0.1")}catch(r){Y("dns",`Failed to bind DNS server: ${r}`,t),n(!1)}})}function f1(i){if(Xi)Y("dns","Stopping DNS server",i),Xi.close(),Xi=null,t0=new Set}function z8(){return Xi!==null}async function aU(i,t=500){let f=i.trim().toLowerCase().replace(/\.$/,"");if(!f)return!1;return new Promise((n)=>{let r=Z$.createSocket("udp4"),c=setTimeout(()=>{r.close(),n(!1)},t);r.on("message",(y)=>{clearTimeout(c),r.close();try{let w=i1(y);n(w.ancount>0)}catch{n(!1)}}),r.on("error",()=>{clearTimeout(c),r.close(),n(!1)});let l=HU(f,1);r.send(l,f0,"127.0.0.1",(y)=>{if(y)clearTimeout(c),r.close(),n(!1)})})}function HU(i,t){let f=Buffer.alloc(12);f.writeUInt16BE(1,0),f.writeUInt16BE(256,2),f.writeUInt16BE(1,4);let n=Buffer.concat([fn(i),Buffer.from([0,t,0,1])]);return Buffer.concat([f,n])}function eU(){return`${zU}
249
+ nameserver 127.0.0.1
250
+ port ${f0}
251
+ `}function nn(i){return p$.join(o$,i)}function qU(i){return i.includes("127.0.0.1")&&i.includes(String(f0))}async function LU(i){try{return await v$.readFile(nn(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Zl(i){if(Bt.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:f,isProcessElevated:n}=await import("./chunk-bvq3wmhm.js");if(!n()&&!f()){Y("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),Y("dns","DNS cache flushed",i)}catch(r){Y("dns",`Could not flush DNS cache: ${r}`,i)}}function n1(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function xU(i,t){n1(i);let{execSudoSync:f}=await import("./chunk-bvq3wmhm.js"),n=eU().replace(/\n/g,"\\n"),r=`bash -c 'mkdir -p ${o$} && printf "%b" "${n}" > ${nn(i)}'`;f(r),Y("dns",`Created ${nn(i)}`,t)}async function gU(i,t){n1(i);let{execSudoSync:f}=await import("./chunk-bvq3wmhm.js");f(`rm -f ${nn(i)}`),Y("dns",`Removed ${nn(i)}`,t)}async function Q8(i,t){return c1({domains:t??[],verbose:i})}async function kU(i,t){if(Bt.platform!=="darwin")return!0;let{getSudoPassword:f,isProcessElevated:n}=await import("./chunk-bvq3wmhm.js");if(!n()&&!f())return Y("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let r of i)await xU(r,t);return await Zl(t),!0}catch(r){return Y("dns",`Failed to create resolver file: ${r}`,t),!1}}async function vl(i,t){if(Bt.platform!=="darwin")return;let{getSudoPassword:f,isProcessElevated:n}=await import("./chunk-bvq3wmhm.js");if(!n()&&!f())return;try{for(let r of i)await gU(r,t);await Zl(t)}catch(r){Y("dns",`Failed to remove resolver files: ${r}`,t)}}async function r1(i){if(Bt.platform!=="darwin")return[];let t=[];for(let f of D$){let n=await LU(f);if(n&&qU(n))await vl([f],i),t.push(f)}return t}async function c1(i){let t=i.rpxDir??Wi(),f=Pl(i.domains);if(f.length===0)return!1;let n=bl(f),r=await GU(f,i.verbose);if(!r){let y=f[0];if(y&&await aU(y))r=!0;else Y("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!r)return!1;if(!await kU(n,i.verbose))return!1;let l={version:or,resolvers:n,domains:f,ownerPid:i.ownerPid??Bt.pid,updatedAt:new Date().toISOString()};return await b$(t,l),!0}async function tn(i,t={}){let f=i.map((w)=>w.to).filter(Boolean),n=t.rpxDir??Wi(),r=bl(f),y=((await i0(n))?.resolvers??[]).filter((w)=>!r.includes(w));if(y.length>0)await vl(y,t.verbose);if(r.length===0){f1(t.verbose),await dl(n);return}await c1({domains:f,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??Bt.pid})}async function jf(i={}){let t=i.rpxDir??Wi();f1(i.verbose);let n=(await i0(t))?.resolvers??[];await vl(n,i.verbose),await r1(i.verbose),await dl(t)}async function M8(i){await jf({verbose:i})}async function mf(i={}){let t=i.rpxDir??Wi(),f=await i0(t),n=f?.ownerPid!=null&&Ri(f.ownerPid);if(f&&!n){Y("dns",`reconcile: owner pid ${f.ownerPid} is gone — tearing down DNS`,i.verbose),await jf(i);return}let r=await r1(i.verbose);if(r.length>0)Y("dns",`reconcile: removed legacy TLD resolvers: ${r.join(", ")}`,i.verbose);await Zl(i.verbose)}
252
+ export{F as a,Jh as b,NB as c,Qt as d,rl as e,cl as f,SB as g,JB as h,Pi as i,Et as j,ll as k,qf as l,yl as m,Fh as n,Hr as o,Lf as p,xf as q,wl as r,Al as s,Oh as t,Gh as u,Tl as v,gX as w,kX as x,VX as y,Hh as z,El as A,Yl as B,Bl as C,sX as D,eh as E,Lh as F,xh as G,gh as H,qr as I,gf as J,kh as K,Cl as L,sB as M,Dh as N,dh as O,iN as P,f$ as Q,n$ as R,UC as S,jC as T,mC as U,r$ as V,w$ as W,ml as X,Rl as Y,u$ as Z,A$ as _,gr as $,Wl as aa,T$ as ba,Ot as ca,_C as da,Xl as ea,Nl as fa,Sl as ga,Df as ha,zC as ia,Fl as ja,Kl as ka,GC as la,Y$ as ma,Vr as na,_l as oa,B$ as pa,kC as qa,VC as ra,DC as sa,zl as ta,XN as ua,W$ as va,Ql as wa,X$ as xa,JN as ya,Jt as za,Ol as Aa,Ri as Ba,S$ as Ca,al as Da,vC as Ea,Yt as Fa,df as Ga,br as Ha,el as Ia,Bf as Ja,I$ as Ka,_$ as La,Q$ as Ma,pf as Na,a$ as Oa,YU as Pa,BU as Qa,bN as Ra,PN as Sa,ZN as Ta,vN as Ua,of as Va,or as Wa,D$ as Xa,P$ as Ya,_U as Za,bl as _a,Pl as $a,f0 as ab,zU as bb,GU as cb,f1 as db,z8 as eb,aU as fb,nn as gb,qU as hb,Q8 as ib,r1 as jb,c1 as kb,tn as lb,jf as mb,M8 as nb,mf as ob,Wi as pb,pr as qb,Uf as rb,UU as sb,k$ as tb,Cf as ub,j8 as vb,JU as wb,m8 as xb,R8 as yb,W8 as zb};