@stacksjs/rpx 0.11.30 → 0.11.33

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.
@@ -1,25 +1,25 @@
1
- import{Ab as F$,Bb as Nt,Cb as Y,Db as O$,Hb as Sh,Ib as wl,Kb as Of,Lb as ah,Nb as r$,Ob as Jh,yb as s,zb as Gl}from"./chunk-z86swbd8.js";import d$ from"node:dgram";import*as D$ from"node:fs/promises";import*as b$ from"node:path";import*as Et from"node:process";import{spawn as G$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as H$}from"node:os";import*as Pi from"node:path";import*as j from"node:process";var J={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as ll}from"node:child_process";import Z from"node:fs/promises";import*as yl from"node:os";import{homedir as en}from"node:os";import*as Fh from"node:path";import{join as D}from"node:path";import*as Li from"node:process";import{createRequire as c1}from"node:module";import{Resolver as f0}from"node:dns/promises";import{createHash as y1,sign as w1}from"node:crypto";import{createHash as u1}from"node:crypto";import{sign as h1}from"node:crypto";import{generateKeyPairSync as nw,X509Certificate as m1}from"node:crypto";import c0 from"node:os";import l0 from"node:path";import{existsSync as ol,statSync as pl}from"fs";import{existsSync as j1,mkdirSync as kC,readdirSync as VC,readFileSync as N1,writeFileSync as dC}from"fs";import{homedir as Lt}from"os";import{dirname as PC,resolve as Ji}from"path";import kr from"process";import{existsSync as iy,statSync as ty}from"fs";import{existsSync as I0,mkdirSync as R1,readdirSync as X1,writeFileSync as W1}from"fs";import{homedir as xt}from"os";import{dirname as ny,resolve as Yi}from"path";import _t from"process";import{join as S1,relative as a1,resolve as ry}from"path";import ar from"process";import{existsSync as rw,mkdirSync as cm,readdirSync as lm,writeFileSync as ym}from"fs";import{homedir as y0}from"os";import{dirname as hm,resolve as Ei}from"path";import Fn from"process";import{join as J1,relative as F1,resolve as fy}from"path";import Jr from"process";import{existsSync as fw,mkdirSync as Ym,readdirSync as Bm,writeFileSync as em}from"fs";import{dirname as mm,resolve as Fr}from"path";import K0 from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as I1,createDecipheriv as K1,randomBytes as w0}from"crypto";import{closeSync as u0,createReadStream as cy,createWriteStream as _1,existsSync as h0,fsyncSync as ly,openSync as yy,writeFileSync as z1}from"fs";import{access as Q1,constants as wy,mkdir as M1,readdir as fr,rename as uy,stat as kt,unlink as cr,writeFile as $0}from"fs/promises";import{join as Vt}from"path";import yi from"process";import{pipeline as O1}from"stream/promises";import{createGzip as hy}from"zlib";import dt from"process";import it from"process";import{Buffer as vi}from"buffer";import{createCipheriv as G1,createDecipheriv as H1,randomBytes as A0}from"crypto";import{closeSync as T0,createReadStream as $y,createWriteStream as q1,existsSync as lr,fsyncSync as Ay,openSync as Ty,writeFileSync as g1}from"fs";import{access as s1,constants as Ey,mkdir as L1,readdir as yr,rename as Yy,stat as Dt,unlink as wr,writeFile as E0}from"fs/promises";import{isAbsolute as x1,join as bt,resolve as k1}from"path";import H from"process";import{pipeline as V1}from"stream/promises";import{createGzip as By}from"zlib";import Pt from"process";import tt from"process";import ur from"process";import{existsSync as hr}from"fs";import{resolve as Y0}from"path";import{existsSync as d1}from"fs";import{existsSync as D1,readdirSync as b1}from"fs";import{extname as B0,resolve as ey}from"path";import P1 from"process";import{join as Z1,relative as v1,resolve as Cy}from"path";import Ir from"process";import{Buffer as oi}from"buffer";import{createCipheriv as o1,createDecipheriv as p1,randomBytes as e0}from"crypto";import{closeSync as C0,createReadStream as my,createWriteStream as iA,existsSync as $r,fsyncSync as Uy,openSync as jy,writeFileSync as tA}from"fs";import{access as nA,constants as Ny,mkdir as rA,readdir as Ar,rename as Ry,stat as Zt,unlink as Tr,writeFile as m0}from"fs/promises";import{isAbsolute as fA,join as vt,resolve as cA}from"path";import q from"process";import{pipeline as lA}from"stream/promises";import{createGzip as Xy}from"zlib";import ot from"process";import nt from"process";import Er from"process";import{existsSync as Yr}from"fs";import{resolve as U0}from"path";import{existsSync as yA}from"fs";import{exec as FT}from"node:child_process";import L0 from"node:fs";import IT from"node:os";import Mi from"node:path";import gw from"node:process";import{promisify as KT}from"node:util";import rn from"node:crypto";import rt from"node:fs";import V0 from"node:path";import iE from"node:crypto";import tE from"node:fs";import nE from"node:tls";import{execSync as cE}from"node:child_process";import Lr from"node:os";var l1=c1(import.meta.url),Ly=30000;async function Cr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function xy(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new f0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new f0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new f0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Jn{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(Jn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Jn.PATH_PREFIX.length);return this.get(n)}}var xr=new Jn;function mr(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function S0(i){return Buffer.from(i,"base64url")}function ky(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 Vy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return y1("sha256").update(t).digest("base64url")}function dy(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=mr(JSON.stringify(t)),c=n===""?"":mr(JSON.stringify(n)),l=`${f}.${c}`,y=w1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:mr(y)}}var Dy="https://acme-staging-v02.api.letsencrypt.org/directory",by="https://acme-v02.api.letsencrypt.org/directory";class Wr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class Sr{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=ky(i.accountPublicKey),this.thumbprint=Vy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??Ly}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await Cr(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 Cr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=dy({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await Cr(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 Wr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return u1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Wr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await vl(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await vl(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Py(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
1
+ import{Ab as Hl,Bb as I$,Db as Nt,Eb as Y,Fb as G$,Jb as ah,Kb as ul,Mb as Gf,Nb as Jh,Pb as f$,Qb as Fh,zb as L}from"./chunk-35444zrq.js";import D$ from"node:dgram";import*as b$ from"node:fs/promises";import*as P$ from"node:path";import*as Et from"node:process";import{spawn as H$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as q$}from"node:os";import*as Pi from"node:path";import*as j from"node:process";var J={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as yl}from"node:child_process";import Z from"node:fs/promises";import*as wl from"node:os";import{homedir as en}from"node:os";import*as Ih from"node:path";import{join as D}from"node:path";import*as si from"node:process";import{createRequire as l1}from"node:module";import{Resolver as c0}from"node:dns/promises";import{createHash as w1,sign as u1}from"node:crypto";import{createHash as h1}from"node:crypto";import{sign as $1}from"node:crypto";import{generateKeyPairSync as rw,X509Certificate as U1}from"node:crypto";import l0 from"node:os";import y0 from"node:path";import{existsSync as pl,statSync as iy}from"fs";import{existsSync as N1,mkdirSync as VC,readdirSync as dC,readFileSync as R1,writeFileSync as DC}from"fs";import{homedir as st}from"os";import{dirname as ZC,resolve as Ji}from"path";import Vr from"process";import{existsSync as ty,statSync as ny}from"fs";import{existsSync as K0,mkdirSync as X1,readdirSync as W1,writeFileSync as S1}from"fs";import{homedir as xt}from"os";import{dirname as ry,resolve as Yi}from"path";import _t from"process";import{join as a1,relative as J1,resolve as fy}from"path";import Jr from"process";import{existsSync as fw,mkdirSync as lm,readdirSync as ym,writeFileSync as wm}from"fs";import{homedir as w0}from"os";import{dirname as $m,resolve as Ei}from"path";import Fn from"process";import{join as F1,relative as I1,resolve as cy}from"path";import Fr from"process";import{existsSync as cw,mkdirSync as Bm,readdirSync as em,writeFileSync as Cm}from"fs";import{dirname as Um,resolve as Ir}from"path";import _0 from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as K1,createDecipheriv as _1,randomBytes as u0}from"crypto";import{closeSync as h0,createReadStream as ly,createWriteStream as z1,existsSync as $0,fsyncSync as yy,openSync as wy,writeFileSync as Q1}from"fs";import{access as M1,constants as uy,mkdir as O1,readdir as cr,rename as hy,stat as kt,unlink as lr,writeFile as A0}from"fs/promises";import{join as Vt}from"path";import yi from"process";import{pipeline as G1}from"stream/promises";import{createGzip as $y}from"zlib";import dt from"process";import it from"process";import{Buffer as vi}from"buffer";import{createCipheriv as H1,createDecipheriv as q1,randomBytes as T0}from"crypto";import{closeSync as E0,createReadStream as Ay,createWriteStream as g1,existsSync as yr,fsyncSync as Ty,openSync as Ey,writeFileSync as L1}from"fs";import{access as s1,constants as Yy,mkdir as x1,readdir as wr,rename as By,stat as Dt,unlink as ur,writeFile as Y0}from"fs/promises";import{isAbsolute as k1,join as bt,resolve as V1}from"path";import H from"process";import{pipeline as d1}from"stream/promises";import{createGzip as ey}from"zlib";import Pt from"process";import tt from"process";import hr from"process";import{existsSync as $r}from"fs";import{resolve as B0}from"path";import{existsSync as D1}from"fs";import{existsSync as b1,readdirSync as P1}from"fs";import{extname as e0,resolve as Cy}from"path";import Z1 from"process";import{join as v1,relative as o1,resolve as my}from"path";import Kr from"process";import{Buffer as oi}from"buffer";import{createCipheriv as p1,createDecipheriv as iA,randomBytes as C0}from"crypto";import{closeSync as m0,createReadStream as Uy,createWriteStream as tA,existsSync as Ar,fsyncSync as jy,openSync as Ny,writeFileSync as nA}from"fs";import{access as rA,constants as Ry,mkdir as fA,readdir as Tr,rename as Xy,stat as Zt,unlink as Er,writeFile as U0}from"fs/promises";import{isAbsolute as cA,join as vt,resolve as lA}from"path";import q from"process";import{pipeline as yA}from"stream/promises";import{createGzip as Wy}from"zlib";import ot from"process";import nt from"process";import Yr from"process";import{existsSync as Br}from"fs";import{resolve as j0}from"path";import{existsSync as wA}from"fs";import{exec as IT}from"node:child_process";import x0 from"node:fs";import KT from"node:os";import Mi from"node:path";import Lw from"node:process";import{promisify as _T}from"node:util";import rn from"node:crypto";import rt from"node:fs";import d0 from"node:path";import tE from"node:crypto";import nE from"node:fs";import rE from"node:tls";import{execSync as lE}from"node:child_process";import xr from"node:os";var y1=l1(import.meta.url),xy=30000;async function mr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function ky(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new c0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new c0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new c0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Jn{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(Jn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Jn.PATH_PREFIX.length);return this.get(n)}}var kr=new Jn;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function a0(i){return Buffer.from(i,"base64url")}function Vy(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function dy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return w1("sha256").update(t).digest("base64url")}function Dy(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),c=n===""?"":Ur(JSON.stringify(n)),l=`${f}.${c}`,y=u1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Ur(y)}}var by="https://acme-staging-v02.api.letsencrypt.org/directory",Py="https://acme-v02.api.letsencrypt.org/directory";class Sr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class ar{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=Vy(i.accountPublicKey),this.thumbprint=dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??xy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await mr(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await mr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=Dy({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await mr(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Sr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return h1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Sr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Zy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
2
2
  `,chainPem:""};let r=`${n.trim()}
3
3
  `,f=t.slice(1).map((c)=>c.trim()).join(`
4
4
  `);return{certPem:r,chainPem:f?`${f}
5
- `:""}}function Zy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function vl(i){return new Promise((t)=>setTimeout(t,i))}function $1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function mt(i,t){return Buffer.concat([Buffer.from([i]),$1(t.length),t])}function vy(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return mt(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return mt(6,Buffer.from(n))}function ai(...i){return mt(48,Buffer.concat(i))}function a0(...i){return mt(49,Buffer.concat(i))}function J0(i){return mt(3,Buffer.concat([Buffer.from([0]),i]))}function oy(i){return mt(4,i)}function py(i){return mt(12,Buffer.from(i,"utf8"))}function F0(i,t,n){let r=128|(n?32:0)|i;return mt(r,t)}var A1="1.2.840.10045.2.1",T1="1.2.840.10045.3.1.7",E1="1.2.840.10045.4.3.2",Y1="2.5.4.3",B1="1.2.840.113549.1.9.14",e1="2.5.29.17";function C1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=S0(t.x),r=S0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function iw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(a0(ai(Kt(Y1),py(t[0])))),c=ai(ai(Kt(A1),Kt(T1)),J0(C1(n))),l=t.map((E)=>F0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(e1),oy(y)),u=ai(w),h=ai(Kt(B1),a0(u)),$=F0(0,h,!0),A=ai(vy(0),f,c,$),T=h1("sha256",A,r),e=ai(Kt(E1));return ai(A,e,J0(T))}function tw(i){return iw(i).toString("base64url")}function U1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=l1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=nw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function d0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?by:Dy),f=U1(i.accountKeyPem),c=new Sr({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??xr,u=[],h=[];try{for(let R of l.authorizations){let a=await c.getAuthorization(R);if(a.status==="valid")continue;let G=Sr.selectChallenge(a,n);if(n==="dns-01"){let o=Zy(a.identifier.value),ki=c.dns01TxtValue(G.token);await i.dnsProvider.setTxt(o,ki),u.push({name:o,value:ki}),await xy(o,ki,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(G.token,c.keyAuthorization(G.token)),h.push(G.token);await c.notifyChallengeReady(G.url),await c.pollAuthorization(R,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=nw("ec",{namedCurve:"P-256"}),T=tw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let e=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(e),{certPem:B,chainPem:C}=Py(E),U=C?`${B}${C}`:B,W=$.export({format:"pem",type:"pkcs8"}).toString(),S=new Date(new m1(B).validTo);return{certPem:B,keyPem:W,chainPem:C,fullChainPem:U,accountKeyPem:f.pem,notAfter:S}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class cw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ol(i))return!0;return pl(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ol(n)?pl(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class lw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var Kr=new cw,D0=new lw,wA=Object.defineProperty,uA=(i)=>i;function hA(i,t){this[i]=uA.bind(null,t)}var $A=(i,t)=>{for(var n in t)wA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:hA.bind(t,n)})},AA=(i,t)=>()=>(i&&(t=i(i=0)),t),yw={};$A(yw,{withErrorRecovery:()=>hw,tryLoadConfig:()=>MA,loadConfigWithResult:()=>zA,loadConfig:()=>Yw,isRetryableError:()=>aA,isConfigNotFoundError:()=>SA,isBunfigError:()=>$w,globalPerformanceMonitor:()=>zn,globalCache:()=>tn,getEnvOrDefault:()=>JA,generateConfigTypes:()=>OA,defaultGeneratedDir:()=>Rw,defaultConfigDir:()=>Nw,deepMergeWithArrayStrategy:()=>o0,deepMerge:()=>Aw,createLibraryConfig:()=>GA,config:()=>QA,bunfigPlugin:()=>HA,applyEnvVarsToConfig:()=>Sn,TypeGenerationError:()=>H0,SchemaValidationError:()=>Kn,PluginError:()=>g0,PerformanceMonitor:()=>P0,FileSystemError:()=>G0,ErrorFactory:()=>Ct,EnvVarError:()=>Gr,EnvProcessor:()=>Vr,ConfigValidator:()=>p0,ConfigValidationError:()=>M0,ConfigNotFoundError:()=>Or,ConfigMergeError:()=>O0,ConfigLoader:()=>ic,ConfigLoadError:()=>In,ConfigFileLoader:()=>dr,ConfigCache:()=>b0,CacheUtils:()=>ew,BunfigError:()=>Ri,BrowserConfigError:()=>q0,ArrayMergeStrategies:()=>Uw});class b0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!iy(i))return!0;return ty(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=iy(n)?ty(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class P0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function TA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function EA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function YA(i){return i.getStats().size*2}function Z0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>_r(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=Z0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>_r(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function _r(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!_r(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!_r(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function BA(i,t){if(!fw(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 Z0(t,r)}catch{return null}}catch{return null}}async function eA({name:i="",cwd:t,defaultConfig:n}){let r=t||K0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Fr(r,`${l}${y}`),u=await BA(w,n);if(u!==null)return u}try{let l=Fr(r,"package.json");if(fw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return Z0(n,y)}catch{}}}catch{}return n}function CA(i,t={}){let n=Jr.cwd();while(n.includes("storage"))n=fy(n,"..");let r=fy(n,i||"");if(t?.relative)return F1(Jr.cwd(),r);return r}async function mA(){try{let i=await eA({name:"clarity",defaultConfig:jr,cwd:Jr.cwd(),endpoint:"",headers:{}});return{...jr,...i}}catch{return jr}}function b(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UA(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof it<"u"){let i=it.type;if(i==="renderer"||i==="worker")return!1;return!!(it.versions&&(it.versions.node||it.versions.bun))}return!1}class ww{async format(i){let t=await UA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:dt.pid,hostname:t(),environment:dt.env.NODE_ENV||"development",platform:dt.platform,version:dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dt.env.NODE_ENV||dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zr{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={...z0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ww,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Nr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Nr};return{...Nr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:z0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await Q1(this.config.logDirectory,wy.F_OK|wy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await M1(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:Bt.from(i);try{if(!h0(this.currentLogFile))await $0(this.currentLogFile,"",{mode:420});if(r=yy(this.currentLogFile,"a",420),z1(r,y,{flag:"a"}),ly(r),r!==void 0)u0(r),r=void 0;if((await kt(this.currentLogFile)).size===0){if(await $0(this.currentLogFile,y,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{u0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return w0(16).toString("hex")}generateKey(){return w0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=w0(16),r=I1("aes-256-gcm",t,n),f=Bt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Bt.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=hy(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(Bt.from(Bt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await kt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await fr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await kt(n).catch(()=>null))try{if(await uy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await cr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await $0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await kt(n).catch(()=>null))await uy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await fr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await cr(Vt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=cy(i),r=_1(t),f=hy();await O1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),h0(this.currentLogFile))try{let i=yy(this.currentLogFile,"r+");ly(i),u0(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 fr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await cr(Vt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=Cw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
5
+ `:""}}function vy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function ol(i){return new Promise((t)=>setTimeout(t,i))}function A1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function mt(i,t){return Buffer.concat([Buffer.from([i]),A1(t.length),t])}function oy(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return mt(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return mt(6,Buffer.from(n))}function ai(...i){return mt(48,Buffer.concat(i))}function J0(...i){return mt(49,Buffer.concat(i))}function F0(i){return mt(3,Buffer.concat([Buffer.from([0]),i]))}function py(i){return mt(4,i)}function iw(i){return mt(12,Buffer.from(i,"utf8"))}function I0(i,t,n){let r=128|(n?32:0)|i;return mt(r,t)}var T1="1.2.840.10045.2.1",E1="1.2.840.10045.3.1.7",Y1="1.2.840.10045.4.3.2",B1="2.5.4.3",e1="1.2.840.113549.1.9.14",C1="2.5.29.17";function m1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=a0(t.x),r=a0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function tw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(J0(ai(Kt(B1),iw(t[0])))),c=ai(ai(Kt(T1),Kt(E1)),F0(m1(n))),l=t.map((E)=>I0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(C1),py(y)),u=ai(w),h=ai(Kt(e1),J0(u)),$=I0(0,h,!0),A=ai(oy(0),f,c,$),T=$1("sha256",A,r),e=ai(Kt(Y1));return ai(A,e,F0(T))}function nw(i){return tw(i).toString("base64url")}function j1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=y1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=rw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function D0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Py:by),f=j1(i.accountKeyPem),c=new ar({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??kr,u=[],h=[];try{for(let R of l.authorizations){let a=await c.getAuthorization(R);if(a.status==="valid")continue;let G=ar.selectChallenge(a,n);if(n==="dns-01"){let o=vy(a.identifier.value),ki=c.dns01TxtValue(G.token);await i.dnsProvider.setTxt(o,ki),u.push({name:o,value:ki}),await ky(o,ki,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(G.token,c.keyAuthorization(G.token)),h.push(G.token);await c.notifyChallengeReady(G.url),await c.pollAuthorization(R,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=rw("ec",{namedCurve:"P-256"}),T=nw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let e=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(e),{certPem:B,chainPem:C}=Zy(E),U=C?`${B}${C}`:B,W=$.export({format:"pem",type:"pkcs8"}).toString(),S=new Date(new U1(B).validTo);return{certPem:B,keyPem:W,chainPem:C,fullChainPem:U,accountKeyPem:f.pem,notAfter:S}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class lw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!pl(i))return!0;return iy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=pl(n)?iy(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class yw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new lw,b0=new yw,uA=Object.defineProperty,hA=(i)=>i;function $A(i,t){this[i]=hA.bind(null,t)}var AA=(i,t)=>{for(var n in t)uA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:$A.bind(t,n)})},TA=(i,t)=>()=>(i&&(t=i(i=0)),t),ww={};AA(ww,{withErrorRecovery:()=>$w,tryLoadConfig:()=>OA,loadConfigWithResult:()=>QA,loadConfig:()=>Bw,isRetryableError:()=>JA,isConfigNotFoundError:()=>aA,isBunfigError:()=>Aw,globalPerformanceMonitor:()=>zn,globalCache:()=>tn,getEnvOrDefault:()=>FA,generateConfigTypes:()=>GA,defaultGeneratedDir:()=>Xw,defaultConfigDir:()=>Rw,deepMergeWithArrayStrategy:()=>p0,deepMerge:()=>Tw,createLibraryConfig:()=>HA,config:()=>MA,bunfigPlugin:()=>qA,applyEnvVarsToConfig:()=>Sn,TypeGenerationError:()=>q0,SchemaValidationError:()=>Kn,PluginError:()=>L0,PerformanceMonitor:()=>Z0,FileSystemError:()=>H0,ErrorFactory:()=>Ct,EnvVarError:()=>Hr,EnvProcessor:()=>dr,ConfigValidator:()=>ic,ConfigValidationError:()=>O0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>G0,ConfigLoader:()=>tc,ConfigLoadError:()=>In,ConfigFileLoader:()=>Dr,ConfigCache:()=>P0,CacheUtils:()=>Cw,BunfigError:()=>Ri,BrowserConfigError:()=>g0,ArrayMergeStrategies:()=>jw});class P0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ty(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ty(n)?ny(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Z0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function EA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function YA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function BA(i){return i.getStats().size*2}function v0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>zr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=v0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>zr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function zr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function eA(i,t){if(!cw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return v0(t,r)}catch{return null}}catch{return null}}async function CA({name:i="",cwd:t,defaultConfig:n}){let r=t||_0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Ir(r,`${l}${y}`),u=await eA(w,n);if(u!==null)return u}try{let l=Ir(r,"package.json");if(cw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return v0(n,y)}catch{}}}catch{}return n}function mA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=cy(n,"..");let r=cy(n,i||"");if(t?.relative)return I1(Fr.cwd(),r);return r}async function UA(){try{let i=await CA({name:"clarity",defaultConfig:Nr,cwd:Fr.cwd(),endpoint:"",headers:{}});return{...Nr,...i}}catch{return Nr}}function b(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jA(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof it<"u"){let i=it.type;if(i==="renderer"||i==="worker")return!1;return!!(it.versions&&(it.versions.node||it.versions.bun))}return!1}class uw{async format(i){let t=await jA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:dt.pid,hostname:t(),environment:dt.env.NODE_ENV||"development",platform:dt.platform,version:dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dt.env.NODE_ENV||dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Q0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rr};return{...Rr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Q0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await M1(this.config.logDirectory,uy.F_OK|uy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await O1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Bt.from(i);try{if(!$0(this.currentLogFile))await A0(this.currentLogFile,"",{mode:420});if(r=wy(this.currentLogFile,"a",420),Q1(r,y,{flag:"a"}),yy(r),r!==void 0)h0(r),r=void 0;if((await kt(this.currentLogFile)).size===0){if(await A0(this.currentLogFile,y,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{h0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return u0(16).toString("hex")}generateKey(){return u0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=u0(16),r=K1("aes-256-gcm",t,n),f=Bt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Bt.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=$y(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(Bt.from(Bt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await kt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await kt(n).catch(()=>null))try{if(await hy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await lr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await A0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await kt(n).catch(()=>null))await hy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await cr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await lr(Vt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=ly(i),r=z1(t),f=$y();await G1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),$0(this.currentLogFile))try{let i=wy(this.currentLogFile,"r+");yy(i),h0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await lr(Vt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=mw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
6
6
  `);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:x.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let w=`${c} ${this.environment}.${i.toUpperCase()}: ${l}
7
7
  `;if(y)w+=`${y}
8
8
  `;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!b()){let n=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:x.blue("◐"),tag:n,message:`${x.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
9
- `,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:x.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new zr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!h0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return cy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Bt.isBuffer(i)?i:Bt.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=K1("aes-256-gcm",n,f);return y.setAuthTag(c),Bt.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!b()){let c=i.split(`
9
+ `,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:x.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Qr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!$0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ly(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Bt.isBuffer(i)?i:Bt.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=_1("aes-256-gcm",n,f);return y.setAuthTag(c),Bt.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!b()){let c=i.split(`
10
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:n,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(w),showTimestamp:!1}))}else if(!b())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
11
11
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(b())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();yi.stdin.removeListener("data",n);try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!1)}catch{}yi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!0)}catch{}yi.stdin.resume(),yi.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,c=0;if(n=i.replace(f,(l,y)=>{if(y==="%")return"%";if(c>=t.length)return l;let w=t[c++];switch(y){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),c<t.length)n+=` ${t.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!b()){let f=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",c=x.blue("◐");console.error(`${c} ${f} ${x.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
12
12
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,r)),f!==void 0)this.activeProgressBar.message=f;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;yi.stdout.write(`${"\r".padEnd(yi.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=x.green("━".repeat(r)),l=x.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?x.green("✓"):x.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=yi.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,yi.stdout.write(i.lastRenderedLine),t)yi.stdout.write(`
13
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await fr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,r);if(i.before)try{if((await kt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await cr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Ur(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let r=[...t];for(let f of i)if(g(f)&&"name"in f){if(!r.find((c)=>g(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(g(f)&&"path"in f){if(!r.find((c)=>g(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>Qr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!g(t)||!g(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(g(f)&&g(n[r]))n[r]=Ur(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&g(f[0])&&g(n[r][0])){let c=[...f];for(let l of n[r])if(g(l)&&"name"in l){if(!c.find((y)=>g(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(g(l)&&"path"in l){if(!c.find((y)=>g(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Qr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function v0(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:Ur(i,t);if(Array.isArray(i))return n==="replace"?t:Ur(i,t);if(!g(t)||!g(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=Ur(l,c);else if(g(c)&&g(l))r[f]=v0(l,c,n);else r[f]=c}return r}function Qr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Qr(i[n],t[n]))return!1;return!0}if(g(i)&&g(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Qr(i[f],t[f]))return!1}return!0}return!1}function g(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Br(i,t,n="replace"){if(!rw(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return v0(t,f,n)}catch{return null}}catch{return null}}function jA(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...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=`${r}_${$.map(A).join("_")}`,e=`${r}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(n)ui.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=Fn.env[T]||Fn.env[e];if(E!==void 0){if(n)ui.info(`Using environment variable ${E?T:e} 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((C)=>C.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function NA({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?jA(i,f,c):f,u=n||Fn.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)ui.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}`]:[],e=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Ei(u,"config"),Ei(u,".config"),r?Ei(u,r):void 0].filter(Boolean)));for(let B of E){if(c)ui.info(`Searching for configuration in: ${B}`);let C=[Ei(u,"config"),Ei(u,".config")].concat(r?[Ei(u,r)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await Br(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from: ${S}`);return R}}}if(i){let B=Ei(y0(),".config",i),C=["config",`${i}.config`];if(t)C.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${B}`);for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await Br(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from user config directory: ${S}`);return R}}}if(i){let B=Ei(y0(),".config"),C=[`.${i}.config`];if(t)C.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await Br(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${S}`);return R}}}if(i){let B=y0(),C=[`.${i}.config`,`.${i}`];if(t)C.push(`.${t}.config`),C.push(`.${t}`);if(c)ui.info(`Checking user home directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await Br(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from user home directory: ${S}`);return R}}}try{let B=Ei(u,"package.json");if(rw(B)){let C=await import(B),U=C[i];if(!U&&t){if(U=C[t],U&&c)ui.success(`Using alias "${t}" configuration from package.json`)}if(U&&typeof U==="object"&&!Array.isArray(U))try{if(c)ui.success(`Configuration loaded from package.json: ${U===C[i]?i:t}`);return v0(w,U,y)}catch(W){if(c)ui.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)ui.warn("Failed to load package.json:",B)}if(c)ui.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function RA(i,t={}){let n=ar.cwd();while(n.includes("storage"))n=ry(n,"..");let r=ry(n,i||"");if(t?.relative)return a1(ar.cwd(),r);return r}async function XA(){try{let i=await NA({name:"clarity",alias:"logging",defaultConfig:Rr,cwd:ar.cwd()});return{...Rr,...i||{}}}catch{return Rr}}function p(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function WA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class uw{async format(i){let t=await WA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid: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}}}class Mr{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={...Q0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Xr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Xr};return{...Xr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Q0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await s1(this.config.logDirectory,Ey.F_OK|Ey.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await L1(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:vi.from(i);try{if(!lr(this.currentLogFile))await E0(this.currentLogFile,"",{mode:420});if(r=Ty(this.currentLogFile,"a",420),g1(r,y,{flag:"a"}),Ay(r),r!==void 0)T0(r),r=void 0;if((await Dt(this.currentLogFile)).size===0){if(await E0(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(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{T0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(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,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return A0(16).toString("hex")}generateKey(){return A0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=A0(16),r=G1("aes-256-gcm",t,n),f=vi.isBuffer(i)?i:vi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=vi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=By(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(vi.from(vi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(p())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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await yr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Dt(n).catch(()=>null))try{if(await Yy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await wr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await 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 f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Dt(n).catch(()=>null))await Yy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await yr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await wr(bt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=$y(i),r=q1(t),f=By();await V1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),lr(this.currentLogFile))try{let i=Ty(this.currentLogFile,"r+");Ay(i),T0(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 yr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await wr(bt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?z.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=H.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${z.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=z.underline(z.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>z.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>z.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>z.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>z.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>z.strikethrough(r)),t}supportsHyperlinks(){if(p())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=H.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(x1(t)||t.startsWith("./")||t.startsWith("../"))t=k1(t);else return null;return lr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":mw[i],A=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:z.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:z.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
13
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,r);if(i.before)try{if((await kt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await lr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let r=[...t];for(let f of i)if(g(f)&&"name"in f){if(!r.find((c)=>g(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(g(f)&&"path"in f){if(!r.find((c)=>g(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>Mr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!g(t)||!g(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(g(f)&&g(n[r]))n[r]=jr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&g(f[0])&&g(n[r][0])){let c=[...f];for(let l of n[r])if(g(l)&&"name"in l){if(!c.find((y)=>g(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(g(l)&&"path"in l){if(!c.find((y)=>g(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Mr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function o0(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:jr(i,t);if(Array.isArray(i))return n==="replace"?t:jr(i,t);if(!g(t)||!g(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=jr(l,c);else if(g(c)&&g(l))r[f]=o0(l,c,n);else r[f]=c}return r}function Mr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Mr(i[n],t[n]))return!1;return!0}if(g(i)&&g(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Mr(i[f],t[f]))return!1}return!0}return!1}function g(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function er(i,t,n="replace"){if(!fw(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return o0(t,f,n)}catch{return null}}catch{return null}}function NA(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...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=`${r}_${$.map(A).join("_")}`,e=`${r}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(n)ui.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=Fn.env[T]||Fn.env[e];if(E!==void 0){if(n)ui.info(`Using environment variable ${E?T:e} 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((C)=>C.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function RA({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?NA(i,f,c):f,u=n||Fn.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)ui.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}`]:[],e=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Ei(u,"config"),Ei(u,".config"),r?Ei(u,r):void 0].filter(Boolean)));for(let B of E){if(c)ui.info(`Searching for configuration in: ${B}`);let C=[Ei(u,"config"),Ei(u,".config")].concat(r?[Ei(u,r)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await er(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from: ${S}`);return R}}}if(i){let B=Ei(w0(),".config",i),C=["config",`${i}.config`];if(t)C.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${B}`);for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await er(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from user config directory: ${S}`);return R}}}if(i){let B=Ei(w0(),".config"),C=[`.${i}.config`];if(t)C.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await er(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${S}`);return R}}}if(i){let B=w0(),C=[`.${i}.config`,`.${i}`];if(t)C.push(`.${t}.config`),C.push(`.${t}`);if(c)ui.info(`Checking user home directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=Ei(B,`${U}${W}`),R=await er(S,w,y);if(R!==null){if(c)ui.success(`Configuration loaded from user home directory: ${S}`);return R}}}try{let B=Ei(u,"package.json");if(fw(B)){let C=await import(B),U=C[i];if(!U&&t){if(U=C[t],U&&c)ui.success(`Using alias "${t}" configuration from package.json`)}if(U&&typeof U==="object"&&!Array.isArray(U))try{if(c)ui.success(`Configuration loaded from package.json: ${U===C[i]?i:t}`);return o0(w,U,y)}catch(W){if(c)ui.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)ui.warn("Failed to load package.json:",B)}if(c)ui.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function XA(i,t={}){let n=Jr.cwd();while(n.includes("storage"))n=fy(n,"..");let r=fy(n,i||"");if(t?.relative)return J1(Jr.cwd(),r);return r}async function WA(){try{let i=await RA({name:"clarity",alias:"logging",defaultConfig:Xr,cwd:Jr.cwd()});return{...Xr,...i||{}}}catch{return Xr}}function p(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class hw{async format(i){let t=await SA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid: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}}}class Or{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={...M0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new hw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Wr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Wr};return{...Wr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:M0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await s1(this.config.logDirectory,Yy.F_OK|Yy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await x1(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:vi.from(i);try{if(!yr(this.currentLogFile))await Y0(this.currentLogFile,"",{mode:420});if(r=Ey(this.currentLogFile,"a",420),L1(r,y,{flag:"a"}),Ty(r),r!==void 0)E0(r),r=void 0;if((await Dt(this.currentLogFile)).size===0){if(await Y0(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(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{E0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(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,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return T0(16).toString("hex")}generateKey(){return T0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=T0(16),r=H1("aes-256-gcm",t,n),f=vi.isBuffer(i)?i:vi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=vi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=ey(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(vi.from(vi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(p())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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Dt(n).catch(()=>null))try{if(await By(n,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&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Y0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Dt(n).catch(()=>null))await By(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await wr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await ur(bt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Ay(i),r=g1(t),f=ey();await d1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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=Ey(this.currentLogFile,"r+");Ty(i),E0(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 wr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await ur(bt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?z.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=H.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${z.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=z.underline(z.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>z.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>z.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>z.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>z.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>z.strikethrough(r)),t}supportsHyperlinks(){if(p())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=H.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(k1(t)||t.startsWith("./")||t.startsWith("../"))t=V1(t);else return null;return yr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Uw[i],A=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:z.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:z.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
14
14
  `);for(let E of e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:z.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
15
  `;if(y)h+=`${y}
16
16
  `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,c="info")=>{if(!p()&&H.stdout.isTTY)H.stdout.write(`
17
17
  `);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":z.blue("◐"),tag:n,message:`${z.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
18
- `,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":z.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Mr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!lr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $y(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=vi.isBuffer(i)?i:vi.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=H1("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=vi.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
18
+ `,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":z.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Or(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ay(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=vi.isBuffer(i)?i:vi.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=q1("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=vi.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
19
19
  `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:z.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(h),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
20
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(`${z.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(n=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)n+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${y}${l} ${z.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
21
21
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=z.green("━".repeat(r)),l=z.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?z.green("✓"):z.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=H.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
22
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await yr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=bt(this.config.logDirectory,r);if(i.before)try{if((await Dt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await wr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function hw(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function $w(i){return i instanceof Ri}function SA(i){return i instanceof Or}function aA(i){if($w(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 Vr{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return zn.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=ur.env[w]||(u?ur.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=ur.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof Gr)throw $;throw Ct.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Ct.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(ur.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
22
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(p()){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),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=bt(this.config.logDirectory,r);if(i.before)try{if((await Dt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await ur(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $w(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Aw(i){return i instanceof Ri}function aA(i){return i instanceof Gr}function JA(i){if(Aw(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 dr{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return zn.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=hr.env[w]||(u?hr.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=hr.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof Hr)throw $;throw Ct.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Ct.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(hr.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
23
23
 
24
24
  `;for(let r of i)n+=`${r.key}
25
25
  `,n+=` Type: ${r.type}
@@ -31,25 +31,25 @@ import{Ab as F$,Bb as Nt,Cb as Y,Db as O$,Hb as Sh,Ib as wl,Kb as Of,Lb as ah,Nb
31
31
  `;n+=`| Variable | Type | Description | Example |
32
32
  `,n+=`|----------|------|-------------|----------|
33
33
  `;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
34
- `;return n}}function JA(i,t){let n=Bw("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Aw(i,t,n={}){return Tw(i,t,n,new WeakMap)}function Tw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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,f,r);if(!Fi(t)||!Fi(i))return t;return _A(i,t,n,r)}function Ew(i,t,n,r){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(n){case"replace":return t;case"concat":return FA(i,t);case"smart":return IA(i,t,r);default:return t}return t}function FA(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>_0(f,r)))n.push(r);return n}function IA(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Fi(t[0])&&Fi(i[0]))return KA(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function KA(i,t,n){let r=[...t];for(let f of i){if(!Fi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Fi(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function _A(i,t,n,r){let f=t;if(Fi(f)&&r.has(f))return r.get(f);let c={...i};if(Fi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Fi(y)&&Fi(w))c[l]=Tw(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Ew(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function o0(i,t,n="replace"){return Aw(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function _0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!_0(i[n],t[n]))return!1;return!0}if(Fi(i)&&Fi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!_0(i[f],t[f]))return!1}return!0}return!1}function Fi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class dr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=tn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!hr(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 In(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new In(i,Error("Configuration must export a valid object"),"unknown");let e={config:o0(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)tn.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?Ct.configLoad(i,u):Ct.configLoad(i,Error(String(u)))}};if(l)return zn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(Y0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return hw(async()=>{return hr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!hr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=Y0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Y0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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(!hr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class p0{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 zn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!d1(t))throw new Kn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Kn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:jw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ic{fileLoader=new dr;envProcessor=new Vr;validator=new p0;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Oi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Oi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_t.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Yi($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Ct.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Sn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Oi.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)Oi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Sn(i,n,f):n,y=[Yi(xt(),".config",i),Yi(xt(),".config"),xt()];for(let w of y){if(f)Oi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)Oi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Sn(i,r,c):r;try{let w=Yi(n,"package.json");if(!I0(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)Oi.success(`Configuration loaded from package.json: ${$}`);return{config:o0(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Oi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Sn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Ct.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return tn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);tn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Yi(i,"config"),Yi(i,".config"),t?Yi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Yi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Yi(xt(),".config",i),Yi(xt(),".config"),xt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Wy(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")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||n}async function zA(i){return ft.loadConfig({...i,__strictErrorHandling:!0})}async function Yw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ft.loadConfig(i);else r=await ft.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)Oi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ft.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function QA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ft.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Wy(n)))return(await ft.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ft.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"&&Wy(t)))return(await ft.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function MA(i,t,n="replace"){let r=new dr;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Sn(i,t,n=!1){let r=new Vr,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=_t.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 OA(i){let t=Yi(_t.cwd(),i.configDir),n=Yi(_t.cwd(),i.generatedDir),r=Yi(n,"config-types.ts");if(!I0(ny(r)))R1(ny(r),{recursive:!0,mode:511});let f=I0(t)?X1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${$T}
34
+ `;return n}}function FA(i,t){let n=ew("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Tw(i,t,n={}){return Ew(i,t,n,new WeakMap)}function Ew(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 Yw(i,t,f,r);if(!Fi(t)||!Fi(i))return t;return zA(i,t,n,r)}function Yw(i,t,n,r){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(n){case"replace":return t;case"concat":return IA(i,t);case"smart":return KA(i,t,r);default:return t}return t}function IA(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>z0(f,r)))n.push(r);return n}function KA(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Fi(t[0])&&Fi(i[0]))return _A(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function _A(i,t,n){let r=[...t];for(let f of i){if(!Fi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Fi(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function zA(i,t,n,r){let f=t;if(Fi(f)&&r.has(f))return r.get(f);let c={...i};if(Fi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Fi(y)&&Fi(w))c[l]=Ew(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Yw(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function p0(i,t,n="replace"){return Tw(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function z0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!z0(i[n],t[n]))return!1;return!0}if(Fi(i)&&Fi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!z0(i[f],t[f]))return!1}return!0}return!1}function Fi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Dr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=tn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$r(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 In(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new In(i,Error("Configuration must export a valid object"),"unknown");let e={config:p0(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)tn.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?Ct.configLoad(i,u):Ct.configLoad(i,Error(String(u)))}};if(l)return zn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(B0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return $w(async()=>{return $r(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!$r(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=B0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=B0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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(!$r(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class ic{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 zn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!D1(t))throw new Kn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Kn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:Nw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class tc{fileLoader=new Dr;envProcessor=new dr;validator=new ic;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Oi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Oi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_t.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Yi($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Ct.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Sn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Oi.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)Oi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Sn(i,n,f):n,y=[Yi(xt(),".config",i),Yi(xt(),".config"),xt()];for(let w of y){if(f)Oi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)Oi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Sn(i,r,c):r;try{let w=Yi(n,"package.json");if(!K0(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)Oi.success(`Configuration loaded from package.json: ${$}`);return{config:p0(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Oi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Sn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Ct.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return tn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);tn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Yi(i,"config"),Yi(i,".config"),t?Yi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Yi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Yi(xt(),".config",i),Yi(xt(),".config"),xt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Sy(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")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||n}async function QA(i){return ft.loadConfig({...i,__strictErrorHandling:!0})}async function Bw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ft.loadConfig(i);else r=await ft.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)Oi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ft.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function MA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ft.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Sy(n)))return(await ft.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ft.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"&&Sy(t)))return(await ft.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function OA(i,t,n="replace"){let r=new Dr;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Sn(i,t,n=!1){let r=new dr,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=_t.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 GA(i){let t=Yi(_t.cwd(),i.configDir),n=Yi(_t.cwd(),i.generatedDir),r=Yi(n,"config-types.ts");if(!K0(ry(r)))X1(ry(r),{recursive:!0,mode:511});let f=K0(t)?W1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${AT}
35
35
  export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
36
- `;W1(r,c,{mode:438})}function GA(i){let t=null,n=null,r=()=>{if(!n)n=Yw(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)Oi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return r(),y},has(c,l){return l in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||f,l)},set(c,l,y){if(!t)t={...f};return t[l]=y,!0}})}function HA(i){let t=ey(P1.cwd(),i?.configDir||"./config");function n(){if(!D1(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=b1(t).filter((w)=>f.has(B0(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=B0(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=B0($).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 r(){let f=n(),c=f.map((w)=>w.base),l=c.length?c.map((w)=>`'${w}'`).join(" | "):"string",y=f.length?`{
37
- ${f.map((w)=>{let u=ey(t,w.file).replace(/\\/g,"/");return` '${w.base}': typeof import('${u}').default`}).join(`,
36
+ `;S1(r,c,{mode:438})}function HA(i){let t=null,n=null,r=()=>{if(!n)n=Bw(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)Oi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return r(),y},has(c,l){return l in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||f,l)},set(c,l,y){if(!t)t={...f};return t[l]=y,!0}})}function qA(i){let t=Cy(Z1.cwd(),i?.configDir||"./config");function n(){if(!b1(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=P1(t).filter((w)=>f.has(e0(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=e0(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=e0($).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 r(){let f=n(),c=f.map((w)=>w.base),l=c.length?c.map((w)=>`'${w}'`).join(" | "):"string",y=f.length?`{
37
+ ${f.map((w)=>{let u=Cy(t,w.file).replace(/\\/g,"/");return` '${w.base}': typeof import('${u}').default`}).join(`,
38
38
  `)}
39
39
  }`:"Record<string, any>";return`export type ConfigNames = ${l}
40
40
  export type ConfigByName = ${y}
41
41
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
42
42
  export type ConfigOf = Config
43
- `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Bw,tn,zn,ew,qA,gA,Sy,jr,z0,wi,x,sA,ay,LA,Jy,xA,kA,j0,VA,Fy,Iy,N0,dA,DA,bA,PA,Nr,Cw,ZA,ui,vA,oA,Ky,Rr,Q0,ii,z,pA,_y,iT,zy,tT,nT,R0,rT,Qy,My,fT,X0,cT,lT,yT,wT,uT,Xr,mw,hT,$T="0.15.6",Ri,Or,In,M0,O0,Gr,G0,H0,Kn,q0,g0,Ct,Uw,jw,Oi,ft,Nw,Rw,AT=AA(async()=>{Bw=import.meta.require,tn=new b0,zn=new P0,ew={createKey:TA,isEquivalent:EA,estimateMemoryUsage:YA},qA=Fr(K0.cwd(),"config"),gA=Fr(K0.cwd(),"src/generated"),Sy=Jr.env.CLARITY_LOG_DIR||J1(CA(),"logs"),jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},z0=await mA(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=wi,sA=wi.red,ay=wi.green,LA=wi.yellow,Jy=wi.blue,xA=wi.magenta,kA=wi.cyan,j0=wi.white,VA=wi.gray,Fy=wi.bgRed,Iy=wi.bgYellow,N0=wi.bold,dA=wi.dim,DA=wi.italic,bA=wi.underline,PA=wi.reset,Nr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Cw={debug:"\uD83D\uDD0D",info:Jy("ℹ"),success:ay("✓"),warning:Iy(j0(N0(" WARN "))),error:Fy(j0(N0(" ERROR ")))},ZA=new zr("stacks"),ui=new zr("bunfig",{showTags:!0}),vA=Ei(Fn.cwd(),"config"),oA=Ei(Fn.cwd(),"src/generated"),Ky=ar.env.CLARITY_LOG_DIR||S1(RA(),"logs"),Rr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ky,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Q0=await XA(),ii={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},z=ii,pA=ii.red,_y=ii.green,iT=ii.yellow,zy=ii.blue,tT=ii.magenta,nT=ii.cyan,R0=ii.white,rT=ii.gray,Qy=ii.bgRed,My=ii.bgYellow,fT=ii.bgGray,X0=ii.bold,cT=ii.dim,lT=ii.italic,yT=ii.underline,wT=ii.strikethrough,uT=ii.reset,Xr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mw={debug:"\uD83D\uDD0D",info:zy("ℹ"),success:_y("✓"),warning:My(R0(X0(" WARN "))),error:Qy(R0(X0(" ERROR ")))},hT=new Mr("stacks"),Ri=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,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Or=class extends Ri{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${i}"${r} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}},In=class extends Ri{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}},M0=class extends Ri{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}},O0=class extends Ri{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Gr=class extends Ri{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}},G0=class extends Ri{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}},H0=class extends Ri{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Kn=class extends Ri{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}},q0=class extends Ri{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}},g0=class extends Ri{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Ct={configNotFound(i,t,n){return new Or(i,t,n)},configLoad(i,t,n){return new In(i,t,n)},configValidation(i,t,n){return new M0(i,t,n)},configMerge(i,t,n,r){return new O0(i,t,n,r)},envVar(i,t,n,r){return new Gr(i,t,n,r)},fileSystem(i,t,n){return new G0(i,t,n)},typeGeneration(i,t,n){return new H0(i,t,n)},schemaValidation(i,t,n){return new Kn(i,t,n)},browserConfig(i,t,n,r){return new q0(i,t,n,r)},plugin(i,t,n){return new g0(i,t,n)}},Uw={replace:"replace",concat:"concat",smart:"smart"},jw=/^https?:\/\//,Oi=new Mr("bunfig",{showTags:!0}),ft=new ic,Nw=Yi(_t.cwd(),"config"),Rw=Yi(_t.cwd(),"src/generated")});function TT(i,t={}){let n=Ir.cwd();while(n.includes("storage"))n=Cy(n,"..");let r=Cy(n,i||"");if(t?.relative)return v1(Ir.cwd(),r);return r}var ET=Ir.env.CLARITY_LOG_DIR||Z1(TT(),"logs"),Xw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ET,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Hr={...Xw},hU=(async()=>{try{let{loadConfig:i}=await AT().then(()=>yw),t=await i({name:"clarity",alias:"logging",defaultConfig:Xw,cwd:Ir.cwd()});if(t)Object.assign(Hr,t)}catch{}return Hr})();function ti(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YT(){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 Ww{async format(i){let t=await YT(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:ot.pid,hostname:t(),environment:ot.env.NODE_ENV||"development",platform:ot.platform,version:ot.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ot.env.NODE_ENV||ot.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},M=ci,$U=ci.red,BT=ci.green,AU=ci.yellow,eT=ci.blue,TU=ci.magenta,EU=ci.cyan,Oy=ci.white,YU=ci.gray,CT=ci.bgRed,mT=ci.bgYellow,BU=ci.bgGray,Gy=ci.bold,eU=ci.dim,CU=ci.italic,mU=ci.underline,UU=ci.strikethrough,jU=ci.reset,W0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},UT={debug:"\uD83D\uDD0D",info:eT("ℹ"),success:BT("✓"),warning:mT(Oy(Gy(" WARN "))),error:CT(Oy(Gy(" ERROR ")))};class Dr{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={...Hr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ww,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 n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...W0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...W0};return{...W0,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Hr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await nA(this.config.logDirectory,Ny.F_OK|Ny.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await rA(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(!$r(this.currentLogFile))await m0(this.currentLogFile,"",{mode:420});if(r=jy(this.currentLogFile,"a",420),tA(r,y,{flag:"a"}),Uy(r),r!==void 0)C0(r),r=void 0;if((await Zt(this.currentLogFile)).size===0){if(await m0(this.currentLogFile,y,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{C0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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 i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return e0(16).toString("hex")}generateKey(){return e0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=e0(16),r=o1("aes-256-gcm",t,n),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=oi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Xy(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(oi.from(oi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await Zt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ar(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Zt(n).catch(()=>null))try{if(await Ry(n,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&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await m0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Zt(n).catch(()=>null))await Ry(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await Ar(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await Tr(vt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=my(i),r=iA(t),f=Xy();await lA(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),$r(this.currentLogFile))try{let i=jy(this.currentLogFile,"r+");Uy(i),C0(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 i=(await Ar(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Tr(vt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.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:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${M.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=M.underline(M.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>M.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>M.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>M.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>M.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>M.strikethrough(r)),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 n=q.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(fA(t)||t.startsWith("./")||t.startsWith("../"))t=cA(t);else return null;return $r(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":UT[i],A=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
43
+ `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var ew,tn,zn,Cw,gA,LA,ay,Nr,Q0,wi,x,sA,Jy,xA,Fy,kA,VA,N0,dA,Iy,Ky,R0,DA,bA,PA,ZA,Rr,mw,vA,ui,oA,pA,_y,Xr,M0,ii,z,iT,zy,tT,Qy,nT,rT,X0,fT,My,Oy,cT,W0,lT,yT,wT,uT,hT,Wr,Uw,$T,AT="0.15.6",Ri,Gr,In,O0,G0,Hr,H0,q0,Kn,g0,L0,Ct,jw,Nw,Oi,ft,Rw,Xw,TT=TA(async()=>{ew=import.meta.require,tn=new P0,zn=new Z0,Cw={createKey:EA,isEquivalent:YA,estimateMemoryUsage:BA},gA=Ir(_0.cwd(),"config"),LA=Ir(_0.cwd(),"src/generated"),ay=Fr.env.CLARITY_LOG_DIR||F1(mA(),"logs"),Nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ay,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Q0=await UA(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=wi,sA=wi.red,Jy=wi.green,xA=wi.yellow,Fy=wi.blue,kA=wi.magenta,VA=wi.cyan,N0=wi.white,dA=wi.gray,Iy=wi.bgRed,Ky=wi.bgYellow,R0=wi.bold,DA=wi.dim,bA=wi.italic,PA=wi.underline,ZA=wi.reset,Rr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mw={debug:"\uD83D\uDD0D",info:Fy("ℹ"),success:Jy("✓"),warning:Ky(N0(R0(" WARN "))),error:Iy(N0(R0(" ERROR ")))},vA=new Qr("stacks"),ui=new Qr("bunfig",{showTags:!0}),oA=Ei(Fn.cwd(),"config"),pA=Ei(Fn.cwd(),"src/generated"),_y=Jr.env.CLARITY_LOG_DIR||a1(XA(),"logs"),Xr={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,writeToFile:!1},M0=await WA(),ii={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},z=ii,iT=ii.red,zy=ii.green,tT=ii.yellow,Qy=ii.blue,nT=ii.magenta,rT=ii.cyan,X0=ii.white,fT=ii.gray,My=ii.bgRed,Oy=ii.bgYellow,cT=ii.bgGray,W0=ii.bold,lT=ii.dim,yT=ii.italic,wT=ii.underline,uT=ii.strikethrough,hT=ii.reset,Wr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Uw={debug:"\uD83D\uDD0D",info:Qy("ℹ"),success:zy("✓"),warning:Oy(X0(W0(" WARN "))),error:My(X0(W0(" ERROR ")))},$T=new Or("stacks"),Ri=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,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Gr=class extends Ri{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${i}"${r} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}},In=class extends Ri{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}},O0=class extends Ri{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}},G0=class extends Ri{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Hr=class extends Ri{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}},H0=class extends Ri{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}},q0=class extends Ri{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Kn=class extends Ri{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}},g0=class extends Ri{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}},L0=class extends Ri{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Ct={configNotFound(i,t,n){return new Gr(i,t,n)},configLoad(i,t,n){return new In(i,t,n)},configValidation(i,t,n){return new O0(i,t,n)},configMerge(i,t,n,r){return new G0(i,t,n,r)},envVar(i,t,n,r){return new Hr(i,t,n,r)},fileSystem(i,t,n){return new H0(i,t,n)},typeGeneration(i,t,n){return new q0(i,t,n)},schemaValidation(i,t,n){return new Kn(i,t,n)},browserConfig(i,t,n,r){return new g0(i,t,n,r)},plugin(i,t,n){return new L0(i,t,n)}},jw={replace:"replace",concat:"concat",smart:"smart"},Nw=/^https?:\/\//,Oi=new Or("bunfig",{showTags:!0}),ft=new tc,Rw=Yi(_t.cwd(),"config"),Xw=Yi(_t.cwd(),"src/generated")});function ET(i,t={}){let n=Kr.cwd();while(n.includes("storage"))n=my(n,"..");let r=my(n,i||"");if(t?.relative)return o1(Kr.cwd(),r);return r}var YT=Kr.env.CLARITY_LOG_DIR||v1(ET(),"logs"),Ww={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qr={...Ww},$U=(async()=>{try{let{loadConfig:i}=await TT().then(()=>ww),t=await i({name:"clarity",alias:"logging",defaultConfig:Ww,cwd:Kr.cwd()});if(t)Object.assign(qr,t)}catch{}return qr})();function ti(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BT(){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 Sw{async format(i){let t=await BT(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:ot.pid,hostname:t(),environment:ot.env.NODE_ENV||"development",platform:ot.platform,version:ot.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ot.env.NODE_ENV||ot.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},M=ci,AU=ci.red,eT=ci.green,TU=ci.yellow,CT=ci.blue,EU=ci.magenta,YU=ci.cyan,Gy=ci.white,BU=ci.gray,mT=ci.bgRed,UT=ci.bgYellow,eU=ci.bgGray,Hy=ci.bold,CU=ci.dim,mU=ci.italic,UU=ci.underline,jU=ci.strikethrough,NU=ci.reset,S0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jT={debug:"\uD83D\uDD0D",info:CT("ℹ"),success:eT("✓"),warning:UT(Gy(Hy(" WARN "))),error:mT(Gy(Hy(" ERROR ")))};class br{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={...qr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Sw,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 n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...S0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...S0};return{...S0,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:qr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await rA(this.config.logDirectory,Ry.F_OK|Ry.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await fA(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(!Ar(this.currentLogFile))await U0(this.currentLogFile,"",{mode:420});if(r=Ny(this.currentLogFile,"a",420),nA(r,y,{flag:"a"}),jy(r),r!==void 0)m0(r),r=void 0;if((await Zt(this.currentLogFile)).size===0){if(await U0(this.currentLogFile,y,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{m0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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 i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return C0(16).toString("hex")}generateKey(){return C0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=C0(16),r=p1("aes-256-gcm",t,n),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=oi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Wy(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(oi.from(oi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await Zt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Tr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Zt(n).catch(()=>null))try{if(await Xy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await Er(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await U0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Zt(n).catch(()=>null))await Xy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await Tr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await Er(vt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Uy(i),r=tA(t),f=Wy();await yA(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),Ar(this.currentLogFile))try{let i=Ny(this.currentLogFile,"r+");jy(i),m0(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 i=(await Tr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Er(vt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.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:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${M.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=M.underline(M.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>M.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>M.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>M.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>M.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>M.strikethrough(r)),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 n=q.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(cA(t)||t.startsWith("./")||t.startsWith("../"))t=lA(t);else return null;return Ar(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":jT[i],A=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
44
44
  `);for(let E of e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:M.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
45
45
  `;if(y)h+=`${y}
46
46
  `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,c="info")=>{if(!ti()&&q.stdout.isTTY)q.stdout.write(`
47
47
  `);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:n,message:`${M.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
48
- `,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":M.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ti())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}`,n=new Dr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!$r(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return my(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=oi.isBuffer(i)?i:oi.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=p1("aes-256-gcm",n,f);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(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
48
+ `,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":M.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ti())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}`,n=new br(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!Ar(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 n=this.keys.get(this.currentKeyId);try{let r=oi.isBuffer(i)?i:oi.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=iA("aes-256-gcm",n,f);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(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
49
49
  `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:M.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:M.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:M.cyan(h),showTimestamp:!1}))}else if(!ti())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
50
50
  `.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(`${M.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();q.stdin.removeListener("data",n);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(n=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)n+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${y}${l} ${M.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
51
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 n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=M.green("━".repeat(r)),l=M.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?M.green("✓"):M.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=q.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
52
- `)}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 Ar(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=vt(this.config.logDirectory,r);if(i.before)try{if((await Zt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Tr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var NU=new Dr("stacks");class qi 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,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Sw extends qi{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class qr extends qi{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class aw extends qi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Jw extends qi{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class tc extends qi{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Fw extends qi{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Iw extends qi{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class gr extends qi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Kw extends qi{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class _w extends qi{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var nn={configNotFound(i,t,n){return new Sw(i,t,n)},configLoad(i,t,n){return new qr(i,t,n)},configValidation(i,t,n){return new aw(i,t,n)},configMerge(i,t,n,r){return new Jw(i,t,n,r)},envVar(i,t,n,r){return new tc(i,t,n,r)},fileSystem(i,t,n){return new Fw(i,t,n)},typeGeneration(i,t,n){return new Iw(i,t,n)},schemaValidation(i,t,n){return new gr(i,t,n)},browserConfig(i,t,n,r){return new Kw(i,t,n,r)},plugin(i,t,n){return new _w(i,t,n)}};async function jT(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class nc{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return D0.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=Er.env[w]||(u?Er.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=Er.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof tc)throw $;throw nn.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw nn.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(Er.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
52
+ `)}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 Tr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=vt(this.config.logDirectory,r);if(i.before)try{if((await Zt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Er(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var RU=new br("stacks");class qi 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,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class aw extends qi{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class gr extends qi{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class Jw extends qi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Fw extends qi{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class nc extends qi{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Iw extends qi{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Kw extends qi{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Lr extends qi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class _w extends qi{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class zw extends qi{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var nn={configNotFound(i,t,n){return new aw(i,t,n)},configLoad(i,t,n){return new gr(i,t,n)},configValidation(i,t,n){return new Jw(i,t,n)},configMerge(i,t,n,r){return new Fw(i,t,n,r)},envVar(i,t,n,r){return new nc(i,t,n,r)},fileSystem(i,t,n){return new Iw(i,t,n)},typeGeneration(i,t,n){return new Kw(i,t,n)},schemaValidation(i,t,n){return new Lr(i,t,n)},browserConfig(i,t,n,r){return new _w(i,t,n,r)},plugin(i,t,n){return new zw(i,t,n)}};async function NT(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class rc{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return b0.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=Yr.env[w]||(u?Yr.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=Yr.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof nc)throw $;throw nn.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw nn.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(Yr.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
53
53
 
54
54
  `;for(let r of i)n+=`${r.key}
55
55
  `,n+=` Type: ${r.type}
@@ -61,32 +61,32 @@ export type ConfigOf = Config
61
61
  `;n+=`| Variable | Type | Description | Example |
62
62
  `,n+=`|----------|------|-------------|----------|
63
63
  `;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
64
- `;return n}}function NT(i,t,n={}){return zw(i,t,n,new WeakMap)}function zw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 Qw(i,t,f,r);if(!Ii(t)||!Ii(i))return t;return ST(i,t,n,r)}function Qw(i,t,n,r){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(n){case"replace":return t;case"concat":return RT(i,t);case"smart":return XT(i,t,r);default:return t}return t}function RT(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>s0(f,r)))n.push(r);return n}function XT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return WT(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function WT(i,t,n){let r=[...t];for(let f of i){if(!Ii(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Ii(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function ST(i,t,n,r){let f=t;if(Ii(f)&&r.has(f))return r.get(f);let c={...i};if(Ii(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Ii(y)&&Ii(w))c[l]=zw(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Qw(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Mw(i,t,n="replace"){return NT(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function s0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!s0(i[n],t[n]))return!1;return!0}if(Ii(i)&&Ii(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!s0(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Ow{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=Kr.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Yr(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 qr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new qr(i,Error("Configuration must export a valid object"),"unknown");let e={config:Mw(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Kr.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?nn.configLoad(i,u):nn.configLoad(i,Error(String(u)))}};if(l)return D0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(U0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return jT(async()=>{return Yr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!Yr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=U0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=U0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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(!Yr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var aT=/^https?:\/\//;class Gw{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 D0.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!yA(t))throw new gr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new gr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:aT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var pi=new Dr("bunfig",{showTags:!0});function JT(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((n)=>`"${n}"`).join(", ")}`}class Hw{fileLoader=new Ow;envProcessor=new nc;validator=new Gw;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)pi.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 pi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||kr.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ji($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw nn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${JT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?er(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)pi.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)pi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?er(i,n,f):n,y=[Ji(Lt(),".config",i),Ji(Lt(),".config"),Lt()];for(let w of y){if(f)pi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)pi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?er(i,r,c):r;try{let w=Ji(n,"package.json");if(!j1(w))return null;let u={};try{u=JSON.parse(N1(w,"utf8"))}catch(A){if(c)pi.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)pi.success(`Configuration loaded from package.json: ${$}`);return{config:Mw(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)pi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:er(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw nn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Kr.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Kr.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.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,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ji(Lt(),".config",i),Ji(Lt(),".config"),Lt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var RU=new Hw;function er(i,t,n=!1){let r=new nc,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=kr.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 XU=Ji(kr.cwd(),"config"),WU=Ji(kr.cwd(),"src/generated"),qw={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:l0.join(c0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:l0.join(c0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:l0.join(c0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var v=qw,Gi={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 X={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},pt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function sw(i){return L0.readFileSync(i,"utf8")}function x0(i,t){let n=[];function r(f){let c;try{c=L0.readdirSync(f)}catch{return}for(let l of c){let y=Mi.join(f,l);try{if(L0.statSync(y).isDirectory())r(y);else if(l===t)n.push(f)}catch{continue}}}return r(i),n}function N(i,t,n){if(n||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var _T=KT(FT);function Lw(){return gw.env.SUDO_PASSWORD}var Hy="[redacted]",zT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),QT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function MT(i){let t=i.toLowerCase();return zT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function sr(i){if(Array.isArray(i))return i.map((n)=>sr(n));if(typeof i==="string")return QT.test(i)?Hy:i;if(!i||typeof i!=="object")return i;let t={};for(let[n,r]of Object.entries(i)){if(MT(n)){t[n]=Hy;continue}t[n]=sr(r)}return t}function br(i){return JSON.stringify(sr(i))}function OT(i){let t=Lw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let n=t.replace(/'/g,"'\\''"),r=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function et(i,t={}){let n=OT(i);try{let{stdout:r,stderr:f}=await _T(n,{cwd:t.cwd||gw.cwd(),timeout:t.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${i}
65
- Error: ${r.message}`);throw f.stack=r.stack,f}}function xw(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 rc(i){let t=Mi.join(IT.homedir(),".stacks","ssl"),n=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,r=i.certPath?Mi.isAbsolute(i.certPath)?i.certPath:Mi.join(n,i.certPath):Mi.join(n,v.certPath),f=i.keyPath?Mi.isAbsolute(i.keyPath)?i.keyPath:Mi.join(n,i.keyPath):Mi.join(n,v.keyPath),c=i.caCertPath?Mi.isAbsolute(i.caCertPath)?i.caCertPath:Mi.join(n,i.caCertPath):Mi.join(n,v.caCertPath);return{certPath:r,keyPath:f,caCertPath:c,basePath:n}}function kw(i){let t=[],n=new Set;if(i.domain)n.add(i.domain);if(i.domains?.length)i.domains.forEach((r)=>n.add(r));for(let r of n)t.push({type:2,value:r});if(i.altNameIPs?.length)for(let r of i.altNameIPs)t.push({type:7,ip:r});if(i.altNameURIs?.length)for(let r of i.altNameURIs)t.push({type:6,value:r});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return N(X.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function fc(i){let t=i.notBeforeDays??Gi.DEFAULT_NOT_BEFORE_DAYS,n=i.validityDays??(i.validityYears?i.validityYears*365:Gi.DEFAULT_VALIDITY_DAYS);N(X.CERT,"Calculating certificate validity dates",i.verbose);let r=new Date(Date.now()-86400*t*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),N(X.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:r,notAfter:f}}var Hi={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},Bi={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 an(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Wi(i,t){let n=an(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function _n(i){let t=i.split(".").map(Number),n=[];n.push(40*t[0]+t[1]);for(let r=2;r<t.length;r++){let f=t[r],c=[];c.unshift(f&127),f>>=7;while(f>0)c.unshift(f&127|128),f>>=7;n.push(...c)}return Wi(Hi.OID,Buffer.from(n))}function k0(i){let t;if(typeof i==="bigint"){let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Wi(Hi.INTEGER,t)}function Vw(i,t=0){return Wi(Hi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function dw(i){return Wi(Hi.OCTET_STRING,i)}function Xi(...i){return Wi(Hi.SEQUENCE,Buffer.concat(i))}function GT(...i){return Wi(Hi.SET,Buffer.concat(i))}function HT(i){return Wi(Hi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function qT(i){return Wi(Hi.UTF8_STRING,Buffer.from(i,"utf8"))}function gT(){return Buffer.from([Hi.NULL,0])}function qy(i,t,n=!0){let r=160|i|(n?0:0),f=an(t.length);return Buffer.concat([Buffer.from([r]),f,t])}function gy(i){let t=i.getUTCFullYear();if(t>=2050){let n=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Wi(Hi.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(t%100).toString().padStart(2,"0"),r=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=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=`${n}${r}${f}${c}${l}${y}Z`;return Wi(Hi.UTC_TIME,Buffer.from(w,"ascii"))}}function sT(i,t){return Xi(gy(i),gy(t))}function sy(i){let t=[];for(let n of i){let r;switch(n.shortName){case"CN":r=Bi.COMMON_NAME;break;case"C":r=Bi.COUNTRY;break;case"L":r=Bi.LOCALITY;break;case"ST":r=Bi.STATE;break;case"O":r=Bi.ORGANIZATION;break;case"OU":r=Bi.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?HT(n.value):qT(n.value),c=Xi(_n(r),f);t.push(GT(c))}return Xi(...t)}function Dw(i){return Xi(_n(i),gT())}function LT(i){return i.export({type:"spki",format:"der"})}function xT(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),c=f[0]?f[0].split(":"):[],l=f[1]?f[1].split(":"):[],y=8-c.length-l.length,w=Array.from({length:y},()=>"0");t=[...c,...w,...l].join(":")}let n=t.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let c=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(c,f*2)}return r}else{let t=i.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(t)}}function kT(i){let t=[];for(let n of i)if(n.type===2&&n.value){let r=an(n.value.length);t.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=xT(n.ip),f=an(r.length);t.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=an(n.value.length);t.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return Xi(...t)}function VT(i,t){if(i){if(t!==void 0)return Xi(Wi(1,Buffer.from([255])),k0(t));return Xi(Wi(1,Buffer.from([255])))}return Xi()}function dT(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 n=0,r=t;while(r>0&&(r&1)===0)n++,r>>=1;if(t===0)n=7;return Vw(Buffer.from([t]),n)}function DT(i){let t=[];if(i.serverAuth)t.push(_n(Bi.SERVER_AUTH));if(i.clientAuth)t.push(_n(Bi.CLIENT_AUTH));return Xi(...t)}function Wn(i,t,n){let r=[_n(i)];if(t)r.push(Wi(1,Buffer.from([255])));return r.push(dw(n)),Xi(...r)}function bT(i){let t=[];if(t.push(qy(0,k0(2))),t.push(k0(i.serialNumber)),t.push(Dw(Bi.SHA256_WITH_RSA)),t.push(sy(i.issuer)),t.push(sT(i.notBefore,i.notAfter)),t.push(sy(i.subject)),t.push(LT(i.publicKey)),i.extensions){let n=[];if(i.extensions.basicConstraints)n.push(Wn(Bi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,VT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)n.push(Wn(Bi.KEY_USAGE,i.extensions.keyUsage.critical??!0,dT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)n.push(Wn(Bi.EXTENDED_KEY_USAGE,!1,DT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)n.push(Wn(Bi.SUBJECT_ALT_NAME,!1,kT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)n.push(Wn(Bi.SUBJECT_KEY_IDENTIFIER,!1,dw(i.extensions.subjectKeyIdentifier)));if(n.length>0)t.push(qy(3,Xi(...n)))}return Xi(...t)}function PT(i,t){let n=rn.createSign("SHA256");n.update(i);let r=n.sign(t);return Xi(i,Dw(Bi.SHA256_WITH_RSA),Vw(r))}function ZT(i,t){let n=i.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${t}-----
64
+ `;return n}}function RT(i,t,n={}){return Qw(i,t,n,new WeakMap)}function Qw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 Mw(i,t,f,r);if(!Ii(t)||!Ii(i))return t;return aT(i,t,n,r)}function Mw(i,t,n,r){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(n){case"replace":return t;case"concat":return XT(i,t);case"smart":return WT(i,t,r);default:return t}return t}function XT(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>s0(f,r)))n.push(r);return n}function WT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return ST(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function ST(i,t,n){let r=[...t];for(let f of i){if(!Ii(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Ii(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function aT(i,t,n,r){let f=t;if(Ii(f)&&r.has(f))return r.get(f);let c={...i};if(Ii(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Ii(y)&&Ii(w))c[l]=Qw(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Mw(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Ow(i,t,n="replace"){return RT(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function s0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!s0(i[n],t[n]))return!1;return!0}if(Ii(i)&&Ii(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!s0(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Gw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=_r.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Br(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 gr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new gr(i,Error("Configuration must export a valid object"),"unknown");let e={config:Ow(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)_r.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?nn.configLoad(i,u):nn.configLoad(i,Error(String(u)))}};if(l)return b0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(j0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return NT(async()=>{return Br(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!Br(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=j0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=j0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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(!Br(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var JT=/^https?:\/\//;class Hw{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 b0.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!wA(t))throw new Lr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Lr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:JT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var pi=new br("bunfig",{showTags:!0});function FT(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((n)=>`"${n}"`).join(", ")}`}class qw{fileLoader=new Gw;envProcessor=new rc;validator=new Hw;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)pi.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 pi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Vr.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ji($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw nn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${FT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Cr(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)pi.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)pi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Cr(i,n,f):n,y=[Ji(st(),".config",i),Ji(st(),".config"),st()];for(let w of y){if(f)pi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)pi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Cr(i,r,c):r;try{let w=Ji(n,"package.json");if(!N1(w))return null;let u={};try{u=JSON.parse(R1(w,"utf8"))}catch(A){if(c)pi.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)pi.success(`Configuration loaded from package.json: ${$}`);return{config:Ow(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)pi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw nn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return _r.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);_r.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.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,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ji(st(),".config",i),Ji(st(),".config"),st()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var XU=new qw;function Cr(i,t,n=!1){let r=new rc,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=Vr.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 WU=Ji(Vr.cwd(),"config"),SU=Ji(Vr.cwd(),"src/generated"),gw={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:y0.join(l0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:y0.join(l0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:y0.join(l0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var v=gw,Gi={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 X={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},pt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function sw(i){return x0.readFileSync(i,"utf8")}function k0(i,t){let n=[];function r(f){let c;try{c=x0.readdirSync(f)}catch{return}for(let l of c){let y=Mi.join(f,l);try{if(x0.statSync(y).isDirectory())r(y);else if(l===t)n.push(f)}catch{continue}}}return r(i),n}function N(i,t,n){if(n||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var zT=_T(IT);function xw(){return Lw.env.SUDO_PASSWORD}var qy="[redacted]",QT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),MT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function OT(i){let t=i.toLowerCase();return QT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function sr(i){if(Array.isArray(i))return i.map((n)=>sr(n));if(typeof i==="string")return MT.test(i)?qy:i;if(!i||typeof i!=="object")return i;let t={};for(let[n,r]of Object.entries(i)){if(OT(n)){t[n]=qy;continue}t[n]=sr(r)}return t}function Pr(i){return JSON.stringify(sr(i))}function GT(i){let t=xw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let n=t.replace(/'/g,"'\\''"),r=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function et(i,t={}){let n=GT(i);try{let{stdout:r,stderr:f}=await zT(n,{cwd:t.cwd||Lw.cwd(),timeout:t.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${i}
65
+ Error: ${r.message}`);throw f.stack=r.stack,f}}function kw(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 fc(i){let t=Mi.join(KT.homedir(),".stacks","ssl"),n=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,r=i.certPath?Mi.isAbsolute(i.certPath)?i.certPath:Mi.join(n,i.certPath):Mi.join(n,v.certPath),f=i.keyPath?Mi.isAbsolute(i.keyPath)?i.keyPath:Mi.join(n,i.keyPath):Mi.join(n,v.keyPath),c=i.caCertPath?Mi.isAbsolute(i.caCertPath)?i.caCertPath:Mi.join(n,i.caCertPath):Mi.join(n,v.caCertPath);return{certPath:r,keyPath:f,caCertPath:c,basePath:n}}function Vw(i){let t=[],n=new Set;if(i.domain)n.add(i.domain);if(i.domains?.length)i.domains.forEach((r)=>n.add(r));for(let r of n)t.push({type:2,value:r});if(i.altNameIPs?.length)for(let r of i.altNameIPs)t.push({type:7,ip:r});if(i.altNameURIs?.length)for(let r of i.altNameURIs)t.push({type:6,value:r});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return N(X.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function cc(i){let t=i.notBeforeDays??Gi.DEFAULT_NOT_BEFORE_DAYS,n=i.validityDays??(i.validityYears?i.validityYears*365:Gi.DEFAULT_VALIDITY_DAYS);N(X.CERT,"Calculating certificate validity dates",i.verbose);let r=new Date(Date.now()-86400*t*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),N(X.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:r,notAfter:f}}var Hi={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},Bi={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 an(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Wi(i,t){let n=an(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function _n(i){let t=i.split(".").map(Number),n=[];n.push(40*t[0]+t[1]);for(let r=2;r<t.length;r++){let f=t[r],c=[];c.unshift(f&127),f>>=7;while(f>0)c.unshift(f&127|128),f>>=7;n.push(...c)}return Wi(Hi.OID,Buffer.from(n))}function V0(i){let t;if(typeof i==="bigint"){let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Wi(Hi.INTEGER,t)}function dw(i,t=0){return Wi(Hi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Dw(i){return Wi(Hi.OCTET_STRING,i)}function Xi(...i){return Wi(Hi.SEQUENCE,Buffer.concat(i))}function HT(...i){return Wi(Hi.SET,Buffer.concat(i))}function qT(i){return Wi(Hi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function gT(i){return Wi(Hi.UTF8_STRING,Buffer.from(i,"utf8"))}function LT(){return Buffer.from([Hi.NULL,0])}function gy(i,t,n=!0){let r=160|i|(n?0:0),f=an(t.length);return Buffer.concat([Buffer.from([r]),f,t])}function Ly(i){let t=i.getUTCFullYear();if(t>=2050){let n=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Wi(Hi.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(t%100).toString().padStart(2,"0"),r=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=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=`${n}${r}${f}${c}${l}${y}Z`;return Wi(Hi.UTC_TIME,Buffer.from(w,"ascii"))}}function sT(i,t){return Xi(Ly(i),Ly(t))}function sy(i){let t=[];for(let n of i){let r;switch(n.shortName){case"CN":r=Bi.COMMON_NAME;break;case"C":r=Bi.COUNTRY;break;case"L":r=Bi.LOCALITY;break;case"ST":r=Bi.STATE;break;case"O":r=Bi.ORGANIZATION;break;case"OU":r=Bi.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?qT(n.value):gT(n.value),c=Xi(_n(r),f);t.push(HT(c))}return Xi(...t)}function bw(i){return Xi(_n(i),LT())}function xT(i){return i.export({type:"spki",format:"der"})}function kT(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),c=f[0]?f[0].split(":"):[],l=f[1]?f[1].split(":"):[],y=8-c.length-l.length,w=Array.from({length:y},()=>"0");t=[...c,...w,...l].join(":")}let n=t.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let c=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(c,f*2)}return r}else{let t=i.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(t)}}function VT(i){let t=[];for(let n of i)if(n.type===2&&n.value){let r=an(n.value.length);t.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=kT(n.ip),f=an(r.length);t.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=an(n.value.length);t.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return Xi(...t)}function dT(i,t){if(i){if(t!==void 0)return Xi(Wi(1,Buffer.from([255])),V0(t));return Xi(Wi(1,Buffer.from([255])))}return Xi()}function DT(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 n=0,r=t;while(r>0&&(r&1)===0)n++,r>>=1;if(t===0)n=7;return dw(Buffer.from([t]),n)}function bT(i){let t=[];if(i.serverAuth)t.push(_n(Bi.SERVER_AUTH));if(i.clientAuth)t.push(_n(Bi.CLIENT_AUTH));return Xi(...t)}function Wn(i,t,n){let r=[_n(i)];if(t)r.push(Wi(1,Buffer.from([255])));return r.push(Dw(n)),Xi(...r)}function PT(i){let t=[];if(t.push(gy(0,V0(2))),t.push(V0(i.serialNumber)),t.push(bw(Bi.SHA256_WITH_RSA)),t.push(sy(i.issuer)),t.push(sT(i.notBefore,i.notAfter)),t.push(sy(i.subject)),t.push(xT(i.publicKey)),i.extensions){let n=[];if(i.extensions.basicConstraints)n.push(Wn(Bi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,dT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)n.push(Wn(Bi.KEY_USAGE,i.extensions.keyUsage.critical??!0,DT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)n.push(Wn(Bi.EXTENDED_KEY_USAGE,!1,bT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)n.push(Wn(Bi.SUBJECT_ALT_NAME,!1,VT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)n.push(Wn(Bi.SUBJECT_KEY_IDENTIFIER,!1,Dw(i.extensions.subjectKeyIdentifier)));if(n.length>0)t.push(gy(3,Xi(...n)))}return Xi(...t)}function ZT(i,t){let n=rn.createSign("SHA256");n.update(i);let r=n.sign(t);return Xi(i,bw(Bi.SHA256_WITH_RSA),dw(r))}function vT(i,t){let n=i.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${t}-----
66
66
  ${r.join(`
67
67
  `)}
68
68
  -----END ${t}-----
69
- `}function cc(){let i=rn.randomBytes(20);return i[0]=i[0]&127||1,i}function bw(i=2048){let{privateKey:t,publicKey:n}=rn.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:n}}function vT(i){let t=i.export({type:"spki",format:"der"});return rn.createHash("sha1").update(t).digest()}function Pw(i){let t={serialNumber:i.serialNumber||cc(),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:vT(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 n=bT(t),r=PT(n,i.signingKey);return{certificate:ZT(r,"CERTIFICATE"),certificateDer:r}}function Zw(i){return i.export({type:"pkcs8",format:"pem"})}function oT(i){return rn.createPrivateKey(i)}function pT(i){let t=new rn.X509Certificate(i),n=t.publicKey,r=[],f=t.subject.split(`
70
- `);for(let c of f){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)r.push({shortName:l.trim(),value:w.trim()})}return{publicKey:n,subject:r}}async function lc(i={}){N("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Gi.DEFAULT_KEY_SIZE;N("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:n,publicKey:r}=bw(t),f=[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:c,notAfter:l}=fc({validityYears:i.validityYears||Gi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:y}=Pw({serialNumber:cc(),notBefore:c,notAfter:l,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:y,privateKey:Zw(n),notBefore:c,notAfter:l}}async function yc(i){if(N("ca","Generating new certificate",i.verbose),N("ca",`Options: ${br(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}=pT(i.rootCA.certificate),n=oT(i.rootCA.privateKey);N("ca",`Generating ${Gi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let r=Gi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:c}=bw(r),l=i.commonName||xw(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}=fc({validityDays:i.validityDays||Gi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=kw(i),$=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=Pw({serialNumber:cc(),notBefore:w,notAfter:u,subject:y,issuer:t,publicKey:c,signingKey:n,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:A,subjectAltName:h});return{certificate:T,privateKey:Zw(f),notBefore:w,notAfter:u}}function vw(i,t){N(X.STORAGE,`Storing certificate and private key with options: ${br(t)}`,t?.verbose);let{certPath:n,keyPath:r}=rc({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});N(X.STORAGE,`Certificate path: ${n}`,t?.verbose),N(X.STORAGE,`Private key path: ${r}`,t?.verbose);let f=V0.dirname(n);if(!rt.existsSync(f))N(X.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),rt.mkdirSync(f,{recursive:!0});N(X.STORAGE,"Writing certificate file",t?.verbose),rt.writeFileSync(n,i.certificate);let c=V0.dirname(r);if(!rt.existsSync(c))N(X.STORAGE,`Creating private key directory: ${c}`,t?.verbose),rt.mkdirSync(c,{recursive:!0});return N(X.STORAGE,"Writing private key file",t?.verbose),rt.writeFileSync(r,i.privateKey),N(X.STORAGE,"Certificate and private key stored successfully",t?.verbose),n}function ow(i,t){N(X.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:n}=rc({basePath:t?.basePath,caCertPath:t?.caCertPath});N(X.STORAGE,`CA certificate path: ${n}`,t?.verbose);let r=V0.dirname(n);if(!rt.existsSync(r))N(X.STORAGE,`Creating CA certificate directory: ${r}`,t?.verbose),rt.mkdirSync(r,{recursive:!0});return N(X.STORAGE,"Writing CA certificate file",t?.verbose),rt.writeFileSync(n,i),N(X.STORAGE,"CA certificate stored successfully",t?.verbose),n}function Pr(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=sw(i);return new iE.X509Certificate(t)}function Zr(i){return Pr(i).fingerprint256.replace(/:/g,"").toUpperCase()}function wc(i){return pw(Pr(i).subject)}function uc(i,t,n=443,r=4000){let f;try{f=t.includes("-----BEGIN")?t:tE.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=nE.connect({host:i,port:n,servername:i,ca:f,rejectUnauthorized:!0},()=>{y(w.authorized),w.end()});w.setTimeout(r,()=>{w.destroy(),y(!1)}),w.on("error",()=>y(!1))})}function rE(i){let t=[],n=i.split(`
71
- `);for(let r of n){let[f,...c]=r.split("="),l=c.join("=");if(f&&l)t.push({shortName:f.trim(),value:l.trim()})}return t}function pw(i){return rE(i).find((t)=>t.shortName==="CN")?.value||""}function fE(i){let t=[],n=pw(i.subject);if(n&&!/^\d+\.\d+\.\d+\.\d+$/.test(n))t.push(n);let r=i.subjectAltName;if(r){let f=r.split(", ");for(let c of f)if(c.startsWith("DNS:"))t.push(c.slice(4))}return[...new Set(t)]}function hc(i,t){let n=Pr(i),r=fE(n);for(let f of r){if(f===t)return!0;if(f.startsWith("*.")){let c=f.slice(2);if(t.endsWith(c)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function lE(i,t){if(Lr.platform()!=="darwin")return!1;try{let n=Zr(i);if(!n)return N(X.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(cE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
72
- `).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return N(X.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return N(X.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return N(X.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var yE={platform:"darwin",async addCertificate(i,t){if(await lE(i,t?.verbose)){N(X.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),pt.success("Certificate is already trusted in system keychain");return}N(X.TRUST,"Adding certificate to macOS keychain",t?.verbose),await et(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await et(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(X.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw N(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},wE={platform:"win32",async addCertificate(i,t){N(X.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await et(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await et(`certutil -delstore -enterprise Root "${r}"`),N(X.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw N(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},uE={platform:"linux",async addCertificate(i,t){N(X.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=Lr.homedir(),r=Gi.LINUX_CERT_DB_FILENAME,f=Gi.LINUX_TRUST_ARGS;N(X.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let c=x0(n,r);if(c.length===0){pt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){N(X.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{N(X.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await et(`certutil -d sql:${l} -D -n ${v.commonName}`)}catch(y){N(X.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}N(X.TRUST,`Adding new certificate to ${l}`,t?.verbose),await et(`certutil -d sql:${l} -A -t ${f} -n ${v.commonName} -i ${i}`),pt.info(`Cert added to ${l}`)}},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=Lr.homedir(),c=Gi.LINUX_CERT_DB_FILENAME;N(X.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=x0(f,c);if(l.length===0){pt.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){N(X.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await et(`certutil -d sql:${y} -D -n "${r}"`),pt.info(`Cert removed from ${y}`)}catch(w){N(X.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},hE={darwin:yE,win32:wE,linux:uE};async function $c(i,t,n){N(X.TRUST,`Adding certificate to system trust store with options: ${br(n)}`,n?.verbose),N(X.TRUST,"Storing certificate and private key",n?.verbose);let r=vw(i,n);N(X.TRUST,"Storing CA certificate",n?.verbose);let f=ow(t,n),c=Lr.platform();N(X.TRUST,`Detected platform: ${c}`,n?.verbose);let l=hE[c];if(!l){let y=`Unsupported platform: ${c}`;throw N(X.TRUST,`Error: ${y}`,n?.verbose),Error(y)}return await l.addCertificate(f,n),N(X.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as pc}from"node:os";import{join as il,resolve as uR}from"node:path";import{existsSync as iu,statSync as tu}from"fs";import{existsSync as $E,mkdirSync as Rj,readdirSync as Xj,readFileSync as AE,writeFileSync as Wj}from"fs";import{homedir as fn}from"os";import{dirname as Jj,resolve as Ki}from"path";import Kf from"process";import{existsSync as nu,statSync as ru}from"fs";import{existsSync as Kc,mkdirSync as TE,readdirSync as EE,writeFileSync as YE}from"fs";import{homedir as cn}from"os";import{dirname as fu,resolve as Ci}from"path";import zt from"process";import{join as BE,relative as eE,resolve as cu}from"path";import Cf from"process";import{existsSync as Lu,mkdirSync as Hj,readdirSync as qj,writeFileSync as gj}from"fs";import{homedir as Ac}from"os";import{dirname as xj,resolve as ei}from"path";import Mn from"process";import{join as CE,relative as mE,resolve as lu}from"path";import mf from"process";import{existsSync as xu,mkdirSync as bj,readdirSync as Pj,writeFileSync as Zj}from"fs";import{dirname as oj,resolve as Uf}from"path";import _c from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as UE,createDecipheriv as jE,randomBytes as Tc}from"crypto";import{closeSync as Ec,createReadStream as yu,createWriteStream as NE,existsSync as Yc,fsyncSync as wu,openSync as uu,writeFileSync as RE}from"fs";import{access as XE,constants as hu,mkdir as WE,readdir as vr,rename as $u,stat as ln,unlink as or,writeFile as Bc}from"fs/promises";import{join as yn}from"path";import hi from"process";import{pipeline as SE}from"stream/promises";import{createGzip as Au}from"zlib";import wn from"process";import wt from"process";import{Buffer as ct}from"buffer";import{createCipheriv as aE,createDecipheriv as JE,randomBytes as ec}from"crypto";import{closeSync as Cc,createReadStream as Tu,createWriteStream as FE,existsSync as pr,fsyncSync as Eu,openSync as Yu,writeFileSync as IE}from"fs";import{access as KE,constants as Bu,mkdir as _E,readdir as tf,rename as eu,stat as un,unlink as nf,writeFile as mc}from"fs/promises";import{isAbsolute as zE,join as hn,resolve as QE}from"path";import K from"process";import{pipeline as ME}from"stream/promises";import{createGzip as Cu}from"zlib";import $n from"process";import ut from"process";import rf from"process";import{existsSync as ff}from"fs";import{resolve as Uc}from"path";import{existsSync as OE}from"fs";import{existsSync as GE,readdirSync as HE}from"fs";import{extname as jc,resolve as mu}from"path";import qE from"process";import{join as gE,relative as sE,resolve as Uu}from"path";import jf from"process";import{Buffer as lt}from"buffer";import{createCipheriv as LE,createDecipheriv as xE,randomBytes as Nc}from"crypto";import{closeSync as Rc,createReadStream as ju,createWriteStream as kE,existsSync as cf,fsyncSync as Nu,openSync as Ru,writeFileSync as VE}from"fs";import{access as dE,constants as Xu,mkdir as DE,readdir as lf,rename as Wu,stat as An,unlink as yf,writeFile as Xc}from"fs/promises";import{isAbsolute as bE,join as Tn,resolve as PE}from"path";import _ from"process";import{pipeline as ZE}from"stream/promises";import{createGzip as Su}from"zlib";import En from"process";import ht from"process";import uf from"process";import{existsSync as hf}from"fs";import{resolve as Ic}from"path";import{existsSync as BB}from"fs";class gu{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!iu(i))return!0;return tu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=iu(n)?tu(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class su{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var ef=new gu,xc=new su;var vE=Object.defineProperty,oE=(i)=>i;function pE(i,t){this[i]=oE.bind(null,t)}var iY=(i,t)=>{for(var n in t)vE(i,n,{get:t[n],enumerable:!0,configurable:!0,set:pE.bind(t,n)})},tY=(i,t)=>()=>(i&&(t=i(i=0)),t),ku={};iY(ku,{withErrorRecovery:()=>Du,tryLoadConfig:()=>XY,loadConfigWithResult:()=>NY,loadConfig:()=>ou,isRetryableError:()=>BY,isConfigNotFoundError:()=>YY,isBunfigError:()=>bu,globalPerformanceMonitor:()=>Hn,globalCache:()=>Yn,getEnvOrDefault:()=>eY,generateConfigTypes:()=>WY,defaultGeneratedDir:()=>lh,defaultConfigDir:()=>ch,deepMergeWithArrayStrategy:()=>bc,deepMerge:()=>Pu,createLibraryConfig:()=>SY,config:()=>RY,bunfigPlugin:()=>aY,applyEnvVarsToConfig:()=>Qn,TypeGenerationError:()=>qc,SchemaValidationError:()=>Gn,PluginError:()=>sc,PerformanceMonitor:()=>Vc,FileSystemError:()=>Hc,ErrorFactory:()=>jt,EnvVarError:()=>af,EnvProcessor:()=>_f,ConfigValidator:()=>Pc,ConfigValidationError:()=>Oc,ConfigNotFoundError:()=>Sf,ConfigMergeError:()=>Gc,ConfigLoader:()=>Zc,ConfigLoadError:()=>On,ConfigFileLoader:()=>zf,ConfigCache:()=>kc,CacheUtils:()=>ih,BunfigError:()=>Si,BrowserConfigError:()=>gc,ArrayMergeStrategies:()=>rh});class kc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!nu(i))return!0;return ru(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=nu(n)?ru(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Vc{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function nY(i,t={}){let r=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return r?`${i}:${r}`:i}function rY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function fY(i){return i.getStats().size*2}function dc(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 r=[...t];for(let f of i)if(d(f)&&"name"in f){if(!r.find((l)=>d(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(d(f)&&"path"in f){if(!r.find((l)=>d(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Nf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!d(t)||!d(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(d(f)&&d(n[r]))n[r]=dc(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&d(f[0])&&d(n[r][0])){let c=[...f];for(let l of n[r])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)=>Nf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function Nf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Nf(i[n],t[n]))return!1;return!0}if(d(i)&&d(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Nf(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function cY(i,t){if(!xu(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 dc(t,r)}catch{return null}}catch{return null}}async function lY({name:i="",cwd:t,defaultConfig:n}){let r=t||_c.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Uf(r,`${l}${y}`),u=await cY(w,n);if(u!==null)return u}try{let l=Uf(r,"package.json");if(xu(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return dc(n,w)}catch{}}}catch{}return n}function yY(i,t={}){let n=mf.cwd();while(n.includes("storage"))n=lu(n,"..");let r=lu(n,i||"");if(t?.relative)return mE(mf.cwd(),r);return r}async function wY(){try{let i=await lY({name:"clarity",defaultConfig:Tf,cwd:mf.cwd(),endpoint:"",headers:{}});return{...Tf,...i}}catch{return Tf}}function P(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uY(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof wt<"u"){let i=wt.type;if(i==="renderer"||i==="worker")return!1;return!!(wt.versions&&(wt.versions.node||wt.versions.bun))}return!1}class Vu{async format(i){let t=await uY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:wn.pid,hostname:t(),environment:wn.env.NODE_ENV||"development",platform:wn.platform,version:wn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wn.env.NODE_ENV||wn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Rf{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={...Qc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Vu,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??hi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Ef,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Ef};return{...Ef,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Qc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await XE(this.config.logDirectory,hu.F_OK|hu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await WE(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:Ut.from(i);try{if(!Yc(this.currentLogFile))await Bc(this.currentLogFile,"",{mode:420});if(f=uu(this.currentLogFile,"a",420),RE(f,w,{flag:"a"}),wu(f),f!==void 0)Ec(f),f=void 0;if((await ln(this.currentLogFile)).size===0){if(await Bc(this.currentLogFile,w,{flag:"w",mode:420}),(await ln(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(f!==void 0)try{Ec(f)}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(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yn(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 yn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yn(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 n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=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(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Tc(16).toString("hex")}generateKey(){return Tc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Tc(16),r=UE("aes-256-gcm",t,n),f=Ut.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Ut.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Au(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(Ut.from(Ut.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await ln(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await vr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await ln(n).catch(()=>null))try{if(await $u(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await or(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Bc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await ln(n).catch(()=>null))await $u(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await vr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await or(yn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=yu(i),r=NE(t),f=Au();await SE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Yc(this.currentLogFile))try{let i=uu(this.currentLogFile,"r+");wu(i),Ec(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 vr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await or(yn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=hi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${k.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!P()){let u=th[i],h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
69
+ `}function lc(){let i=rn.randomBytes(20);return i[0]=i[0]&127||1,i}function Pw(i=2048){let{privateKey:t,publicKey:n}=rn.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:n}}function oT(i){let t=i.export({type:"spki",format:"der"});return rn.createHash("sha1").update(t).digest()}function Zw(i){let t={serialNumber:i.serialNumber||lc(),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:oT(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 n=PT(t),r=ZT(n,i.signingKey);return{certificate:vT(r,"CERTIFICATE"),certificateDer:r}}function vw(i){return i.export({type:"pkcs8",format:"pem"})}function pT(i){return rn.createPrivateKey(i)}function iE(i){let t=new rn.X509Certificate(i),n=t.publicKey,r=[],f=t.subject.split(`
70
+ `);for(let c of f){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)r.push({shortName:l.trim(),value:w.trim()})}return{publicKey:n,subject:r}}async function yc(i={}){N("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Gi.DEFAULT_KEY_SIZE;N("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:n,publicKey:r}=Pw(t),f=[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:c,notAfter:l}=cc({validityYears:i.validityYears||Gi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:y}=Zw({serialNumber:lc(),notBefore:c,notAfter:l,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:y,privateKey:vw(n),notBefore:c,notAfter:l}}async function wc(i){if(N("ca","Generating new certificate",i.verbose),N("ca",`Options: ${Pr(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}=iE(i.rootCA.certificate),n=pT(i.rootCA.privateKey);N("ca",`Generating ${Gi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let r=Gi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:c}=Pw(r),l=i.commonName||kw(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}=cc({validityDays:i.validityDays||Gi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=Vw(i),$=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=Zw({serialNumber:lc(),notBefore:w,notAfter:u,subject:y,issuer:t,publicKey:c,signingKey:n,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:A,subjectAltName:h});return{certificate:T,privateKey:vw(f),notBefore:w,notAfter:u}}function ow(i,t){N(X.STORAGE,`Storing certificate and private key with options: ${Pr(t)}`,t?.verbose);let{certPath:n,keyPath:r}=fc({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});N(X.STORAGE,`Certificate path: ${n}`,t?.verbose),N(X.STORAGE,`Private key path: ${r}`,t?.verbose);let f=d0.dirname(n);if(!rt.existsSync(f))N(X.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),rt.mkdirSync(f,{recursive:!0});N(X.STORAGE,"Writing certificate file",t?.verbose),rt.writeFileSync(n,i.certificate);let c=d0.dirname(r);if(!rt.existsSync(c))N(X.STORAGE,`Creating private key directory: ${c}`,t?.verbose),rt.mkdirSync(c,{recursive:!0});return N(X.STORAGE,"Writing private key file",t?.verbose),rt.writeFileSync(r,i.privateKey),N(X.STORAGE,"Certificate and private key stored successfully",t?.verbose),n}function pw(i,t){N(X.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:n}=fc({basePath:t?.basePath,caCertPath:t?.caCertPath});N(X.STORAGE,`CA certificate path: ${n}`,t?.verbose);let r=d0.dirname(n);if(!rt.existsSync(r))N(X.STORAGE,`Creating CA certificate directory: ${r}`,t?.verbose),rt.mkdirSync(r,{recursive:!0});return N(X.STORAGE,"Writing CA certificate file",t?.verbose),rt.writeFileSync(n,i),N(X.STORAGE,"CA certificate stored successfully",t?.verbose),n}function Zr(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=sw(i);return new tE.X509Certificate(t)}function vr(i){return Zr(i).fingerprint256.replace(/:/g,"").toUpperCase()}function uc(i){return iu(Zr(i).subject)}function hc(i,t,n=443,r=4000){let f;try{f=t.includes("-----BEGIN")?t:nE.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=rE.connect({host:i,port:n,servername:i,ca:f,rejectUnauthorized:!0},()=>{y(w.authorized),w.end()});w.setTimeout(r,()=>{w.destroy(),y(!1)}),w.on("error",()=>y(!1))})}function fE(i){let t=[],n=i.split(`
71
+ `);for(let r of n){let[f,...c]=r.split("="),l=c.join("=");if(f&&l)t.push({shortName:f.trim(),value:l.trim()})}return t}function iu(i){return fE(i).find((t)=>t.shortName==="CN")?.value||""}function cE(i){let t=[],n=iu(i.subject);if(n&&!/^\d+\.\d+\.\d+\.\d+$/.test(n))t.push(n);let r=i.subjectAltName;if(r){let f=r.split(", ");for(let c of f)if(c.startsWith("DNS:"))t.push(c.slice(4))}return[...new Set(t)]}function $c(i,t){let n=Zr(i),r=cE(n);for(let f of r){if(f===t)return!0;if(f.startsWith("*.")){let c=f.slice(2);if(t.endsWith(c)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function yE(i,t){if(xr.platform()!=="darwin")return!1;try{let n=vr(i);if(!n)return N(X.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(lE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
72
+ `).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return N(X.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return N(X.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return N(X.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var wE={platform:"darwin",async addCertificate(i,t){if(await yE(i,t?.verbose)){N(X.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),pt.success("Certificate is already trusted in system keychain");return}N(X.TRUST,"Adding certificate to macOS keychain",t?.verbose),await et(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await et(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(X.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw N(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},uE={platform:"win32",async addCertificate(i,t){N(X.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await et(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await et(`certutil -delstore -enterprise Root "${r}"`),N(X.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw N(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},hE={platform:"linux",async addCertificate(i,t){N(X.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=xr.homedir(),r=Gi.LINUX_CERT_DB_FILENAME,f=Gi.LINUX_TRUST_ARGS;N(X.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let c=k0(n,r);if(c.length===0){pt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){N(X.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{N(X.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await et(`certutil -d sql:${l} -D -n ${v.commonName}`)}catch(y){N(X.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}N(X.TRUST,`Adding new certificate to ${l}`,t?.verbose),await et(`certutil -d sql:${l} -A -t ${f} -n ${v.commonName} -i ${i}`),pt.info(`Cert added to ${l}`)}},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=xr.homedir(),c=Gi.LINUX_CERT_DB_FILENAME;N(X.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=k0(f,c);if(l.length===0){pt.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){N(X.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await et(`certutil -d sql:${y} -D -n "${r}"`),pt.info(`Cert removed from ${y}`)}catch(w){N(X.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},$E={darwin:wE,win32:uE,linux:hE};async function Ac(i,t,n){N(X.TRUST,`Adding certificate to system trust store with options: ${Pr(n)}`,n?.verbose),N(X.TRUST,"Storing certificate and private key",n?.verbose);let r=ow(i,n);N(X.TRUST,"Storing CA certificate",n?.verbose);let f=pw(t,n),c=xr.platform();N(X.TRUST,`Detected platform: ${c}`,n?.verbose);let l=$E[c];if(!l){let y=`Unsupported platform: ${c}`;throw N(X.TRUST,`Error: ${y}`,n?.verbose),Error(y)}return await l.addCertificate(f,n),N(X.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as il}from"node:os";import{join as tl,resolve as hR}from"node:path";import{existsSync as tu,statSync as nu}from"fs";import{existsSync as AE,mkdirSync as Xj,readdirSync as Wj,readFileSync as TE,writeFileSync as Sj}from"fs";import{homedir as fn}from"os";import{dirname as Fj,resolve as Ki}from"path";import _f from"process";import{existsSync as ru,statSync as fu}from"fs";import{existsSync as _c,mkdirSync as EE,readdirSync as YE,writeFileSync as BE}from"fs";import{homedir as cn}from"os";import{dirname as cu,resolve as Ci}from"path";import zt from"process";import{join as eE,relative as CE,resolve as lu}from"path";import mf from"process";import{existsSync as xu,mkdirSync as qj,readdirSync as gj,writeFileSync as Lj}from"fs";import{homedir as Tc}from"os";import{dirname as kj,resolve as ei}from"path";import Mn from"process";import{join as mE,relative as UE,resolve as yu}from"path";import Uf from"process";import{existsSync as ku,mkdirSync as Pj,readdirSync as Zj,writeFileSync as vj}from"fs";import{dirname as pj,resolve as jf}from"path";import zc from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as jE,createDecipheriv as NE,randomBytes as Ec}from"crypto";import{closeSync as Yc,createReadStream as wu,createWriteStream as RE,existsSync as Bc,fsyncSync as uu,openSync as hu,writeFileSync as XE}from"fs";import{access as WE,constants as $u,mkdir as SE,readdir as or,rename as Au,stat as ln,unlink as pr,writeFile as ec}from"fs/promises";import{join as yn}from"path";import hi from"process";import{pipeline as aE}from"stream/promises";import{createGzip as Tu}from"zlib";import wn from"process";import wt from"process";import{Buffer as ct}from"buffer";import{createCipheriv as JE,createDecipheriv as FE,randomBytes as Cc}from"crypto";import{closeSync as mc,createReadStream as Eu,createWriteStream as IE,existsSync as tf,fsyncSync as Yu,openSync as Bu,writeFileSync as KE}from"fs";import{access as _E,constants as eu,mkdir as zE,readdir as nf,rename as Cu,stat as un,unlink as rf,writeFile as Uc}from"fs/promises";import{isAbsolute as QE,join as hn,resolve as ME}from"path";import K from"process";import{pipeline as OE}from"stream/promises";import{createGzip as mu}from"zlib";import $n from"process";import ut from"process";import ff from"process";import{existsSync as cf}from"fs";import{resolve as jc}from"path";import{existsSync as GE}from"fs";import{existsSync as HE,readdirSync as qE}from"fs";import{extname as Nc,resolve as Uu}from"path";import gE from"process";import{join as LE,relative as sE,resolve as ju}from"path";import Nf from"process";import{Buffer as lt}from"buffer";import{createCipheriv as xE,createDecipheriv as kE,randomBytes as Rc}from"crypto";import{closeSync as Xc,createReadStream as Nu,createWriteStream as VE,existsSync as lf,fsyncSync as Ru,openSync as Xu,writeFileSync as dE}from"fs";import{access as DE,constants as Wu,mkdir as bE,readdir as yf,rename as Su,stat as An,unlink as wf,writeFile as Wc}from"fs/promises";import{isAbsolute as PE,join as Tn,resolve as ZE}from"path";import _ from"process";import{pipeline as vE}from"stream/promises";import{createGzip as au}from"zlib";import En from"process";import ht from"process";import hf from"process";import{existsSync as $f}from"fs";import{resolve as Kc}from"path";import{existsSync as eB}from"fs";class Lu{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!tu(i))return!0;return nu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=tu(n)?nu(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class su{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var Cf=new Lu,kc=new su;var oE=Object.defineProperty,pE=(i)=>i;function iY(i,t){this[i]=pE.bind(null,t)}var tY=(i,t)=>{for(var n in t)oE(i,n,{get:t[n],enumerable:!0,configurable:!0,set:iY.bind(t,n)})},nY=(i,t)=>()=>(i&&(t=i(i=0)),t),Vu={};tY(Vu,{withErrorRecovery:()=>bu,tryLoadConfig:()=>WY,loadConfigWithResult:()=>RY,loadConfig:()=>pu,isRetryableError:()=>eY,isConfigNotFoundError:()=>BY,isBunfigError:()=>Pu,globalPerformanceMonitor:()=>Hn,globalCache:()=>Yn,getEnvOrDefault:()=>CY,generateConfigTypes:()=>SY,defaultGeneratedDir:()=>yh,defaultConfigDir:()=>lh,deepMergeWithArrayStrategy:()=>Pc,deepMerge:()=>Zu,createLibraryConfig:()=>aY,config:()=>XY,bunfigPlugin:()=>JY,applyEnvVarsToConfig:()=>Qn,TypeGenerationError:()=>gc,SchemaValidationError:()=>Gn,PluginError:()=>sc,PerformanceMonitor:()=>dc,FileSystemError:()=>qc,ErrorFactory:()=>jt,EnvVarError:()=>Jf,EnvProcessor:()=>zf,ConfigValidator:()=>Zc,ConfigValidationError:()=>Gc,ConfigNotFoundError:()=>af,ConfigMergeError:()=>Hc,ConfigLoader:()=>vc,ConfigLoadError:()=>On,ConfigFileLoader:()=>Qf,ConfigCache:()=>Vc,CacheUtils:()=>th,BunfigError:()=>Si,BrowserConfigError:()=>Lc,ArrayMergeStrategies:()=>fh});class Vc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ru(i))return!0;return fu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ru(n)?fu(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class dc{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function rY(i,t={}){let r=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return r?`${i}:${r}`:i}function fY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function cY(i){return i.getStats().size*2}function Dc(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 r=[...t];for(let f of i)if(d(f)&&"name"in f){if(!r.find((l)=>d(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(d(f)&&"path"in f){if(!r.find((l)=>d(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Rf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!d(t)||!d(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(d(f)&&d(n[r]))n[r]=Dc(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&d(f[0])&&d(n[r][0])){let c=[...f];for(let l of n[r])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)=>Rf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function Rf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Rf(i[n],t[n]))return!1;return!0}if(d(i)&&d(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Rf(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function lY(i,t){if(!ku(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 Dc(t,r)}catch{return null}}catch{return null}}async function yY({name:i="",cwd:t,defaultConfig:n}){let r=t||zc.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=jf(r,`${l}${y}`),u=await lY(w,n);if(u!==null)return u}try{let l=jf(r,"package.json");if(ku(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Dc(n,w)}catch{}}}catch{}return n}function wY(i,t={}){let n=Uf.cwd();while(n.includes("storage"))n=yu(n,"..");let r=yu(n,i||"");if(t?.relative)return UE(Uf.cwd(),r);return r}async function uY(){try{let i=await yY({name:"clarity",defaultConfig:Ef,cwd:Uf.cwd(),endpoint:"",headers:{}});return{...Ef,...i}}catch{return Ef}}function P(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hY(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof wt<"u"){let i=wt.type;if(i==="renderer"||i==="worker")return!1;return!!(wt.versions&&(wt.versions.node||wt.versions.bun))}return!1}class du{async format(i){let t=await hY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:wn.pid,hostname:t(),environment:wn.env.NODE_ENV||"development",platform:wn.platform,version:wn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wn.env.NODE_ENV||wn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xf{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={...Mc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new du,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??hi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Yf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Yf};return{...Yf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Mc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await WE(this.config.logDirectory,$u.F_OK|$u.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await SE(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:Ut.from(i);try{if(!Bc(this.currentLogFile))await ec(this.currentLogFile,"",{mode:420});if(f=hu(this.currentLogFile,"a",420),XE(f,w,{flag:"a"}),uu(f),f!==void 0)Yc(f),f=void 0;if((await ln(this.currentLogFile)).size===0){if(await ec(this.currentLogFile,w,{flag:"w",mode:420}),(await ln(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(f!==void 0)try{Yc(f)}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(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yn(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 yn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yn(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 n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=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(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Ec(16).toString("hex")}generateKey(){return Ec(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Ec(16),r=jE("aes-256-gcm",t,n),f=Ut.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Ut.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Tu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(Ut.from(Ut.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await ln(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await or(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await ln(n).catch(()=>null))try{if(await Au(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await pr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await ec(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await ln(n).catch(()=>null))await Au(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await or(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await pr(yn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=wu(i),r=RE(t),f=Tu();await aE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Bc(this.currentLogFile))try{let i=hu(this.currentLogFile,"r+");uu(i),Yc(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 or(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await pr(yn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=hi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${k.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!P()){let u=nh[i],h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
73
73
  `);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:k.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
74
  `;if(y)w+=`${y}
75
75
  `;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!P()){let n=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:k.blue("◐"),tag:n,message:`${k.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
76
- `,u=u.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:k.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Rf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Yc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Ut.isBuffer(i)?i:Ut.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=jE("aes-256-gcm",n,f);return y.setAuthTag(c),Ut.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!P()){let c=i.split(`
76
+ `,u=u.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:k.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Xf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Bc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Ut.isBuffer(i)?i:Ut.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=NE("aes-256-gcm",n,f);return y.setAuthTag(c),Ut.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!P()){let c=i.split(`
77
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:n,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
78
78
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${k.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();hi.stdin.removeListener("data",n);try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!1)}catch{}hi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!0)}catch{}hi.stdin.resume(),hi.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(n=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)n+=` ${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?k.gray(this.formatTag(this.name)):"",y=k.blue("◐");console.error(`${y} ${l} ${k.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
79
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 n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,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;hi.stdout.write(`${"\r".padEnd(hi.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()||!hi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=k.green("━".repeat(r)),l=k.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?k.green("✓"):k.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=hi.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,hi.stdout.write(i.lastRenderedLine),t)hi.stdout.write(`
80
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!hi.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 vr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=yn(this.config.logDirectory,r);if(i.before)try{if((await ln(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await or(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Af(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 r=[...t];for(let f of i)if(L(f)&&"name"in f){if(!r.find((l)=>L(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(L(f)&&"path"in f){if(!r.find((l)=>L(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Xf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!L(t)||!L(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(L(f)&&L(n[r]))n[r]=Af(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&L(f[0])&&L(n[r][0])){let c=[...f];for(let l of n[r])if(L(l)&&"name"in l){if(!c.find((w)=>L(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(L(l)&&"path"in l){if(!c.find((w)=>L(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Xf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function Dc(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:Af(i,t);if(Array.isArray(i))return n==="replace"?t:Af(i,t);if(!L(t)||!L(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=Af(l,c);else if(L(c)&&L(l))r[f]=Dc(l,c,n);else r[f]=c}return r}function Xf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Xf(i[n],t[n]))return!1;return!0}if(L(i)&&L(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Xf(i[f],t[f]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function wf(i,t,n="replace"){if(!Lu(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Dc(t,f,n)}catch{return null}}catch{return null}}function hY(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...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=`${r}_${$.map(A).join("_")}`,e=`${r}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(n)Ai.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=Mn.env[T]||Mn.env[e];if(E!==void 0){if(n)Ai.info(`Using environment variable ${E?T:e} 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((C)=>C.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function $Y({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?hY(i,f,c):f,u=n||Mn.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)Ai.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}`]:[],e=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,ei(u,"config"),ei(u,".config"),r?ei(u,r):void 0].filter(Boolean)));for(let B of E){if(c)Ai.info(`Searching for configuration in: ${B}`);let U=[ei(u,"config"),ei(u,".config")].concat(r?[ei(u,r)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let W of U)for(let S of h){let R=ei(B,`${W}${S}`),a=await wf(R,w,y);if(a!==null){if(c)Ai.success(`Configuration loaded from: ${R}`);return a}}}if(i){let B=ei(Ac(),".config",i),C=["config",`${i}.config`];if(t)C.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${B}`);for(let U of C)for(let W of h){let S=ei(B,`${U}${W}`),R=await wf(S,w,y);if(R!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${S}`);return R}}}if(i){let B=ei(Ac(),".config"),C=[`.${i}.config`];if(t)C.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=ei(B,`${U}${W}`),R=await wf(S,w,y);if(R!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${S}`);return R}}}if(i){let B=Ac(),C=[`.${i}.config`,`.${i}`];if(t)C.push(`.${t}.config`),C.push(`.${t}`);if(c)Ai.info(`Checking user home directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=ei(B,`${U}${W}`),R=await wf(S,w,y);if(R!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${S}`);return R}}}try{let B=ei(u,"package.json");if(Lu(B)){let C=await import(B),U=C[i];if(!U&&t){if(U=C[t],U&&c)Ai.success(`Using alias "${t}" configuration from package.json`)}if(U&&typeof U==="object"&&!Array.isArray(U))try{if(c)Ai.success(`Configuration loaded from package.json: ${U===C[i]?i:t}`);return Dc(w,U,y)}catch(W){if(c)Ai.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)Ai.warn("Failed to load package.json:",B)}if(c)Ai.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function AY(i,t={}){let n=Cf.cwd();while(n.includes("storage"))n=cu(n,"..");let r=cu(n,i||"");if(t?.relative)return eE(Cf.cwd(),r);return r}async function TY(){try{let i=await $Y({name:"clarity",alias:"logging",defaultConfig:Yf,cwd:Cf.cwd()});return{...Yf,...i||{}}}catch{return Yf}}function ni(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EY(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let i=ut.type;if(i==="renderer"||i==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class du{async format(i){let t=await EY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$n.pid,hostname:t(),environment:$n.env.NODE_ENV||"development",platform:$n.platform,version:$n.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$n.env.NODE_ENV||$n.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Wf{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={...Mc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new du,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??K.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Bf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Bf};return{...Bf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Mc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await KE(this.config.logDirectory,Bu.F_OK|Bu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await _E(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:ct.from(i);try{if(!pr(this.currentLogFile))await mc(this.currentLogFile,"",{mode:420});if(f=Yu(this.currentLogFile,"a",420),IE(f,w,{flag:"a"}),Eu(f),f!==void 0)Cc(f),f=void 0;if((await un(this.currentLogFile)).size===0){if(await mc(this.currentLogFile,w,{flag:"w",mode:420}),(await un(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(f!==void 0)try{Cc(f)}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(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return hn(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 hn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return hn(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 n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=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(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return ec(16).toString("hex")}generateKey(){return ec(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=ec(16),r=aE("aes-256-gcm",t,n),f=ct.isBuffer(i)?i:ct.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=ct.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Cu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(ct.from(ct.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await un(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await tf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await un(n).catch(()=>null))try{if(await eu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await nf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await mc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await un(n).catch(()=>null))await eu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await tf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await nf(hn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=Tu(i),r=FE(t),f=Cu();await ME(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),pr(this.currentLogFile))try{let i=Yu(this.currentLogFile,"r+");Eu(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(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await tf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await nf(hn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?Q.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof K.env.NO_COLOR<"u",t=K.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof K.stderr<"u"&&K.stderr.isTTY||typeof K.stdout<"u"&&K.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=K.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${Q.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=Q.underline(Q.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>Q.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Q.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Q.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Q.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>Q.strikethrough(r)),t}supportsHyperlinks(){if(ni())return!1;let i=K.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 n=K.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(zE(t)||t.startsWith("./")||t.startsWith("../"))t=QE(t);else return null;return pr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":nh[i],A=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
80
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!hi.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 or(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=yn(this.config.logDirectory,r);if(i.before)try{if((await ln(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await pr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Tf(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 r=[...t];for(let f of i)if(s(f)&&"name"in f){if(!r.find((l)=>s(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(s(f)&&"path"in f){if(!r.find((l)=>s(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Wf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!s(t)||!s(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(s(f)&&s(n[r]))n[r]=Tf(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&s(f[0])&&s(n[r][0])){let c=[...f];for(let l of n[r])if(s(l)&&"name"in l){if(!c.find((w)=>s(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(s(l)&&"path"in l){if(!c.find((w)=>s(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Wf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function bc(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:Tf(i,t);if(Array.isArray(i))return n==="replace"?t:Tf(i,t);if(!s(t)||!s(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=Tf(l,c);else if(s(c)&&s(l))r[f]=bc(l,c,n);else r[f]=c}return r}function Wf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Wf(i[n],t[n]))return!1;return!0}if(s(i)&&s(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Wf(i[f],t[f]))return!1}return!0}return!1}function s(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function uf(i,t,n="replace"){if(!xu(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return bc(t,f,n)}catch{return null}}catch{return null}}function $Y(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...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=`${r}_${$.map(A).join("_")}`,e=`${r}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(n)Ai.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=Mn.env[T]||Mn.env[e];if(E!==void 0){if(n)Ai.info(`Using environment variable ${E?T:e} 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((C)=>C.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function AY({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?$Y(i,f,c):f,u=n||Mn.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)Ai.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}`]:[],e=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,ei(u,"config"),ei(u,".config"),r?ei(u,r):void 0].filter(Boolean)));for(let B of E){if(c)Ai.info(`Searching for configuration in: ${B}`);let U=[ei(u,"config"),ei(u,".config")].concat(r?[ei(u,r)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let W of U)for(let S of h){let R=ei(B,`${W}${S}`),a=await uf(R,w,y);if(a!==null){if(c)Ai.success(`Configuration loaded from: ${R}`);return a}}}if(i){let B=ei(Tc(),".config",i),C=["config",`${i}.config`];if(t)C.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${B}`);for(let U of C)for(let W of h){let S=ei(B,`${U}${W}`),R=await uf(S,w,y);if(R!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${S}`);return R}}}if(i){let B=ei(Tc(),".config"),C=[`.${i}.config`];if(t)C.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=ei(B,`${U}${W}`),R=await uf(S,w,y);if(R!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${S}`);return R}}}if(i){let B=Tc(),C=[`.${i}.config`,`.${i}`];if(t)C.push(`.${t}.config`),C.push(`.${t}`);if(c)Ai.info(`Checking user home directory for dotfile configs: ${B}`);for(let U of C)for(let W of h){let S=ei(B,`${U}${W}`),R=await uf(S,w,y);if(R!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${S}`);return R}}}try{let B=ei(u,"package.json");if(xu(B)){let C=await import(B),U=C[i];if(!U&&t){if(U=C[t],U&&c)Ai.success(`Using alias "${t}" configuration from package.json`)}if(U&&typeof U==="object"&&!Array.isArray(U))try{if(c)Ai.success(`Configuration loaded from package.json: ${U===C[i]?i:t}`);return bc(w,U,y)}catch(W){if(c)Ai.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)Ai.warn("Failed to load package.json:",B)}if(c)Ai.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function TY(i,t={}){let n=mf.cwd();while(n.includes("storage"))n=lu(n,"..");let r=lu(n,i||"");if(t?.relative)return CE(mf.cwd(),r);return r}async function EY(){try{let i=await AY({name:"clarity",alias:"logging",defaultConfig:Bf,cwd:mf.cwd()});return{...Bf,...i||{}}}catch{return Bf}}function ni(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YY(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let i=ut.type;if(i==="renderer"||i==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class Du{async format(i){let t=await YY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$n.pid,hostname:t(),environment:$n.env.NODE_ENV||"development",platform:$n.platform,version:$n.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$n.env.NODE_ENV||$n.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Sf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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={...Oc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Du,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??K.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...ef,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...ef};return{...ef,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Oc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await _E(this.config.logDirectory,eu.F_OK|eu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await zE(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:ct.from(i);try{if(!tf(this.currentLogFile))await Uc(this.currentLogFile,"",{mode:420});if(f=Bu(this.currentLogFile,"a",420),KE(f,w,{flag:"a"}),Yu(f),f!==void 0)mc(f),f=void 0;if((await un(this.currentLogFile)).size===0){if(await Uc(this.currentLogFile,w,{flag:"w",mode:420}),(await un(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(f!==void 0)try{mc(f)}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(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return hn(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 hn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return hn(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 n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=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(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Cc(16).toString("hex")}generateKey(){return Cc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Cc(16),r=JE("aes-256-gcm",t,n),f=ct.isBuffer(i)?i:ct.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=ct.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=mu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(ct.from(ct.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await un(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await nf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await un(n).catch(()=>null))try{if(await Cu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await rf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Uc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await un(n).catch(()=>null))await Cu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await nf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await rf(hn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=Eu(i),r=IE(t),f=mu();await OE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),tf(this.currentLogFile))try{let i=Bu(this.currentLogFile,"r+");Yu(i),mc(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 nf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await rf(hn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?Q.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof K.env.NO_COLOR<"u",t=K.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof K.stderr<"u"&&K.stderr.isTTY||typeof K.stdout<"u"&&K.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=K.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${Q.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=Q.underline(Q.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>Q.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Q.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Q.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Q.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>Q.strikethrough(r)),t}supportsHyperlinks(){if(ni())return!1;let i=K.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 n=K.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(QE(t)||t.startsWith("./")||t.startsWith("../"))t=ME(t);else return null;return tf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":rh[i],A=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
81
81
  `);for(let E of e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:Q.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){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
82
  `;if(y)h+=`${y}
83
83
  `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&K.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()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ni()&&K.stdout.isTTY)K.stdout.write(`
84
84
  `);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Q.blue("◐"),tag:n,message:`${Q.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
85
- `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Wf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!pr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=ct.isBuffer(i)?i:ct.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=JE("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=ct.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
85
+ `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Sf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!tf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Eu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=ct.isBuffer(i)?i:ct.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=FE("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=ct.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
86
86
  `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:Q.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Q.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:Q.cyan(h),showTimestamp:!1}))}else if(!ni())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
87
87
  `.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(`${Q.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();K.stdin.removeListener("data",n);try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!1)}catch{}K.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!0)}catch{}K.stdin.resume(),K.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(n=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)n+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${u}${w} ${Q.cyan(r)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
88
88
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!K.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=Q.green("━".repeat(r)),l=Q.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?Q.green("✓"):Q.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=K.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,K.stdout.write(i.lastRenderedLine),t)K.stdout.write(`
89
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!K.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 tf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=hn(this.config.logDirectory,r);if(i.before)try{if((await un(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await nf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Du(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function bu(i){return i instanceof Si}function YY(i){return i instanceof Sf}function BY(i){if(bu(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>i.message.toLowerCase().includes(n.toLowerCase()))}class _f{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Hn.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=rf.env[w]||(u?rf.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=rf.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof af)throw $;throw jt.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw jt.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(rf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
89
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!K.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 nf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=hn(this.config.logDirectory,r);if(i.before)try{if((await un(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await rf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function bu(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Pu(i){return i instanceof Si}function BY(i){return i instanceof af}function eY(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((n)=>i.message.toLowerCase().includes(n.toLowerCase()))}class zf{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Hn.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=ff.env[w]||(u?ff.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=ff.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof Jf)throw $;throw jt.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw jt.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(ff.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
90
90
 
91
91
  `;for(let r of i)n+=`${r.key}
92
92
  `,n+=` Type: ${r.type}
@@ -98,25 +98,25 @@ ${r.join(`
98
98
  `;n+=`| Variable | Type | Description | Example |
99
99
  `,n+=`|----------|------|-------------|----------|
100
100
  `;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
101
- `;return n}}function eY(i,t){let n=pu("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Pu(i,t,n={}){return Zu(i,t,n,new WeakMap)}function Zu(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 vu(i,t,f,r);if(!_i(t)||!_i(i))return t;return jY(i,t,n,r)}function vu(i,t,n,r){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(n){case"replace":return t;case"concat":return CY(i,t);case"smart":return mY(i,t,r);default:return t}return t}function CY(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>zc(f,r)))n.push(r);return n}function mY(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return UY(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function UY(i,t,n){let r=[...t];for(let f of i){if(!_i(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>_i(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function jY(i,t,n,r){let f=t;if(_i(f)&&r.has(f))return r.get(f);let c={...i};if(_i(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(_i(y)&&_i(w))c[l]=Zu(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=vu(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function bc(i,t,n="replace"){return Pu(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function zc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zc(i[n],t[n]))return!1;return!0}if(_i(i)&&_i(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zc(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class zf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=Yn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!ff(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 On(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new On(i,Error("Configuration must export a valid object"),"unknown");let B={config:bc(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Yn.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?jt.configLoad(i,u):jt.configLoad(i,Error(String(u)))}};if(l)return Hn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(Uc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return Du(async()=>{return ff(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!ff(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=Uc(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Uc(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!ff(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Pc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 Hn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!OE(t))throw new Gn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Gn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:fh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Zc{fileLoader=new zf;envProcessor=new _f;validator=new Pc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)gi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw gi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||zt.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ci($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw jt.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Qn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)gi.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)gi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Qn(i,n,f):n,y=[Ci(cn(),".config",i),Ci(cn(),".config"),cn()];for(let w of y){if(f)gi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Qn(i,r,c):r;try{let w=Ci(n,"package.json");if(!Kc(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)gi.success(`Configuration loaded from package.json: ${$}`);return{config:bc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)gi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Qn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw jt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Yn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Yn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ci(i,"config"),Ci(i,".config"),t?Ci(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ci(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ci(cn(),".config",i),Ci(cn(),".config"),cn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function au(i){let n=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return n||r}async function NY(i){return $t.loadConfig({...i,__strictErrorHandling:!0})}async function ou(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await $t.loadConfig(i);else r=await $t.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)gi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let y=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await $t.applyEnvironmentVariables(y.name||"",t,!0,y.verbose||!1))?.config??t;return t}}async function RY(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await $t.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&au(n)))return(await $t.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await $t.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"&&au(t)))return(await $t.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function XY(i,t,n="replace"){let r=new zf;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Qn(i,t,n=!1){let r=new _f,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=zt.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 WY(i){let t=Ci(zt.cwd(),i.configDir),n=Ci(zt.cwd(),i.generatedDir),r=Ci(n,"config-types.ts");if(!Kc(fu(r)))TE(fu(r),{recursive:!0,mode:511});let f=Kc(t)?EE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${iB}
101
+ `;return n}}function CY(i,t){let n=ih("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Zu(i,t,n={}){return vu(i,t,n,new WeakMap)}function vu(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 ou(i,t,f,r);if(!_i(t)||!_i(i))return t;return NY(i,t,n,r)}function ou(i,t,n,r){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(n){case"replace":return t;case"concat":return mY(i,t);case"smart":return UY(i,t,r);default:return t}return t}function mY(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Qc(f,r)))n.push(r);return n}function UY(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return jY(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function jY(i,t,n){let r=[...t];for(let f of i){if(!_i(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>_i(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function NY(i,t,n,r){let f=t;if(_i(f)&&r.has(f))return r.get(f);let c={...i};if(_i(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(_i(y)&&_i(w))c[l]=vu(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=ou(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Pc(i,t,n="replace"){return Zu(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Qc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Qc(i[n],t[n]))return!1;return!0}if(_i(i)&&_i(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Qc(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Qf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=Yn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!cf(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 On(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new On(i,Error("Configuration must export a valid object"),"unknown");let B={config:Pc(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Yn.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?jt.configLoad(i,u):jt.configLoad(i,Error(String(u)))}};if(l)return Hn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(jc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return bu(async()=>{return cf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!cf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=jc(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=jc(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!cf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Zc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 Hn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!GE(t))throw new Gn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Gn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:ch},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class vc{fileLoader=new Qf;envProcessor=new zf;validator=new Zc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)gi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw gi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||zt.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ci($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw jt.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Qn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)gi.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)gi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Qn(i,n,f):n,y=[Ci(cn(),".config",i),Ci(cn(),".config"),cn()];for(let w of y){if(f)gi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Qn(i,r,c):r;try{let w=Ci(n,"package.json");if(!_c(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)gi.success(`Configuration loaded from package.json: ${$}`);return{config:Pc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)gi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Qn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw jt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Yn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Yn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ci(i,"config"),Ci(i,".config"),t?Ci(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ci(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ci(cn(),".config",i),Ci(cn(),".config"),cn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Ju(i){let n=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return n||r}async function RY(i){return $t.loadConfig({...i,__strictErrorHandling:!0})}async function pu(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await $t.loadConfig(i);else r=await $t.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)gi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let y=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await $t.applyEnvironmentVariables(y.name||"",t,!0,y.verbose||!1))?.config??t;return t}}async function XY(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await $t.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Ju(n)))return(await $t.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await $t.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"&&Ju(t)))return(await $t.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function WY(i,t,n="replace"){let r=new Qf;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Qn(i,t,n=!1){let r=new zf,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=zt.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 SY(i){let t=Ci(zt.cwd(),i.configDir),n=Ci(zt.cwd(),i.generatedDir),r=Ci(n,"config-types.ts");if(!_c(cu(r)))EE(cu(r),{recursive:!0,mode:511});let f=_c(t)?YE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${tB}
102
102
  export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
103
- `;YE(r,c,{mode:438})}function SY(i){let t=null,n=null,r=()=>{if(!n)n=ou(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)gi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return r(),y},has(c,l){return l in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||f,l)},set(c,l,y){if(!t)t={...f};return t[l]=y,!0}})}function aY(i){let t=mu(qE.cwd(),i?.configDir||"./config");function n(){if(!GE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=HE(t).filter((w)=>f.has(jc(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=jc(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=jc($).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 r(){let f=n(),c=f.map((u)=>u.base),l=c.length?c.map((u)=>`'${u}'`).join(" | "):"string",y=f.length?`{
104
- ${f.map((u)=>{let h=mu(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
103
+ `;BE(r,c,{mode:438})}function aY(i){let t=null,n=null,r=()=>{if(!n)n=pu(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)gi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return r(),y},has(c,l){return l in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||f,l)},set(c,l,y){if(!t)t={...f};return t[l]=y,!0}})}function JY(i){let t=Uu(gE.cwd(),i?.configDir||"./config");function n(){if(!HE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=qE(t).filter((w)=>f.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 r(){let f=n(),c=f.map((u)=>u.base),l=c.length?c.map((u)=>`'${u}'`).join(" | "):"string",y=f.length?`{
104
+ ${f.map((u)=>{let h=Uu(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
105
105
  `)}
106
106
  }`:"Record<string, any>";return`export type ConfigNames = ${l}
107
107
  export type ConfigByName = ${y}
108
108
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
109
109
  export type ConfigOf = Config
110
- `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var pu,Yn,Hn,ih,JY,FY,Ju,Tf,Qc,$i,k,IY,Fu,KY,Iu,_Y,zY,Wc,QY,Ku,_u,Sc,MY,OY,GY,HY,Ef,th,qY,Ai,gY,sY,zu,Yf,Mc,ri,Q,LY,Qu,xY,Mu,kY,VY,ac,dY,Ou,Gu,DY,Jc,bY,PY,ZY,vY,oY,Bf,nh,pY,iB="0.15.6",Si,Sf,On,Oc,Gc,af,Hc,qc,Gn,gc,sc,jt,rh,fh,gi,$t,ch,lh,tB=tY(async()=>{pu=import.meta.require,Yn=new kc,Hn=new Vc,ih={createKey:nY,isEquivalent:rY,estimateMemoryUsage:fY},JY=Uf(_c.cwd(),"config"),FY=Uf(_c.cwd(),"src/generated"),Ju=mf.env.CLARITY_LOG_DIR||CE(yY(),"logs"),Tf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ju,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Qc=await wY(),$i={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=$i,IY=$i.red,Fu=$i.green,KY=$i.yellow,Iu=$i.blue,_Y=$i.magenta,zY=$i.cyan,Wc=$i.white,QY=$i.gray,Ku=$i.bgRed,_u=$i.bgYellow,Sc=$i.bold,MY=$i.dim,OY=$i.italic,GY=$i.underline,HY=$i.reset,Ef={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},th={debug:"\uD83D\uDD0D",info:Iu("ℹ"),success:Fu("✓"),warning:_u(Wc(Sc(" WARN "))),error:Ku(Wc(Sc(" ERROR ")))},qY=new Rf("stacks"),Ai=new Rf("bunfig",{showTags:!0}),gY=ei(Mn.cwd(),"config"),sY=ei(Mn.cwd(),"src/generated"),zu=Cf.env.CLARITY_LOG_DIR||BE(AY(),"logs"),Yf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Mc=await TY(),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"},Q=ri,LY=ri.red,Qu=ri.green,xY=ri.yellow,Mu=ri.blue,kY=ri.magenta,VY=ri.cyan,ac=ri.white,dY=ri.gray,Ou=ri.bgRed,Gu=ri.bgYellow,DY=ri.bgGray,Jc=ri.bold,bY=ri.dim,PY=ri.italic,ZY=ri.underline,vY=ri.strikethrough,oY=ri.reset,Bf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nh={debug:"\uD83D\uDD0D",info:Mu("ℹ"),success:Qu("✓"),warning:Gu(ac(Jc(" WARN "))),error:Ou(ac(Jc(" ERROR ")))},pY=new Wf("stacks"),Si=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Sf=class extends Si{code="CONFIG_NOT_FOUND";constructor(t,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},On=class extends Si{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Oc=class extends Si{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Gc=class extends Si{code="CONFIG_MERGE_ERROR";constructor(t,n,r,f){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},af=class extends Si{code="ENV_VAR_ERROR";constructor(t,n,r,f){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:f})}},Hc=class extends Si{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qc=class extends Si{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Gn=class extends Si{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},gc=class extends Si{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,f){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:f})}},sc=class extends Si{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},jt={configNotFound(i,t,n){return new Sf(i,t,n)},configLoad(i,t,n){return new On(i,t,n)},configValidation(i,t,n){return new Oc(i,t,n)},configMerge(i,t,n,r){return new Gc(i,t,n,r)},envVar(i,t,n,r){return new af(i,t,n,r)},fileSystem(i,t,n){return new Hc(i,t,n)},typeGeneration(i,t,n){return new qc(i,t,n)},schemaValidation(i,t,n){return new Gn(i,t,n)},browserConfig(i,t,n,r){return new gc(i,t,n,r)},plugin(i,t,n){return new sc(i,t,n)}},rh={replace:"replace",concat:"concat",smart:"smart"},fh=/^https?:\/\//,gi=new Wf("bunfig",{showTags:!0}),$t=new Zc,ch=Ci(zt.cwd(),"config"),lh=Ci(zt.cwd(),"src/generated")});function nB(i,t={}){let n=jf.cwd();while(n.includes("storage"))n=Uu(n,"..");let r=Uu(n,i||"");if(t?.relative)return sE(jf.cwd(),r);return r}var rB=jf.env.CLARITY_LOG_DIR||gE(nB(),"logs"),yh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jf={...yh},qN=(async()=>{try{let{loadConfig:i}=await tB().then(()=>ku),t=await i({name:"clarity",alias:"logging",defaultConfig:yh,cwd:jf.cwd()});if(t)Object.assign(Jf,t)}catch{}return Jf})();function fi(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fB(){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 wh{async format(i){let t=await fB(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:En.pid,hostname:t(),environment:En.env.NODE_ENV||"development",platform:En.platform,version:En.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:En.env.NODE_ENV||En.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=li,gN=li.red,cB=li.green,sN=li.yellow,lB=li.blue,LN=li.magenta,xN=li.cyan,Hu=li.white,kN=li.gray,yB=li.bgRed,wB=li.bgYellow,VN=li.bgGray,qu=li.bold,dN=li.dim,DN=li.italic,bN=li.underline,PN=li.strikethrough,ZN=li.reset,Fc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uB={debug:"\uD83D\uDD0D",info:lB("ℹ"),success:cB("✓"),warning:wB(Hu(qu(" WARN "))),error:yB(Hu(qu(" ERROR ")))};class Qf{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={...Jf},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Fc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Fc};return{...Fc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Jf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await dE(this.config.logDirectory,Xu.F_OK|Xu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await DE(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:lt.from(i);try{if(!cf(this.currentLogFile))await Xc(this.currentLogFile,"",{mode:420});if(f=Ru(this.currentLogFile,"a",420),VE(f,w,{flag:"a"}),Nu(f),f!==void 0)Rc(f),f=void 0;if((await An(this.currentLogFile)).size===0){if(await Xc(this.currentLogFile,w,{flag:"w",mode:420}),(await An(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(f!==void 0)try{Rc(f)}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(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Tn(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 Tn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Tn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())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 n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=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(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Nc(16).toString("hex")}generateKey(){return Nc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Nc(16),r=LE("aes-256-gcm",t,n),f=lt.isBuffer(i)?i:lt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=lt.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Su(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(lt.from(lt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await An(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await lf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await An(n).catch(()=>null))try{if(await Wu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await yf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Xc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await An(n).catch(()=>null))await Wu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await lf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await yf(Tn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=ju(i),r=kE(t),f=Su();await ZE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),cf(this.currentLogFile))try{let i=Ru(this.currentLogFile,"r+");Nu(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(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await lf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await yf(Tn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=_.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${O.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=O.underline(O.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>O.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>O.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>O.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>O.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>O.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=_.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(bE(t)||t.startsWith("./")||t.startsWith("../"))t=PE(t);else return null;return cf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":uB[i],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
110
+ `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var ih,Yn,Hn,th,FY,IY,Fu,Ef,Mc,$i,k,KY,Iu,_Y,Ku,zY,QY,Sc,MY,_u,zu,ac,OY,GY,HY,qY,Yf,nh,gY,Ai,LY,sY,Qu,Bf,Oc,ri,Q,xY,Mu,kY,Ou,VY,dY,Jc,DY,Gu,Hu,bY,Fc,PY,ZY,vY,oY,pY,ef,rh,iB,tB="0.15.6",Si,af,On,Gc,Hc,Jf,qc,gc,Gn,Lc,sc,jt,fh,ch,gi,$t,lh,yh,nB=nY(async()=>{ih=import.meta.require,Yn=new Vc,Hn=new dc,th={createKey:rY,isEquivalent:fY,estimateMemoryUsage:cY},FY=jf(zc.cwd(),"config"),IY=jf(zc.cwd(),"src/generated"),Fu=Uf.env.CLARITY_LOG_DIR||mE(wY(),"logs"),Ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Mc=await uY(),$i={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=$i,KY=$i.red,Iu=$i.green,_Y=$i.yellow,Ku=$i.blue,zY=$i.magenta,QY=$i.cyan,Sc=$i.white,MY=$i.gray,_u=$i.bgRed,zu=$i.bgYellow,ac=$i.bold,OY=$i.dim,GY=$i.italic,HY=$i.underline,qY=$i.reset,Yf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nh={debug:"\uD83D\uDD0D",info:Ku("ℹ"),success:Iu("✓"),warning:zu(Sc(ac(" WARN "))),error:_u(Sc(ac(" ERROR ")))},gY=new Xf("stacks"),Ai=new Xf("bunfig",{showTags:!0}),LY=ei(Mn.cwd(),"config"),sY=ei(Mn.cwd(),"src/generated"),Qu=mf.env.CLARITY_LOG_DIR||eE(TY(),"logs"),Bf={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,writeToFile:!1},Oc=await EY(),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"},Q=ri,xY=ri.red,Mu=ri.green,kY=ri.yellow,Ou=ri.blue,VY=ri.magenta,dY=ri.cyan,Jc=ri.white,DY=ri.gray,Gu=ri.bgRed,Hu=ri.bgYellow,bY=ri.bgGray,Fc=ri.bold,PY=ri.dim,ZY=ri.italic,vY=ri.underline,oY=ri.strikethrough,pY=ri.reset,ef={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rh={debug:"\uD83D\uDD0D",info:Ou("ℹ"),success:Mu("✓"),warning:Hu(Jc(Fc(" WARN "))),error:Gu(Jc(Fc(" ERROR ")))},iB=new Sf("stacks"),Si=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},af=class extends Si{code="CONFIG_NOT_FOUND";constructor(t,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},On=class extends Si{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Gc=class extends Si{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Hc=class extends Si{code="CONFIG_MERGE_ERROR";constructor(t,n,r,f){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},Jf=class extends Si{code="ENV_VAR_ERROR";constructor(t,n,r,f){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:f})}},qc=class extends Si{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},gc=class extends Si{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Gn=class extends Si{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Lc=class extends Si{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,f){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:f})}},sc=class extends Si{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},jt={configNotFound(i,t,n){return new af(i,t,n)},configLoad(i,t,n){return new On(i,t,n)},configValidation(i,t,n){return new Gc(i,t,n)},configMerge(i,t,n,r){return new Hc(i,t,n,r)},envVar(i,t,n,r){return new Jf(i,t,n,r)},fileSystem(i,t,n){return new qc(i,t,n)},typeGeneration(i,t,n){return new gc(i,t,n)},schemaValidation(i,t,n){return new Gn(i,t,n)},browserConfig(i,t,n,r){return new Lc(i,t,n,r)},plugin(i,t,n){return new sc(i,t,n)}},fh={replace:"replace",concat:"concat",smart:"smart"},ch=/^https?:\/\//,gi=new Sf("bunfig",{showTags:!0}),$t=new vc,lh=Ci(zt.cwd(),"config"),yh=Ci(zt.cwd(),"src/generated")});function rB(i,t={}){let n=Nf.cwd();while(n.includes("storage"))n=ju(n,"..");let r=ju(n,i||"");if(t?.relative)return sE(Nf.cwd(),r);return r}var fB=Nf.env.CLARITY_LOG_DIR||LE(rB(),"logs"),wh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ff={...wh},gN=(async()=>{try{let{loadConfig:i}=await nB().then(()=>Vu),t=await i({name:"clarity",alias:"logging",defaultConfig:wh,cwd:Nf.cwd()});if(t)Object.assign(Ff,t)}catch{}return Ff})();function fi(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cB(){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 uh{async format(i){let t=await cB(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:En.pid,hostname:t(),environment:En.env.NODE_ENV||"development",platform:En.platform,version:En.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:En.env.NODE_ENV||En.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=li,LN=li.red,lB=li.green,sN=li.yellow,yB=li.blue,xN=li.magenta,kN=li.cyan,qu=li.white,VN=li.gray,wB=li.bgRed,uB=li.bgYellow,dN=li.bgGray,gu=li.bold,DN=li.dim,bN=li.italic,PN=li.underline,ZN=li.strikethrough,vN=li.reset,Ic={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hB={debug:"\uD83D\uDD0D",info:yB("ℹ"),success:lB("✓"),warning:uB(qu(gu(" WARN "))),error:wB(qu(gu(" ERROR ")))};class Mf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Ff},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Ic,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Ic};return{...Ic,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Ff.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await DE(this.config.logDirectory,Wu.F_OK|Wu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await bE(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:lt.from(i);try{if(!lf(this.currentLogFile))await Wc(this.currentLogFile,"",{mode:420});if(f=Xu(this.currentLogFile,"a",420),dE(f,w,{flag:"a"}),Ru(f),f!==void 0)Xc(f),f=void 0;if((await An(this.currentLogFile)).size===0){if(await Wc(this.currentLogFile,w,{flag:"w",mode:420}),(await An(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(f!==void 0)try{Xc(f)}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(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Tn(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 Tn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Tn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())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 n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=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(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Rc(16).toString("hex")}generateKey(){return Rc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Rc(16),r=xE("aes-256-gcm",t,n),f=lt.isBuffer(i)?i:lt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=lt.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=au(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(lt.from(lt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await An(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await yf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await An(n).catch(()=>null))try{if(await Su(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await wf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await 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 f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await An(n).catch(()=>null))await Su(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await yf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await wf(Tn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=Nu(i),r=VE(t),f=au();await vE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),lf(this.currentLogFile))try{let i=Xu(this.currentLogFile,"r+");Ru(i),Xc(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(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await yf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await wf(Tn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=_.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${O.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=O.underline(O.blue(r)),l=this.toAbsoluteFilePath(f);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;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>O.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>O.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>O.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>O.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>O.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=_.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(PE(t)||t.startsWith("./")||t.startsWith("../"))t=ZE(t);else return null;return lf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":hB[i],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let e=y.split(`
111
111
  `);for(let E of e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!fi()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
112
112
  `;if(y)h+=`${y}
113
113
  `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!fi()&&_.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()&&!fi()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!fi()&&_.stdout.isTTY)_.stdout.write(`
114
114
  `);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!fi()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:n,message:`${O.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
115
- `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":O.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!fi())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}`,n=new Qf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!cf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ju(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=lt.isBuffer(i)?i:lt.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=xE("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=lt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return fi()}isServerMode(){return!fi()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
115
+ `,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":O.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!fi())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}`,n=new Mf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!lf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Nu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=lt.isBuffer(i)?i:lt.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=kE("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=lt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return fi()}isServerMode(){return!fi()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
116
116
  `),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:O.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(h),showTimestamp:!1}))}else if(!fi())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
117
117
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(fi())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();_.stdin.removeListener("data",n);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(n=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)n+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${u}${w} ${O.cyan(r)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
118
118
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=O.green("━".repeat(r)),l=O.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?O.green("✓"):O.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=_.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
119
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!_.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(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await lf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=Tn(this.config.logDirectory,r);if(i.before)try{if((await An(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await yf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var vN=new Qf("stacks");class si 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,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class uh extends si{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class Ff extends si{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class hh extends si{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class $h extends si{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class vc extends si{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Ah extends si{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Th extends si{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class If extends si{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Eh extends si{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class Yh extends si{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var Bn={configNotFound(i,t,n){return new uh(i,t,n)},configLoad(i,t,n){return new Ff(i,t,n)},configValidation(i,t,n){return new hh(i,t,n)},configMerge(i,t,n,r){return new $h(i,t,n,r)},envVar(i,t,n,r){return new vc(i,t,n,r)},fileSystem(i,t,n){return new Ah(i,t,n)},typeGeneration(i,t,n){return new Th(i,t,n)},schemaValidation(i,t,n){return new If(i,t,n)},browserConfig(i,t,n,r){return new Eh(i,t,n,r)},plugin(i,t,n){return new Yh(i,t,n)}};async function hB(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class oc{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return xc.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=uf.env[w]||(u?uf.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=uf.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof vc)throw $;throw Bn.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Bn.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(uf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
119
+ `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!_.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(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await yf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=Tn(this.config.logDirectory,r);if(i.before)try{if((await An(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await wf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var oN=new Mf("stacks");class Li 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,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class hh extends Li{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class If extends Li{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class $h extends Li{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Ah extends Li{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class oc extends Li{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Th extends Li{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Eh extends Li{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Kf extends Li{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Yh extends Li{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class Bh extends Li{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var Bn={configNotFound(i,t,n){return new hh(i,t,n)},configLoad(i,t,n){return new If(i,t,n)},configValidation(i,t,n){return new $h(i,t,n)},configMerge(i,t,n,r){return new Ah(i,t,n,r)},envVar(i,t,n,r){return new oc(i,t,n,r)},fileSystem(i,t,n){return new Th(i,t,n)},typeGeneration(i,t,n){return new Eh(i,t,n)},schemaValidation(i,t,n){return new Kf(i,t,n)},browserConfig(i,t,n,r){return new Yh(i,t,n,r)},plugin(i,t,n){return new Bh(i,t,n)}};async function $B(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class pc{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return kc.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,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=hf.env[w]||(u?hf.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=hf.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof oc)throw $;throw Bn.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Bn.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(hf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.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 n=`Environment Variables for ${t}:
120
120
 
121
121
  `;for(let r of i)n+=`${r.key}
122
122
  `,n+=` Type: ${r.type}
@@ -128,10 +128,10 @@ export type ConfigOf = Config
128
128
  `;n+=`| Variable | Type | Description | Example |
129
129
  `,n+=`|----------|------|-------------|----------|
130
130
  `;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
131
- `;return n}}function $B(i,t,n={}){return Bh(i,t,n,new WeakMap)}function Bh(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 eh(i,t,f,r);if(!zi(t)||!zi(i))return t;return YB(i,t,n,r)}function eh(i,t,n,r){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(n){case"replace":return t;case"concat":return AB(i,t);case"smart":return TB(i,t,r);default:return t}return t}function AB(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Lc(f,r)))n.push(r);return n}function TB(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return EB(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function EB(i,t,n){let r=[...t];for(let f of i){if(!zi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>zi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function YB(i,t,n,r){let f=t;if(zi(f)&&r.has(f))return r.get(f);let c={...i};if(zi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(zi(y)&&zi(w))c[l]=Bh(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=eh(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Ch(i,t,n="replace"){return $B(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Lc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Lc(i[n],t[n]))return!1;return!0}if(zi(i)&&zi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Lc(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class mh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=ef.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!hf(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 Ff(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Ff(i,Error("Configuration must export a valid object"),"unknown");let B={config:Ch(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)ef.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Bn.configLoad(i,u):Bn.configLoad(i,Error(String(u)))}};if(l)return xc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(Ic(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return hB(async()=>{return hf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!hf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=Ic(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Ic(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!hf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var eB=/^https?:\/\//;class Uh{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 xc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!BB(t))throw new If(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new If(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:eB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var yt=new Qf("bunfig",{showTags:!0});function CB(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((n)=>`"${n}"`).join(", ")}`}class jh{fileLoader=new mh;envProcessor=new oc;validator=new Uh;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)yt.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 yt.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Kf.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ki($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Bn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${CB(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?$f(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)yt.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)yt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?$f(i,n,f):n,y=[Ki(fn(),".config",i),Ki(fn(),".config"),fn()];for(let w of y){if(f)yt.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)yt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?$f(i,r,c):r;try{let w=Ki(n,"package.json");if(!$E(w))return null;let u={};try{u=JSON.parse(AE(w,"utf8"))}catch(A){if(c)yt.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)yt.success(`Configuration loaded from package.json: ${$}`);return{config:Ch(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)yt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:$f(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Bn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return ef.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);ef.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ki(i,"config"),Ki(i,".config"),t?Ki(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ki(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ki(fn(),".config",i),Ki(fn(),".config"),fn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var nR=new jh;function $f(i,t,n=!1){let r=new oc,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=Kf.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 rR=Ki(Kf.cwd(),"config"),fR=Ki(Kf.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",mB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:il(pc(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:il(pc(),".stacks","ssl","stacks.localhost.crt"),keyPath:il(pc(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Nh=mB;import{execSync as qn}from"node:child_process";import{homedir as RB}from"node:os";import{join as XB}from"node:path";function UB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Qt(i){try{return Zr(i)}catch{return null}}function tl(i){try{return wc(i)||null}catch{return null}}function nl(i,t){try{return t.every((n)=>hc(i,n))}catch{return!1}}function jB(i,t,n=443){return uc(i,t,n)}function NB(i){let t=[];for(let n of i.split(`
132
- `)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var Di="-d -r trustRoot -p ssl -p basic",At="/Library/Keychains/System.keychain",rl="rpx.localhost";function gn(){return XB(RB(),"Library/Keychains/login.keychain-db")}function fl(){return[At,gn()]}function Rh(i,t=rl){let n=qn(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
133
- `)){let c=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)r.push(c[1].toUpperCase())}return r}function Mf(i){if(process.platform!=="darwin")return;let t=Qt(i.caPath);if(!t)return;let n=i.commonName??rl,r=i.keychains??fl();for(let f of r)for(let c of Rh(f,n)){if(c===t)continue;try{if(f.startsWith("/Library"))Nt(`security delete-certificate -Z ${c} "${f}"`);else qn(`security delete-certificate -Z ${c} "${f}"`,{stdio:"ignore"});Y("ssl",`Removed stale Root CA ${c} from ${f}`,i.verbose)}catch{}}}function sn(i,t,n){if(process.platform!=="darwin")return Ln(i,n);try{let f=qn(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return Y("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function Ln(i,t){let n=Qt(i);if(!n)return!1;for(let r of fl())try{let f=qn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let c of f.split(`
134
- `))if(c.toUpperCase().includes("SHA-256")){if(c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return Y("ssl",`Root CA fingerprint found in ${r}`,t?.verbose),!0}}catch{}return!1}function cl(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Mf({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=gn();try{qn(`security add-trusted-cert ${Di} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{Nt(`security add-trusted-cert ${Di} -k ${At} "${i}"`)}catch{return!1}return sn(i,n,{verbose:t.verbose})||Ln(i,{verbose:t.verbose})}var Rt=null,ul=D(en(),".stacks","ssl","rpx.localhost.crt");function Ih(i,t){return[...new Set(i.filter(Boolean))].map((n)=>({serverName:n,cert:t.cert,key:t.key}))}function Kh(i,t,n){let r=D(en(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:ul,keyPath:D(r,"rpx.localhost.key"),caCertPath:D(r,"rpx.localhost.ca.crt"),commonName:t},verbose:n,regenerateUntrustedCerts:!0,proxies:f.map((c)=>({from:"localhost:1",to:c,cleanUrls:!1}))}}var WB="rpx-root-ca.crt",SB="rpx-root-ca.key";function hl(i){return{caCertPath:D(i,WB),caKeyPath:D(i,SB)}}function KR(i){return{certPath:D(i,"rpx.localhost.crt"),keyPath:D(i,"rpx.localhost.key"),caCertPath:D(i,"rpx.localhost.ca.crt"),rootCA:hl(i)}}async function aB(i,t){try{let[n,r]=await Promise.all([Z.readFile(i.caCertPath,"utf8"),Z.readFile(i.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return Y("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:n,privateKey:r}}catch(n){return Y("ssl",`No existing Root CA at ${i.caCertPath} (${n.code||n}), will create one`,t),null}}function Xh(i){let t=new Set;t.add(i);let n=i.split(".");if(n.length>=3){let r=n[n.length-1],f=n[n.length-2],c=new Set(["co","com","org","net","ac","gov","edu"]);if(!(n.length===3&&r.length===2&&c.has(f)))t.add(`*.${n.slice(1).join(".")}`)}return Array.from(t)}function _h(i){let n=wl(i).replace(/\*/g,"wildcard"),r=D(en(),".stacks","ssl"),f=r;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:r,{caCertPath:i.https.caCertPath||D(f,`${n}.ca.crt`),certPath:i.https.certPath||D(f,`${n}.crt`),keyPath:i.https.keyPath||D(f,`${n}.key`)};return{caCertPath:D(f,`${n}.ca.crt`),certPath:D(f,`${n}.crt`),keyPath:D(f,`${n}.key`)}}function Wh(i){let t=new Set;if(Of(i))i.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";Xh(r).forEach((f)=>t.add(f))});else if(ah(i)){let n=i.to||"rpx.localhost";Xh(n).forEach((r)=>t.add(r))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function _R(i){Y("ssl","Loading SSL configuration",i.verbose);let t={...Nh,...i};if(i.https=Tl(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 n=!i.https?.keyPath?"keyPath":"certPath";throw Y("ssl",`Invalid SSL configuration - missing ${n}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{Y("ssl","Reading SSL certificate files",i.verbose);let n=await Z.readFile(i.https?.keyPath,"utf8"),r=await Z.readFile(i.https?.certPath,"utf8");return Y("ssl","SSL configuration loaded successfully",i.verbose),{key:n,cert:r}}catch(n){return Y("ssl",`Failed to read certificates: ${n}`,i.verbose),null}}catch(n){throw Y("ssl",`SSL configuration error: ${n}`,i.verbose),n}}async function zR(i,t){if(Li.platform==="darwin")return JB(i,t);if(Li.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(c)=>{r(!c)})})})}catch{return!1}return!1}async function JB(i,t){if(Li.platform!=="darwin")return!1;let n=t?.serverName??"rpx.localhost",r=t?.verbose??!1;try{if(sn(i,n,{verbose:r}))return Y("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return Y("ssl","Trusting Root CA for browsers (login + system keychains)",r),cl(i,{serverName:n,verbose:r})}catch{return!1}}async function zh(i){if(Rt&&!i.forceRegenerate){Y("ssl","Using cached SSL configuration",i.verbose);return}$l();let t=Of(i)?i.proxies.map((h)=>h.to):[i.to];Y("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let n=Tl(i,i.verbose),r=n.basePath||D(en(),".stacks","ssl");await Z.mkdir(r,{recursive:!0});let f=hl(r),c=await aB(f,i.verbose),l=!1;if(!c){if(i.verbose)J.info("Generating Root CA certificate (one-time)...");c=await lc(n);try{await Promise.all([Z.writeFile(f.caCertPath,c.certificate),Z.writeFile(f.caKeyPath,c.privateKey,{mode:384})]),l=!0,Y("ssl",`Persisted Root CA at ${f.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 ${f.caCertPath}`,i.verbose);if(i.verbose)J.info(`Generating host certificate for: ${t.join(", ")}`);let y=await yc({...n,rootCA:{certificate:c.certificate,privateKey:c.privateKey}});try{await Promise.all([Z.writeFile(n.certPath,y.certificate),Z.writeFile(n.keyPath,y.privateKey),Z.writeFile(n.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 Qh(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(Y("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)J.success("Root CA is already trusted in system trust store");if(Rt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)J.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)J.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(Li.platform==="darwin")try{Mf({caPath:f.caCertPath,verbose:i.verbose});let h=gn();try{ll(`security add-trusted-cert ${Di} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Nt(`security add-trusted-cert ${Di} -k ${At} "${f.caCertPath}"`),i.verbose)J.success("Successfully added Root CA to system trust store");u=!0;let $=D(r,"trust-rpx-cert.sh"),A=`#!/bin/bash
131
+ `;return n}}function AB(i,t,n={}){return eh(i,t,n,new WeakMap)}function eh(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;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 Ch(i,t,f,r);if(!zi(t)||!zi(i))return t;return BB(i,t,n,r)}function Ch(i,t,n,r){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(n){case"replace":return t;case"concat":return TB(i,t);case"smart":return EB(i,t,r);default:return t}return t}function TB(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>xc(f,r)))n.push(r);return n}function EB(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return YB(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function YB(i,t,n){let r=[...t];for(let f of i){if(!zi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>zi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function BB(i,t,n,r){let f=t;if(zi(f)&&r.has(f))return r.get(f);let c={...i};if(zi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(zi(y)&&zi(w))c[l]=eh(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Ch(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function mh(i,t,n="replace"){return AB(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function xc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!xc(i[n],t[n]))return!1;return!0}if(zi(i)&&zi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!xc(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Uh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=Cf.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$f(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 B={config:mh(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Cf.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Bn.configLoad(i,u):Bn.configLoad(i,Error(String(u)))}};if(l)return kc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(Kc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return $B(async()=>{return $f(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!$f(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=Kc(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Kc(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}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((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!$f(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var CB=/^https?:\/\//;class jh{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,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 kc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!eB(t))throw new Kf(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Kf(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,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(r.push({path:n,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(r.push({path:n,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)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,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=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.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(r.push({path:n?`${n}.${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=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.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))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,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))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,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:CB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var yt=new Mf("bunfig",{showTags:!0});function mB(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((n)=>`"${n}"`).join(", ")}`}class Nh{fileLoader=new Uh;envProcessor=new pc;validator=new jh;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}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(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)yt.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 yt.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_f.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let e=await this.loadHomeConfiguration(r,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(e,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ki($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Bn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${mB(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Af(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)yt.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)yt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Af(i,n,f):n,y=[Ki(fn(),".config",i),Ki(fn(),".config"),fn()];for(let w of y){if(f)yt.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)yt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Af(i,r,c):r;try{let w=Ki(n,"package.json");if(!AE(w))return null;let u={};try{u=JSON.parse(TE(w,"utf8"))}catch(A){if(c)yt.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)yt.success(`Configuration loaded from package.json: ${$}`);return{config:mh(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)yt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Af(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Bn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Cf.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Cf.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ki(i,"config"),Ki(i,".config"),t?Ki(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ki(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ki(fn(),".config",i),Ki(fn(),".config"),fn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var rR=new Nh;function Af(i,t,n=!1){let r=new pc,f=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=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,e;for(let E of A)if(T=_f.env[E],T!==void 0){e=E;break}if(T!==void 0&&e)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 fR=Ki(_f.cwd(),"config"),cR=Ki(_f.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",UB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:tl(il(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:tl(il(),".stacks","ssl","stacks.localhost.crt"),keyPath:tl(il(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Rh=UB;import{execSync as qn}from"node:child_process";import{homedir as XB}from"node:os";import{join as WB}from"node:path";function jB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Qt(i){try{return vr(i)}catch{return null}}function nl(i){try{return uc(i)||null}catch{return null}}function rl(i,t){try{return t.every((n)=>$c(i,n))}catch{return!1}}function NB(i,t,n=443){return hc(i,t,n)}function RB(i){let t=[];for(let n of i.split(`
132
+ `)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var Di="-d -r trustRoot -p ssl -p basic",At="/Library/Keychains/System.keychain",fl="rpx.localhost";function gn(){return WB(XB(),"Library/Keychains/login.keychain-db")}function cl(){return[At,gn()]}function Xh(i,t=fl){let n=qn(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
133
+ `)){let c=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)r.push(c[1].toUpperCase())}return r}function Of(i){if(process.platform!=="darwin")return;let t=Qt(i.caPath);if(!t)return;let n=i.commonName??fl,r=i.keychains??cl();for(let f of r)for(let c of Xh(f,n)){if(c===t)continue;try{if(f.startsWith("/Library"))Nt(`security delete-certificate -Z ${c} "${f}"`);else qn(`security delete-certificate -Z ${c} "${f}"`,{stdio:"ignore"});Y("ssl",`Removed stale Root CA ${c} from ${f}`,i.verbose)}catch{}}}function Ln(i,t,n){if(process.platform!=="darwin")return sn(i,n);try{let f=qn(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return Y("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function sn(i,t){let n=Qt(i);if(!n)return!1;for(let r of cl())try{let f=qn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let c of f.split(`
134
+ `))if(c.toUpperCase().includes("SHA-256")){if(c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return Y("ssl",`Root CA fingerprint found in ${r}`,t?.verbose),!0}}catch{}return!1}function ll(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Of({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=gn();try{qn(`security add-trusted-cert ${Di} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{Nt(`security add-trusted-cert ${Di} -k ${At} "${i}"`)}catch{return!1}return Ln(i,n,{verbose:t.verbose})||sn(i,{verbose:t.verbose})}var Rt=null,hl=D(en(),".stacks","ssl","rpx.localhost.crt");function Kh(i,t){return[...new Set(i.filter(Boolean))].map((n)=>({serverName:n,cert:t.cert,key:t.key}))}function _h(i,t,n){let r=D(en(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:hl,keyPath:D(r,"rpx.localhost.key"),caCertPath:D(r,"rpx.localhost.ca.crt"),commonName:t},verbose:n,regenerateUntrustedCerts:!0,proxies:f.map((c)=>({from:"localhost:1",to:c,cleanUrls:!1}))}}var SB="rpx-root-ca.crt",aB="rpx-root-ca.key";function $l(i){return{caCertPath:D(i,SB),caKeyPath:D(i,aB)}}function _R(i){return{certPath:D(i,"rpx.localhost.crt"),keyPath:D(i,"rpx.localhost.key"),caCertPath:D(i,"rpx.localhost.ca.crt"),rootCA:$l(i)}}async function JB(i,t){try{let[n,r]=await Promise.all([Z.readFile(i.caCertPath,"utf8"),Z.readFile(i.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return Y("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:n,privateKey:r}}catch(n){return Y("ssl",`No existing Root CA at ${i.caCertPath} (${n.code||n}), will create one`,t),null}}function Wh(i){let t=new Set;t.add(i);let n=i.split(".");if(n.length>=3){let r=n[n.length-1],f=n[n.length-2],c=new Set(["co","com","org","net","ac","gov","edu"]);if(!(n.length===3&&r.length===2&&c.has(f)))t.add(`*.${n.slice(1).join(".")}`)}return Array.from(t)}function zh(i){let n=ul(i).replace(/\*/g,"wildcard"),r=D(en(),".stacks","ssl"),f=r;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:r,{caCertPath:i.https.caCertPath||D(f,`${n}.ca.crt`),certPath:i.https.certPath||D(f,`${n}.crt`),keyPath:i.https.keyPath||D(f,`${n}.key`)};return{caCertPath:D(f,`${n}.ca.crt`),certPath:D(f,`${n}.crt`),keyPath:D(f,`${n}.key`)}}function Sh(i){let t=new Set;if(Gf(i))i.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";Wh(r).forEach((f)=>t.add(f))});else if(Jh(i)){let n=i.to||"rpx.localhost";Wh(n).forEach((r)=>t.add(r))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function zR(i){Y("ssl","Loading SSL configuration",i.verbose);let t={...Rh,...i};if(i.https=El(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 n=!i.https?.keyPath?"keyPath":"certPath";throw Y("ssl",`Invalid SSL configuration - missing ${n}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{Y("ssl","Reading SSL certificate files",i.verbose);let n=await Z.readFile(i.https?.keyPath,"utf8"),r=await Z.readFile(i.https?.certPath,"utf8");return Y("ssl","SSL configuration loaded successfully",i.verbose),{key:n,cert:r}}catch(n){return Y("ssl",`Failed to read certificates: ${n}`,i.verbose),null}}catch(n){throw Y("ssl",`SSL configuration error: ${n}`,i.verbose),n}}async function QR(i,t){if(si.platform==="darwin")return FB(i,t);if(si.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(c)=>{r(!c)})})})}catch{return!1}return!1}async function FB(i,t){if(si.platform!=="darwin")return!1;let n=t?.serverName??"rpx.localhost",r=t?.verbose??!1;try{if(Ln(i,n,{verbose:r}))return Y("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return Y("ssl","Trusting Root CA for browsers (login + system keychains)",r),ll(i,{serverName:n,verbose:r})}catch{return!1}}async function Qh(i){if(Rt&&!i.forceRegenerate){Y("ssl","Using cached SSL configuration",i.verbose);return}Al();let t=Gf(i)?i.proxies.map((h)=>h.to):[i.to];Y("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let n=El(i,i.verbose),r=n.basePath||D(en(),".stacks","ssl");await Z.mkdir(r,{recursive:!0});let f=$l(r),c=await JB(f,i.verbose),l=!1;if(!c){if(i.verbose)J.info("Generating Root CA certificate (one-time)...");c=await yc(n);try{await Promise.all([Z.writeFile(f.caCertPath,c.certificate),Z.writeFile(f.caKeyPath,c.privateKey,{mode:384})]),l=!0,Y("ssl",`Persisted Root CA at ${f.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 ${f.caCertPath}`,i.verbose);if(i.verbose)J.info(`Generating host certificate for: ${t.join(", ")}`);let y=await wc({...n,rootCA:{certificate:c.certificate,privateKey:c.privateKey}});try{await Promise.all([Z.writeFile(n.certPath,y.certificate),Z.writeFile(n.keyPath,y.privateKey),Z.writeFile(n.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 Mh(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(Y("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)J.success("Root CA is already trusted in system trust store");if(Rt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)J.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)J.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(si.platform==="darwin")try{Of({caPath:f.caCertPath,verbose:i.verbose});let h=gn();try{yl(`security add-trusted-cert ${Di} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Nt(`security add-trusted-cert ${Di} -k ${At} "${f.caCertPath}"`),i.verbose)J.success("Successfully added Root CA to system trust store");u=!0;let $=D(r,"trust-rpx-cert.sh"),A=`#!/bin/bash
135
135
  echo "Trusting RPX Root CA"
136
136
  # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
137
137
  # non-interactive. Without it, fall back to a normal sudo prompt.
@@ -157,34 +157,34 @@ else
157
157
  fi
158
158
  echo "Root CA trusted! Please restart your browser."
159
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)J.info(`Created a trust helper script at: ${$}`),J.info(`If you're still having certificate issues, run: sh ${$}`)}else if(Li.platform==="linux")try{let{exec:h}=await import("node:child_process"),$="/usr/local/share/ca-certificates/rpx",A=`
160
+ `;if(await Z.writeFile($,A,{mode:493}),i.verbose)J.info(`Created a trust helper script at: ${$}`),J.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
161
  mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
162
162
  cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
163
163
  update-ca-certificates
164
164
  echo "RPX Root CA installed. Please restart your browser."
165
- `,T=D(yl.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((e)=>{h(`sudo bash "${T}"`,(E)=>{if(E){if(i.verbose)J.warn(`Could not trust certificates: ${E}`);e(!1)}else{if(i.verbose)J.success("Successfully added certificates to system trust store");e(!0)}})}),await Z.unlink(T).catch(()=>{}),u=!0}catch(h){if(i.verbose)J.warn(`Failed to trust certificates: ${h}`)}else if(Li.platform==="win32")try{let h=`
165
+ `,T=D(wl.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((e)=>{h(`sudo bash "${T}"`,(E)=>{if(E){if(i.verbose)J.warn(`Could not trust certificates: ${E}`);e(!1)}else{if(i.verbose)J.success("Successfully added certificates to system trust store");e(!0)}})}),await Z.unlink(T).catch(()=>{}),u=!0}catch(h){if(i.verbose)J.warn(`Failed to trust certificates: ${h}`)}else if(si.platform==="win32")try{let h=`
166
166
  $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
167
167
  $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
168
168
  $store.Open("ReadWrite")
169
169
  $store.Add($cert)
170
170
  $store.Close()
171
171
  Write-Host "Root CA trusted successfully!"
172
- `,$=D(yl.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),ll(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)J.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)J.warn(`Could not trust certificate: ${h}`)}else try{await $c(y,c.certificate,n),u=!0}catch(h){if(i.verbose)J.warn(`Could not add certificate to trust store: ${h}`)}if(Rt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)J.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)J.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),J.warn("This will bypass the warning and you should only need to do it once")}function $l(){Rt=null}async function Al(i){if(!i)return null;if(Rt)return Rt;let t=Tl(i);try{let[n,r,f]=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(!n||!r)return Y("ssl",`Certificate files don't exist: key=${n}, cert=${r}, 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(en(),".stacks","ssl"),u=hl(w);if(!(y?await Qh(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"),f&&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(Of(i))try{let{X509Certificate:e}=await import("node:crypto"),B=new e(A).subjectAltName||"",U=i.proxies.map((W)=>W.to).filter((W)=>!B.includes(`DNS:${W}`));if(U.length>0)return Y("ssl",`Certificate missing SANs for: ${U.join(", ")}, will regenerate`,i.verbose),null}catch(e){Y("ssl",`Could not verify cert SANs: ${e}`,i.verbose)}return Y("ssl","Successfully loaded existing certificates",i.verbose),Rt={key:$,cert:A,ca:T},Rt}catch(n){return Y("ssl",`Error checking existing certificates: ${n}`,i.verbose),null}}function Tl(i,t){let n=wl(i);Y("ssl",`Primary domain: ${n}`,t);let r=_h(i),f=D(en(),".stacks","ssl");if(typeof i.https==="object"){let c=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,l={domain:n,hostCertCN:n,basePath:c,caCertPath:i.https.caCertPath||r.caCertPath,certPath:i.https.certPath||r.certPath,keyPath:i.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||n,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(Wh(i)).map((y)=>({type:2,value:y}))};if(Sh(i.https.rootCA))l.rootCA=i.https.rootCA;return l}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Wh(i)).map((c)=>({type:2,value:c}))}}async function QR(i,t){let n=_h({to:i,verbose:t}),r=[n.caCertPath,n.certPath,n.keyPath];Y("certificates","Attempting to clean up relating certificates",t),await Promise.all(r.map((f)=>Jh(f,t)))}async function Qh(i,t){try{if(Y("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),Li.platform==="darwin"){if(t?.serverName)return sn(i,t.serverName,{verbose:t?.verbose});return Ln(i,{verbose:t?.verbose})}else if(Li.platform==="win32")try{let n=tl(i)||"";if(!n)return Y("ssl","Could not extract certificate subject",t?.verbose),!1;let r=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(ll(r).toString().includes(n))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(n){return Y("ssl",`Error checking certificate trust on Windows: ${n}`,t?.verbose),!1}else if(Li.platform==="linux")try{let n=Qt(i);if(!n)return Y("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let r=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of r){let c;try{c=await Z.readdir(f)}catch{continue}for(let l of c){let y=Qt(Fh.join(f,l));if(y&&y===n)return Y("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return Y("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(n){return Y("ssl",`Error checking certificate trust on Linux: ${n}`,t?.verbose),!1}return Y("ssl",`Platform ${Li.platform} not supported for certificate trust check`,t?.verbose),!1}catch(n){return Y("ssl",`Error checking if certificate is trusted: ${n}`,t?.verbose),!1}}function FB(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 IB(i){return(Array.isArray(i)?i:[i]).map((n)=>{let r=typeof n==="string"?{url:n}:n;return{url:r.url,weight:r.weight&&r.weight>0?r.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Mh(i){return(Array.isArray(i)?i:[i]).map((n)=>typeof n==="string"?n:n.url)}function Oh(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 Gh(i,t){return{upstreams:IB(i),strategy:t?.strategy??"round-robin",healthCheck:FB(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function KB(i){let t=i.upstreams.filter((n)=>n.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function _B(i,t){let n=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[n]}function zB(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let n=t.reduce((f,c)=>f+c.weight,0),r=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[r])r=f;return i.wrrCurrentWeights[r]-=n,t[r]}function QB(i){let t=i[0];for(let n=1;n<i.length;n++)if(i[n].activeConnections<t.activeConnections)t=i[n];return t}function Hh(i){let t=KB(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return zB(i,t);case"least-connections":return QB(t);case"round-robin":default:return _B(i,t)}}function Gf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function xn(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function MB(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let n=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(n)?n:80}}async function OB(i,t){let{hostname:n,port:r}=MB(t.url),f=new AbortController,c=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${n}:${r}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Gf(i,t)}catch{xn(i,t)}finally{clearTimeout(c)}}function qh(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let n of i.upstreams)OB(i,n)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function El(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as sh,timingSafeEqual as gh}from"node:crypto";import{readFileSync as GB}from"node:fs";var HB="/.well-known/acme-challenge/";function kn(i,t){let n=Buffer.from(i,"utf8"),r=Buffer.from(t,"utf8");if(n.length!==r.length)return gh(n,n),!1;return gh(n,r)}function qB(i,t){let n=(A)=>sh("md5").update(A).digest(),r=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),c=n(Buffer.concat([r,f,r])),l=[r,Buffer.from("$apr1$","utf8"),f];for(let A=r.length;A>0;A-=16)l.push(c.subarray(0,Math.min(A,16)));for(let A=r.length;A>0;A>>=1)l.push(A&1?Buffer.from([0]):r.subarray(0,1));let y=n(Buffer.concat(l));for(let A=0;A<1000;A++){let T=[];if(T.push(A&1?r:y.subarray(0,16)),A%3)T.push(f);if(A%7)T.push(r);T.push(A&1?y.subarray(0,16):r),y=n(Buffer.concat(T))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",u=(A,T)=>{let e="",E=A;for(let B=0;B<T;B++)e+=w[E&63],E>>=6;return e},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 gB(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let r=t.split("$")[2]??"";return kn(qB(i,r),t)}if(t.startsWith("{SHA}")){let n=sh("sha1").update(i,"utf8").digest("base64");return kn(`{SHA}${n}`,t)}return kn(i,t)}function sB(i){let t=new Map;for(let n of i.split(`
173
- `)){let r=n.trim();if(!r||r.startsWith("#"))continue;let f=r.indexOf(":");if(f<=0)continue;t.set(r.slice(0,f),r.slice(f+1))}return t}function Lh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",n=[];if(i.username)n.push({username:i.username,password:i.password??""});for(let c of i.users??[])if(c?.username)n.push({username:c.username,password:c.password??""});let r;if(i.htpasswdFile)try{r=sB(GB(i.htpasswdFile,"utf8"))}catch{r=void 0}if(n.length===0&&(!r||r.size===0))return;return{realm:t,verify:(c,l)=>{let y=!1;for(let w of n)if(kn(c,w.username)&&kn(l,w.password))y=!0;if(r){let w=r.get(c);if(w&&gB(l,w))y=!0}return y}}}function xh(i,t,n){if(t.startsWith(HB))return;let r=i.headers.get("authorization")??"",f=r.indexOf(" "),c=f===-1?r:r.slice(0,f),l=f===-1?"":r.slice(f+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&&n.verify(w.slice(0,u),w.slice(u+1)))return}let y=n.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:LB}=Bun,Vn=Symbol("rpx.pool.fallback"),Hf=Symbol("rpx.pool.stale");var xB=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function kB(i){return xB.has(i.toUpperCase())}var Bl=Symbol("rpx.pool.timeout"),Mt=Symbol("rpx.pool.busy");function VB(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function dB(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function DB(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function bB(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Vh=1048576;function PB(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var Yl=30000,ZB=16384,dh=262144,vB=2097152,oB=524288,pB=8192,ie=4096,te=new TextEncoder,Dh=new TextDecoder,ne=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class bh{socket=null;buf=new Uint8Array(ZB);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,n=t.write(i);while(n<i.length){if(this.closed)throw Hf;await new Promise((r)=>{this.drainWaiter=r}),n+=t.write(i.subarray(n))}}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()>vB)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=oB)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 n=new Uint8Array(Math.max(this.buf.length*2,t));n.set(this.buf.subarray(0,this.len)),this.buf=n}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 Ph{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=VB();maxWaiters;checkoutIdleMs=DB();inUse=new Set;constructor(i,t,n,r=""){this.host=i;this.port=t;this.maxTotal=n;this.key=r;this.maxWaiters=dB(n)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new bh;return LB({hostname:this.host,port:this.port,socket:{data:(t,n)=>i.push(n),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let n=t;n.setNoDelay?.(!0);let r=bB();if(r>0)n.timeout?.(r);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,n=(c)=>{if(t)return;t=!0,clearTimeout(f),i(c)},r=(c)=>n(c),f=setTimeout(()=>{let c=this.waiters.indexOf(r);if(c!==-1)this.waiters.splice(c,1);n(Mt)},this.queueWaitMs);f.unref?.(),this.waiters.push(r)})}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(Yl,this.checkoutIdleMs):Yl;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-Yl;if(this.idle.length){let n=[];for(let r of this.idle)if(r.closed||r.idleSince<=t)r.destroy(),this.open--;else n.push(r);this.idle=n}if(this.checkoutIdleMs>0&&this.inUse.size){let n=i-this.checkoutIdleMs;for(let r of this.inUse)if(!r.closed&&r.lastActivityAt>0&&r.lastActivityAt<=n)r.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&qf.get(this.key)===this)qf.delete(this.key)}}}var qf=new Map;function re(i,t){let n=qf.get(i);if(!n){let r=i.lastIndexOf(":"),f=r===-1?i:i.slice(0,r),c=r===-1?80:Number(i.slice(r+1));n=new Ph(f,c,t,i),qf.set(i,n)}return n}function kh(i,t,n){for(let r=n+3;r<t;r++)if(i[r]===10&&i[r-1]===13&&i[r-2]===10&&i[r-3]===13)return r-3;return-1}function fe(i,t,n){let r=Dh.decode(i.subarray(t,n)),f=r.indexOf(`\r
172
+ `,$=D(wl.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),yl(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)J.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)J.warn(`Could not trust certificate: ${h}`)}else try{await Ac(y,c.certificate,n),u=!0}catch(h){if(i.verbose)J.warn(`Could not add certificate to trust store: ${h}`)}if(Rt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)J.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)J.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),J.warn("This will bypass the warning and you should only need to do it once")}function Al(){Rt=null}async function Tl(i){if(!i)return null;if(Rt)return Rt;let t=El(i);try{let[n,r,f]=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(!n||!r)return Y("ssl",`Certificate files don't exist: key=${n}, cert=${r}, 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(en(),".stacks","ssl"),u=$l(w);if(!(y?await Mh(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"),f&&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(Gf(i))try{let{X509Certificate:e}=await import("node:crypto"),B=new e(A).subjectAltName||"",U=i.proxies.map((W)=>W.to).filter((W)=>!B.includes(`DNS:${W}`));if(U.length>0)return Y("ssl",`Certificate missing SANs for: ${U.join(", ")}, will regenerate`,i.verbose),null}catch(e){Y("ssl",`Could not verify cert SANs: ${e}`,i.verbose)}return Y("ssl","Successfully loaded existing certificates",i.verbose),Rt={key:$,cert:A,ca:T},Rt}catch(n){return Y("ssl",`Error checking existing certificates: ${n}`,i.verbose),null}}function El(i,t){let n=ul(i);Y("ssl",`Primary domain: ${n}`,t);let r=zh(i),f=D(en(),".stacks","ssl");if(typeof i.https==="object"){let c=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,l={domain:n,hostCertCN:n,basePath:c,caCertPath:i.https.caCertPath||r.caCertPath,certPath:i.https.certPath||r.certPath,keyPath:i.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||n,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(Sh(i)).map((y)=>({type:2,value:y}))};if(ah(i.https.rootCA))l.rootCA=i.https.rootCA;return l}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Sh(i)).map((c)=>({type:2,value:c}))}}async function MR(i,t){let n=zh({to:i,verbose:t}),r=[n.caCertPath,n.certPath,n.keyPath];Y("certificates","Attempting to clean up relating certificates",t),await Promise.all(r.map((f)=>Fh(f,t)))}async function Mh(i,t){try{if(Y("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),si.platform==="darwin"){if(t?.serverName)return Ln(i,t.serverName,{verbose:t?.verbose});return sn(i,{verbose:t?.verbose})}else if(si.platform==="win32")try{let n=nl(i)||"";if(!n)return Y("ssl","Could not extract certificate subject",t?.verbose),!1;let r=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(yl(r).toString().includes(n))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(n){return Y("ssl",`Error checking certificate trust on Windows: ${n}`,t?.verbose),!1}else if(si.platform==="linux")try{let n=Qt(i);if(!n)return Y("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let r=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of r){let c;try{c=await Z.readdir(f)}catch{continue}for(let l of c){let y=Qt(Ih.join(f,l));if(y&&y===n)return Y("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return Y("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(n){return Y("ssl",`Error checking certificate trust on Linux: ${n}`,t?.verbose),!1}return Y("ssl",`Platform ${si.platform} not supported for certificate trust check`,t?.verbose),!1}catch(n){return Y("ssl",`Error checking if certificate is trusted: ${n}`,t?.verbose),!1}}function IB(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 KB(i){return(Array.isArray(i)?i:[i]).map((n)=>{let r=typeof n==="string"?{url:n}:n;return{url:r.url,weight:r.weight&&r.weight>0?r.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Oh(i){return(Array.isArray(i)?i:[i]).map((n)=>typeof n==="string"?n:n.url)}function Gh(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 Hh(i,t){return{upstreams:KB(i),strategy:t?.strategy??"round-robin",healthCheck:IB(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function _B(i){let t=i.upstreams.filter((n)=>n.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function zB(i,t){let n=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[n]}function QB(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let n=t.reduce((f,c)=>f+c.weight,0),r=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[r])r=f;return i.wrrCurrentWeights[r]-=n,t[r]}function MB(i){let t=i[0];for(let n=1;n<i.length;n++)if(i[n].activeConnections<t.activeConnections)t=i[n];return t}function qh(i){let t=_B(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return QB(i,t);case"least-connections":return MB(t);case"round-robin":default:return zB(i,t)}}function Hf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function xn(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function OB(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let n=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(n)?n:80}}async function GB(i,t){let{hostname:n,port:r}=OB(t.url),f=new AbortController,c=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${n}:${r}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Hf(i,t)}catch{xn(i,t)}finally{clearTimeout(c)}}function gh(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let n of i.upstreams)GB(i,n)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function Yl(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as sh,timingSafeEqual as Lh}from"node:crypto";import{readFileSync as HB}from"node:fs";var qB="/.well-known/acme-challenge/";function kn(i,t){let n=Buffer.from(i,"utf8"),r=Buffer.from(t,"utf8");if(n.length!==r.length)return Lh(n,n),!1;return Lh(n,r)}function gB(i,t){let n=(A)=>sh("md5").update(A).digest(),r=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),c=n(Buffer.concat([r,f,r])),l=[r,Buffer.from("$apr1$","utf8"),f];for(let A=r.length;A>0;A-=16)l.push(c.subarray(0,Math.min(A,16)));for(let A=r.length;A>0;A>>=1)l.push(A&1?Buffer.from([0]):r.subarray(0,1));let y=n(Buffer.concat(l));for(let A=0;A<1000;A++){let T=[];if(T.push(A&1?r:y.subarray(0,16)),A%3)T.push(f);if(A%7)T.push(r);T.push(A&1?y.subarray(0,16):r),y=n(Buffer.concat(T))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",u=(A,T)=>{let e="",E=A;for(let B=0;B<T;B++)e+=w[E&63],E>>=6;return e},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 LB(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let r=t.split("$")[2]??"";return kn(gB(i,r),t)}if(t.startsWith("{SHA}")){let n=sh("sha1").update(i,"utf8").digest("base64");return kn(`{SHA}${n}`,t)}return kn(i,t)}function sB(i){let t=new Map;for(let n of i.split(`
173
+ `)){let r=n.trim();if(!r||r.startsWith("#"))continue;let f=r.indexOf(":");if(f<=0)continue;t.set(r.slice(0,f),r.slice(f+1))}return t}function xh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",n=[];if(i.username)n.push({username:i.username,password:i.password??""});for(let c of i.users??[])if(c?.username)n.push({username:c.username,password:c.password??""});let r;if(i.htpasswdFile)try{r=sB(HB(i.htpasswdFile,"utf8"))}catch{r=void 0}if(n.length===0&&(!r||r.size===0))return;return{realm:t,verify:(c,l)=>{let y=!1;for(let w of n)if(kn(c,w.username)&&kn(l,w.password))y=!0;if(r){let w=r.get(c);if(w&&LB(l,w))y=!0}return y}}}function kh(i,t,n){if(t.startsWith(qB))return;let r=i.headers.get("authorization")??"",f=r.indexOf(" "),c=f===-1?r:r.slice(0,f),l=f===-1?"":r.slice(f+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&&n.verify(w.slice(0,u),w.slice(u+1)))return}let y=n.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:xB}=Bun,Vn=Symbol("rpx.pool.fallback"),qf=Symbol("rpx.pool.stale");var kB=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function VB(i){return kB.has(i.toUpperCase())}var el=Symbol("rpx.pool.timeout"),Mt=Symbol("rpx.pool.busy");function dB(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function DB(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function bB(){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 dh=1048576;function ZB(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var Bl=30000,vB=16384,Dh=262144,oB=2097152,pB=524288,ie=8192,te=4096,ne=new TextEncoder,bh=new TextDecoder,re=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(vB);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,n=t.write(i);while(n<i.length){if(this.closed)throw qf;await new Promise((r)=>{this.drainWaiter=r}),n+=t.write(i.subarray(n))}}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()>oB)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=pB)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 n=new Uint8Array(Math.max(this.buf.length*2,t));n.set(this.buf.subarray(0,this.len)),this.buf=n}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 Zh{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=dB();maxWaiters;checkoutIdleMs=bB();inUse=new Set;constructor(i,t,n,r=""){this.host=i;this.port=t;this.maxTotal=n;this.key=r;this.maxWaiters=DB(n)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new Ph;return xB({hostname:this.host,port:this.port,socket:{data:(t,n)=>i.push(n),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let n=t;n.setNoDelay?.(!0);let r=PB();if(r>0)n.timeout?.(r);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,n=(c)=>{if(t)return;t=!0,clearTimeout(f),i(c)},r=(c)=>n(c),f=setTimeout(()=>{let c=this.waiters.indexOf(r);if(c!==-1)this.waiters.splice(c,1);n(Mt)},this.queueWaitMs);f.unref?.(),this.waiters.push(r)})}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(Bl,this.checkoutIdleMs):Bl;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-Bl;if(this.idle.length){let n=[];for(let r of this.idle)if(r.closed||r.idleSince<=t)r.destroy(),this.open--;else n.push(r);this.idle=n}if(this.checkoutIdleMs>0&&this.inUse.size){let n=i-this.checkoutIdleMs;for(let r of this.inUse)if(!r.closed&&r.lastActivityAt>0&&r.lastActivityAt<=n)r.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&gf.get(this.key)===this)gf.delete(this.key)}}}var gf=new Map;function fe(i,t){let n=gf.get(i);if(!n){let r=i.lastIndexOf(":"),f=r===-1?i:i.slice(0,r),c=r===-1?80:Number(i.slice(r+1));n=new Zh(f,c,t,i),gf.set(i,n)}return n}function Vh(i,t,n){for(let r=n+3;r<t;r++)if(i[r]===10&&i[r-1]===13&&i[r-2]===10&&i[r-3]===13)return r-3;return-1}function ce(i,t,n){let r=bh.decode(i.subarray(t,n)),f=r.indexOf(`\r
174
174
  `),c=f===-1?r:r.slice(0,f),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,e=!1,E=f===-1?r.length:f+2;while(E<r.length){let B=r.indexOf(`\r
175
- `,E);if(B===-1)B=r.length;let C=r.slice(E,B);if(E=B+2,C==="")continue;let U=C.indexOf(":");if(U===-1)continue;let W=C.slice(0,U),S=C.slice(U+1).trim(),R=W.charCodeAt(0)|32;if(R===99||R===116||R===107){let a=W.toLowerCase();if(a==="content-length"){let G=/^\d+$/.test(S)?Number(S):Number.NaN;if(!Number.isSafeInteger(G)||h>=0&&h!==G)e=!0;else h=G;continue}if(a==="transfer-encoding"){if(S.toLowerCase().includes("chunked"))$=!0;continue}if(a==="connection"){let G=S.toLowerCase();if(G.includes("close"))A=!0;if(G.includes("keep-alive"))T=!0;continue}if(a==="keep-alive")continue}u.push([W,S])}if(w&&T)A=!1;if($&&h>=0)h=-1;return{status:y,headerEnd:n,headers:u,contentLength:h,chunked:$,closeConn:A,malformed:e}}function ce(i,t){return t||i===204||i===304}async function Zh(i){let{hostPort:t,method:n,path:r,reqHeaders:f,forwardedHost:c,originOverride:l,body:y}=i,w=n==="HEAD";if(f.get("expect")||f.get("upgrade"))throw Vn;let u=null;if(y){let T=f.get("content-length"),e=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(e)||e>Vh)throw Vn;if(u=await Ae(y),u===null)throw Vn}let h=$e(n,r,f,t,c,l,u),$=h;if(u&&u.length)$=new Uint8Array(h.length+u.length),$.set(h),$.set(u,h.length);let A=re(t,i.maxPerHost??PB());for(let T=0;;T++){if(T>0)await new Promise((E)=>{setTimeout(E,T)});let e;try{e=A.acquireIdleSync()??await A.acquireOrDial()}catch(E){if(E!==Mt&&T<4)continue;throw E}try{let E=e.socket.write($);if(E<$.length)await e.writeAll($.subarray(E));return await ye(A,e,w)}catch(E){let B=E===Hf&&T<4&&(e.fresh||kB(n));if(A.destroy(e),B)continue;if(E===Hf)throw Error("upstream closed connection");throw E}}}async function le(i){let t=kh(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw Bl;if(i.len===i.pos)throw Hf;throw Error("upstream closed mid-header")}if(i.len-i.pos>dh)throw Error("upstream header block too large");await i.waitForData(i.len),t=kh(i.buf,i.len,i.pos)}return t}async function ye(i,t,n){let r;for(;;){let c=await le(t);if(r=fe(t.buf,t.pos,c),t.pos=c+4,r.status>=100&&r.status<200)continue;break}if(r.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=r.headers;if(ce(r.status,n))return vh(i,t,r.closeConn),new Response(null,{status:r.status,headers:f});if(r.chunked)return new Response(he(i,t,r.closeConn),{status:r.status,headers:f});if(r.contentLength>=0){if(t.len-t.pos>=r.contentLength){let l=t.pos+r.contentLength,y=t.len>l,w=null;if(r.contentLength>=pB)w=t.buf.subarray(t.pos,l),t.buf=new Uint8Array(ie);else if(r.contentLength>0)w=t.buf.slice(t.pos,l);if(t.pos=0,t.len=0,r.closeConn||y)i.destroy(t);else i.release(t);return new Response(w,{status:r.status,headers:f})}return new Response(we(i,t,r.contentLength,r.closeConn),{status:r.status,headers:f})}return new Response(ue(t),{status:r.status,headers:f})}function vh(i,t,n){if(n||t.pos!==t.len)i.destroy(t);else i.release(t)}function we(i,t,n,r){let f=t.len-t.pos,c=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=n-f,t.queuedBytes=0,t.streamingBody=!0;let l=(y)=>{if(t.bodyQueue=null,r||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 ue(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 he(i,t,n){t.streamingBody=!0;let r=0,f=!1;async function c(){for(;;){for(let l=t.pos;l+1<t.len;l++)if(t.buf[l]===13&&t.buf[l+1]===10){let y=Dh.decode(t.buf.subarray(t.pos,l));return t.pos=l+2,y}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>dh)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(l){for(;;){if(r>0){if(t.len===t.pos){if(t.closed){i.destroy(t),l.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let h=Math.min(r,t.len-t.pos);if(l.enqueue(t.buf.slice(t.pos,t.pos+h)),t.pos+=h,r-=h,t.resumeIfDrained(),r===0)f=!0;return}if(f)await c(),f=!1;let y=await c(),w=y.indexOf(";"),u=Number.parseInt(w===-1?y:y.slice(0,w),16);if(!Number.isInteger(u)||u<0){i.destroy(t),l.error(Error("upstream sent malformed chunk size"));return}if(u===0){for(;;)if(await c()==="")break;vh(i,t,n),l.close();return}r=u}},cancel(){i.destroy(t)}})}function $e(i,t,n,r,f,c,l){let y=`${i} ${t} HTTP/1.1\r
175
+ `,E);if(B===-1)B=r.length;let C=r.slice(E,B);if(E=B+2,C==="")continue;let U=C.indexOf(":");if(U===-1)continue;let W=C.slice(0,U),S=C.slice(U+1).trim(),R=W.charCodeAt(0)|32;if(R===99||R===116||R===107){let a=W.toLowerCase();if(a==="content-length"){let G=/^\d+$/.test(S)?Number(S):Number.NaN;if(!Number.isSafeInteger(G)||h>=0&&h!==G)e=!0;else h=G;continue}if(a==="transfer-encoding"){if(S.toLowerCase().includes("chunked"))$=!0;continue}if(a==="connection"){let G=S.toLowerCase();if(G.includes("close"))A=!0;if(G.includes("keep-alive"))T=!0;continue}if(a==="keep-alive")continue}u.push([W,S])}if(w&&T)A=!1;if($&&h>=0)h=-1;return{status:y,headerEnd:n,headers:u,contentLength:h,chunked:$,closeConn:A,malformed:e}}function le(i,t){return t||i===204||i===304}async function vh(i){let{hostPort:t,method:n,path:r,reqHeaders:f,forwardedHost:c,originOverride:l,body:y}=i,w=n==="HEAD";if(f.get("expect")||f.get("upgrade"))throw Vn;let u=null;if(y){let T=f.get("content-length"),e=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(e)||e>dh)throw Vn;if(u=await Te(y),u===null)throw Vn}let h=Ae(n,r,f,t,c,l,u),$=h;if(u&&u.length)$=new Uint8Array(h.length+u.length),$.set(h),$.set(u,h.length);let A=fe(t,i.maxPerHost??ZB());for(let T=0;;T++){if(T>0)await new Promise((E)=>{setTimeout(E,T)});let e;try{e=A.acquireIdleSync()??await A.acquireOrDial()}catch(E){if(E!==Mt&&T<4)continue;throw E}try{let E=e.socket.write($);if(E<$.length)await e.writeAll($.subarray(E));return await we(A,e,w)}catch(E){let B=E===qf&&T<4&&(e.fresh||VB(n));if(A.destroy(e),B)continue;if(E===qf)throw Error("upstream closed connection");throw E}}}async function ye(i){let t=Vh(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw el;if(i.len===i.pos)throw qf;throw Error("upstream closed mid-header")}if(i.len-i.pos>Dh)throw Error("upstream header block too large");await i.waitForData(i.len),t=Vh(i.buf,i.len,i.pos)}return t}async function we(i,t,n){let r;for(;;){let c=await ye(t);if(r=ce(t.buf,t.pos,c),t.pos=c+4,r.status>=100&&r.status<200)continue;break}if(r.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=r.headers;if(le(r.status,n))return oh(i,t,r.closeConn),new Response(null,{status:r.status,headers:f});if(r.chunked)return new Response($e(i,t,r.closeConn),{status:r.status,headers:f});if(r.contentLength>=0){if(t.len-t.pos>=r.contentLength){let l=t.pos+r.contentLength,y=t.len>l,w=null;if(r.contentLength>=ie)w=t.buf.subarray(t.pos,l),t.buf=new Uint8Array(te);else if(r.contentLength>0)w=t.buf.slice(t.pos,l);if(t.pos=0,t.len=0,r.closeConn||y)i.destroy(t);else i.release(t);return new Response(w,{status:r.status,headers:f})}return new Response(ue(i,t,r.contentLength,r.closeConn),{status:r.status,headers:f})}return new Response(he(t),{status:r.status,headers:f})}function oh(i,t,n){if(n||t.pos!==t.len)i.destroy(t);else i.release(t)}function ue(i,t,n,r){let f=t.len-t.pos,c=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=n-f,t.queuedBytes=0,t.streamingBody=!0;let l=(y)=>{if(t.bodyQueue=null,r||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 he(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 $e(i,t,n){t.streamingBody=!0;let r=0,f=!1;async function c(){for(;;){for(let l=t.pos;l+1<t.len;l++)if(t.buf[l]===13&&t.buf[l+1]===10){let y=bh.decode(t.buf.subarray(t.pos,l));return t.pos=l+2,y}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>Dh)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(l){for(;;){if(r>0){if(t.len===t.pos){if(t.closed){i.destroy(t),l.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let h=Math.min(r,t.len-t.pos);if(l.enqueue(t.buf.slice(t.pos,t.pos+h)),t.pos+=h,r-=h,t.resumeIfDrained(),r===0)f=!0;return}if(f)await c(),f=!1;let y=await c(),w=y.indexOf(";"),u=Number.parseInt(w===-1?y:y.slice(0,w),16);if(!Number.isInteger(u)||u<0){i.destroy(t),l.error(Error("upstream sent malformed chunk size"));return}if(u===0){for(;;)if(await c()==="")break;oh(i,t,n),l.close();return}r=u}},cancel(){i.destroy(t)}})}function Ae(i,t,n,r,f,c,l){let y=`${i} ${t} HTTP/1.1\r
176
176
  host: ${r}\r
177
177
  x-forwarded-for: 127.0.0.1\r
178
178
  x-forwarded-proto: https\r
179
179
  x-forwarded-host: ${f}\r
180
180
  `;if(c!==void 0)y+=`origin: ${c}\r
181
- `;let w=!1;for(let[u,h]of n){let $=u.toLowerCase();if(ne.has($))continue;if(c!==void 0&&$==="origin")continue;if($==="content-length")w=!0;y+=`${u}: ${h}\r
181
+ `;let w=!1;for(let[u,h]of n){let $=u.toLowerCase();if(re.has($))continue;if(c!==void 0&&$==="origin")continue;if($==="content-length")w=!0;y+=`${u}: ${h}\r
182
182
  `}if(y+=`connection: keep-alive\r
183
183
  `,l&&!w)y+=`content-length: ${l.length}\r
184
184
  `;return y+=`\r
185
- `,te.encode(y)}async function Ae(i){let t=i.getReader(),n=[],r=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(r+=y.length,r>Vh)return t.cancel().catch(()=>{}),null;n.push(y)}}if(n.length===1)return n[0];let f=new Uint8Array(r),c=0;for(let l of n)f.set(l,c),c+=l.length;return f}function xR(i){let t=typeof i==="string"?{to:i}:i,n=(t.to??"").trim();if(n&&!/^[a-z][\w+.-]*:\/\//i.test(n))n=`https://${n}`;return n=n.replace(/\/+$/,""),{to:n,status:t.status??301,preservePath:t.preservePath??!0}}function oh(i,t,n){if(!i.preservePath)return i.to||"/";let r=`${t}${n}`;return r==="/"?`${i.to}/`:`${i.to}${r}`}import*as Qi from"node:path";function ph(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 Te={".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 Ee(i){let t=Qi.extname(i).toLowerCase();return Te[t]??"application/octet-stream"}function Ye(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let n=Qi.posix.normalize(`/${t}`);if(n.split("/").includes(".."))return null;return n.replace(/^\/+/,"")}function Be(i,t){let n=Ye(i);if(n===null)return null;let r=Qi.posix.extname(n);if(t.cleanUrls&&r===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Qi.join(t.dir,n),redirectTo:f||"/"}}if(n===""||i.endsWith("/"))return{filePath:Qi.join(t.dir,n,"index.html")};if(r!=="")return{filePath:Qi.join(t.dir,n)};if(t.pathRewriteStyle==="flat")return{filePath:Qi.join(t.dir,`${n}.html`)};return{filePath:Qi.join(t.dir,n,"index.html")}}async function i$(i,t){let n=Be(i,t);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(n.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":Ee(n.filePath),"Cache-Control":r}});if(t.spa){let c=Qi.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 ee(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var Ce=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function me(i){let t=i.headers.get("host")||"",n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function f$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let n=i.slice(t.length);return n===""?"/":n}return i}function t$(i){if(i.upstreamPool)return Hh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function n$(i,t,n,r){let f=n?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?f$(i,t.basePath):i,y=r$(l,t.pathRewrites);if(y)f=y.targetHost,l=y.targetPath,Y("request",`Path rewrite: ${i} → ${f}${l}`,r);return{targetHost:f,targetPath:l}}function Ue(i){let t=i.indexOf("://"),n=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(n===-1)return{pathname:"/",search:""};let r=i.indexOf("?",n);if(r===-1)return{pathname:i.slice(n),search:""};return{pathname:i.slice(n,r),search:i.slice(r)}}function el(i,t,n){let r=async(f,c)=>{let{pathname:l,search:y}=Ue(f.url),w=me(f),u=i(w,l);if(!u&&n){let B=await n(w,l,f);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=xh(f,l,u.auth);if(B)return Y("request",`401 challenge for ${w}${l}`,t),B}if(u.redirect){let B=oh(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 C=u.stripBasePathPrefix??!0?f$(l,u.basePath):l;return i$(C,u.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let B=t$(u);if(!c||!B)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:C,targetPath:U}=n$(l,u,B,t),W=`ws://${C}${U}${y}`,S={};for(let[G,o]of f.headers)if(!Ce.has(G.toLowerCase())&&G.toLowerCase()!=="host")S[G]=o;S.host=C,S["x-forwarded-for"]="127.0.0.1",S["x-forwarded-proto"]="https",S["x-forwarded-host"]=w;let R={targetUrl:W,forwardHeaders:S};if(c.upgrade(f,{data:R})){Y("ws",`upgraded ${w}${U} → ${W}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=t$(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}=n$(l,u,h,t),T=u.changeOrigin?`http://${$}`:void 0,e=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=u.upstreamPool;if(E)h.activeConnections++;try{let B=await Zh({hostPort:$,method:f.method,path:`${A}${y}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body});if(E)Gf(E,h);return B}catch(B){if(B===Bl){if(Y("request",`Upstream timeout for ${w}`,t),E)xn(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===Vn||!e)try{let C=new Headers(f.headers);if(C.set("host",$),C.set("x-forwarded-for","127.0.0.1"),C.set("x-forwarded-proto","https"),C.set("x-forwarded-host",w),T!==void 0)C.set("origin",T);let U=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:C,body:f.body,redirect:"manual"});if(E)Gf(E,h);return U}catch(C){if(Y("request",`Proxy error for ${w}: ${C}`,t),E)xn(E,h);return new Response(`Proxy Error: ${C}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)xn(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)h.activeConnections--}};return async(f,c)=>{try{return await r(f,c)}catch(l){return Y("request",`Unhandled proxy handler error: ${l}`,t),new Response("Bad Gateway",{status:502})}}}function Cl(i){let t=new WeakMap,n=ee();return{open(r){let{targetUrl:f,forwardHeaders:c}=r.data,l;try{l=new WebSocket(f,{headers:c})}catch(w){Y("ws",`failed to open upstream ${f}: ${w}`,i),r.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(r,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)=>{r.send(w.data)}),l.addEventListener("close",(w)=>{try{r.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{Y("ws",`upstream error for ${f}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,f){let c=t.get(r);if(!c)return;let l=typeof f==="string"?f:new Uint8Array(f);if(c.upstreamOpen){c.upstream.send(l);return}let y=typeof l==="string"?Buffer.byteLength(l):l.byteLength;if(c.pendingBytes+y>n){Y("ws",`pending buffer would exceed ${n}B before upstream open; closing socket`,i);try{r.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(r);return}c.pending.push(l),c.pendingBytes+=y},close(r,f,c){let l=t.get(r);if(!l)return;t.delete(r);try{l.upstream.close(f||1000,c||"")}catch{}}}}import*as l$ from"node:fs";import*as y$ from"node:path";var c$="/.well-known/acme-challenge/";function w$(i,t){if(!i||!t.startsWith(c$))return null;let n=t.slice(c$.length);if(!n||!/^[A-Za-z0-9_-]+$/.test(n))return null;try{return l$.readFileSync(y$.join(i,n),"utf8")}catch{return null}}function gf(i){return i.startsWith("*.")}function ml(i,t){if(!gf(t))return!1;let n=t.slice(1);return i.length>n.length&&i.endsWith(n)}function u$(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!gf(c))continue;if(ml(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Ot(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function je(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Ul(i){let t=new Map;for(let r of i){let f=Ot(r.path),c=t.get(r.host);if(!c)c=new Map,t.set(r.host,c);c.set(f,r.route)}let n=new Map;for(let[r,f]of t){let c=[];for(let[l,y]of f)c.push({path:l,route:y});c.sort((l,y)=>y.path.length-l.path.length),n.set(r,c)}return n}function jl(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!gf(c))continue;if(ml(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Nl(i,t,n){let r=jl(i,t);if(!r)return;for(let f of r)if(je(n,f.path))return f.route;return}import*as dn from"node:fs/promises";import*as Rl from"node:path";function Ne(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 Re(i,t,n,r){try{let[f,c]=await Promise.all([dn.readFile(t,"utf8"),dn.readFile(n,"utf8")]);return{serverName:i,cert:f,key:c}}catch(f){return Y("sni",`skipping ${i}: ${f.message}`,r),null}}async function Xl(i,t){let n=new Map;if(i.certsDir){let f=[];try{f=await dn.readdir(i.certsDir)}catch(c){Y("sni",`certsDir read failed (${i.certsDir}): ${c.message}`,t)}for(let c of f){let l=Ne(c);if(!l)continue;let y=c.slice(0,-4);n.set(l,{certPath:Rl.join(i.certsDir,c),keyPath:Rl.join(i.certsDir,`${y}.key`)})}}if(i.domains)for(let[f,c]of Object.entries(i.domains))n.set(f,c);let r=[];for(let[f,c]of n){let l=await Re(f,c.certPath,c.keyPath,t);if(l)r.push(l)}return r}import*as Xt from"node:fs/promises";import*as Wl from"node:path";var Xe=60000,h$=4096;function We(i,t){if(!t||t.length===0)return!1;return t.some((n)=>{let r=n.startsWith(".")?n.slice(1):n;return i===r||i.endsWith(`.${r}`)})}function $$(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 sf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??xr,this.issuer=i.issuer??d0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??Xe;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(!$$(i))return!1;if(We(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(!$$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let n=this.negativeCache.get(i);if(n!==void 0&&Date.now()<n){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return Y("on-demand",`${i} negatively cached for ${n-Date.now()}ms`,this.verbose),!1}let r=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,r),r}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);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let n={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,n),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>=h$){let t=Date.now();for(let[n,r]of this.negativeCache)if(r<=t)this.negativeCache.delete(n);if(this.negativeCache.size>=h$){let n=this.negativeCache.keys().next().value;if(n!==void 0)this.negativeCache.delete(n)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:n}=this.pathsFor(i);try{let[r,f]=await Promise.all([Xt.readFile(t,"utf8"),Xt.readFile(n,"utf8")]),c={serverName:i,cert:r,key:f};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:Wl.join(this.certsDir,`${i}.crt`),keyPath:Wl.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await Xt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([Xt.writeFile(r,t,"utf8"),Xt.writeFile(f,n,{encoding:"utf8",mode:384})])}}import{existsSync as Se,readdirSync as ae,readFileSync as Je,statSync as Fe}from"node:fs";import{homedir as E$}from"node:os";import{isAbsolute as Ie,join as Cn}from"node:path";var Y$=["~/Code"],B$=["localhost","test"],Ke=1800000,Sl={dirExists:(i)=>{try{return Fe(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return Se(i)}catch{return!1}},readText:(i)=>{try{return Je(i,"utf8")}catch{return null}}};function al(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Cn(t,i.slice(2));return i}function _e(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function A$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function ze(i,t){for(let n of t){let r=`.${n}`;if(i.endsWith(r)){let f=i.slice(0,-r.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function Qe(i,t){let n=t.readText(Cn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(Cn(i,"package.json"));if(r)try{let f=JSON.parse(r);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function Me(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 Oe(i,t){let n=Qe(i,t);if(n?.command)return Me(n);let r=t.fileExists(Cn(i,"buddy")),f=t.readText(Cn(i,"package.json")),c=null;if(f)try{c=JSON.parse(f)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(r||Object.keys(l).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:r?"./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 Jl(i,t={}){let n={dirExists:t.dirExists??Sl.dirExists,fileExists:t.fileExists??Sl.fileExists,readText:t.readText??Sl.readText},r=t.detect??Oe,f=t.homeDir??E$(),c=i.tlds??B$,l=(i.roots??Y$).map((A)=>al(A,f)),y=i.idleTimeoutMs??Ke,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=u$(w,A);if(!T)return null;let e=Ie(T.dir)?T.dir:al(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=r(e,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let C=T$({...T.env??{}},void 0,A);return{host:A,id:A$(A),dir:e,command:T.command,env:C,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=ze(A,c);if(!T)return null;for(let e of l){let E=Cn(e,T);if(!n.dirExists(E))continue;let B=r(E,n);if(!B)continue;let C=B.selfRegisters??!1;return{host:A,id:A$(A),dir:E,command:B.command,env:T$({...B.env??{}},B.urlEnv,A),routes:C?[]:B.routes??[],selfRegisters:C,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=_e(A);if(!T)return null;return h(T)??$(T)}}}function Ge(i){try{return ae(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function AX(i,t={}){let n=t.homeDir??E$(),r=i.tlds??B$,f=(i.roots??Y$).map(($)=>al($,n)),c=t.readdir??Ge,l=Jl(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=r[0]??"localhost";for(let $ of f)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function T$(i,t,n){if(!t)return i;let r=`https://${n}`;for(let f of t)if(i[f]===void 0)i[f]=r;return i}import{closeSync as N$,openSync as Le,readFileSync as xe}from"node:fs";import*as R$ from"node:fs/promises";import{spawn as ke}from"node:child_process";import{homedir as Ve}from"node:os";import*as bn from"node:path";import*as xi from"node:process";import*as Lf from"node:net";function C$(i,t,n){return Y("port",`Checking if port ${i} is in use on ${t}`,n),new Promise((r)=>{let f=Lf.createServer(),c=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,n),r(!0);else Y("port",`Error checking port ${i}: ${l.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(c),Y("port",`Port ${i} is available`,n),f.close(),r(!1)});try{f.listen(i,t)}catch(l){clearTimeout(c),Y("port",`Exception checking port ${i}: ${l}`,n),r(!0)}})}async function Fl(i,t,n,r=50){Y("port",`Finding available port starting from ${i} (max attempts: ${r})`,n);let f=i,c=0;while(c<r){if(c++,!await C$(f,t,n))return Y("port",`Found available port: ${f} after ${c} attempts`,n),f;Y("port",`Port ${f} is in use, trying ${f+1} (attempt ${c}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${i}`)}function e$(i,t,n=5000,r){return Y("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let c=Lf.connect({host:t,port:i,timeout:n});c.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,r),c.end(),f(!0)}),c.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,r),c.destroy(),f(!1)}),c.once("error",(l)=>{Y("port",`Failed to connect to ${t}:${i}: ${l.message}`,r),c.destroy(),f(!1)})})}class m${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,n=50){this.hostname=i,this.verbose=t,this.maxRetries=n}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await C$(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await e$(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 n=await Fl(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await e$(n,this.hostname,3000,this.verbose))if(n<i+this.maxRetries)return this.findNextAvailablePort(n+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var YX=new m$;import*as xf from"node:fs";import*as mi from"node:fs/promises";import{homedir as He}from"node:os";import*as Il from"node:path";import*as kf from"node:process";var qe=/^[a-zA-Z0-9._-]+$/;function Wt(){return Il.join(He(),".stacks","rpx","registry.d")}function Kl(i){return typeof i==="string"&&i.length>0&&i.length<=128&&qe.test(i)}function _l(i,t){if(!Kl(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Il.join(i,`${t}.json`)}function Ui(i){if(!Number.isInteger(i)||i<=0)return!1;try{return kf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function U$(i){if(!i||typeof i!=="object")return!1;let t=i,n=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,r=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=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"&&Kl(t.id)&&(r||f)&&typeof t.to==="string"&&t.to.length>0&&c&&n&&typeof t.createdAt==="string"}async function ge(i){await mi.mkdir(i,{recursive:!0})}async function j$(i,t=Wt(),n){if(!U$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await ge(t);let r=_l(t,i.id),f=`${r}.tmp.${kf.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await mi.writeFile(f,c,{encoding:"utf8",mode:420}),await mi.rename(f,r),Y("registry",`wrote entry ${i.id} → ${r}`,n)}catch(l){throw await mi.unlink(f).catch(()=>{}),l}}async function zl(i,t=Wt(),n){let r=_l(t,i);try{await mi.unlink(r),Y("registry",`removed entry ${i}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function se(i,t=Wt(),n){let r=_l(t,i);try{let f=await mi.readFile(r,"utf8"),c=JSON.parse(f);if(!U$(c))return Y("registry",`entry ${i} failed validation, removing`,n),await mi.unlink(r).catch(()=>{}),null;return c}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return Y("registry",`entry ${i} has invalid JSON, removing`,n),await mi.unlink(r).catch(()=>{}),null;throw f}}async function Tt(i=Wt(),t){let n;try{n=await mi.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let c=f.slice(0,-5);if(!Kl(c))continue;let l=await se(c,i,t);if(l)r.push(l)}return r}async function Dn(i=Wt(),t){let n=await Tt(i,t),r=0;for(let f of n){if(f.pid===void 0)continue;if(!Ui(f.pid))Y("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await zl(f.id,i,t).catch(()=>{}),r++}return r}function Vf(i,t={}){let n=t.dir??Wt(),r=t.debounceMs??100,f=t.pollMs??Math.max(r*2,250),c=t.verbose;xf.mkdirSync(n,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((C)=>({id:C.id,from:C.from,to:C.to,path:C.path,pid:C.pid,pathRewrites:C.pathRewrites,cleanUrls:C.cleanUrls,changeOrigin:C.changeOrigin,static:C.static,loadBalancer:C.loadBalancer})).sort((C,U)=>C.id.localeCompare(U.id)))},$=()=>{if(l=null,y)return;Tt(n,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($,r)},e=setInterval(()=>{if(y||u)return;u=!0,Tt(n,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=xf.watch(n,{persistent:!0},(B,C)=>{if(C&&/\.tmp\.\d+\.\d+$/.test(C))return;A()});return E.on("error",(B)=>{Y("registry",`watcher error: ${B}`,c)}),A(),{close:()=>{if(y=!0,l)clearTimeout(l);clearInterval(e),E.close()}}}var de=120000,De=200,be=30000,Pe=3000,Ze=4000;class Ml{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??Wt(),this.rpxDir=i.rpxDir??bn.join(Ve(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??de,this.pollIntervalMs=i.pollIntervalMs??De,this.restartDelayMs=i.restartDelayMs??Pe,this.killGraceMs=i.killGraceMs??Ze,this.launch=i.launcher??oe(this.verbose),this.probePort=i.probePort??ve,this.pickPort=i.pickPort??((n)=>Fl(n,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??j$,this.removeEntry=i.removeEntry??zl;let t=i.reapIntervalMs??be;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 n=this.resolver.resolve(i);if(!n)return{kind:"unknown"};t=await this.start(n)}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 n=bn.join(this.rpxDir,"sites",`${i.id}.log`);await R$.mkdir(bn.dirname(n),{recursive:!0}).catch(()=>{});let r=this.buildEnv(i,t),f=null,c;try{f=this.launch({command:i.command,cwd:i.dir,env:r,logPath:n})}catch(y){c=`failed to spawn: ${y.message}`}let l={site:i,status:c?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:c?this.now():0,error:c,logPath:n,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,l),c)return J.warn(`rpx: site ${i.host} ${c}`),l;return J.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.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"){J.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let n of i.routeIds)await this.removeEntry(n,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,n=this.now()+this.startupTimeoutMs,r=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<n&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await r()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",J.success(`rpx: ${t.host} ready`);return}await Ql(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 n=i.routes.filter((f)=>f.readyGate??Ot(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),r=n.length>0?n:[...t.values()];return async()=>{for(let f of r)if(!await this.probePort(f))return!1;return r.length>0}}async publishRoutes(i){let{site:t,ports:n}=i;if(t.selfRegisters||t.routes.length===0)return;let r=t.routes.find((w)=>Ot(w.path)==="/")??t.routes[0],f=n.get(r.portEnv);if(f===void 0)return;let c=[];for(let w of t.routes){if(w===r)continue;let u=n.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:${f}`,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 Ql(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),J.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(xi.env))if(typeof f==="string")n[r]=f;Object.assign(n,i.env);for(let[r,f]of t)n[r]=String(f);return n.RPX_SITE_HOST=i.host,n.RPX_SITE_URL=`https://${i.host}`,n}readLogTail(i,t=40){try{return xe(i.logPath,"utf8").split(`
185
+ `,ne.encode(y)}async function Te(i){let t=i.getReader(),n=[],r=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(r+=y.length,r>dh)return t.cancel().catch(()=>{}),null;n.push(y)}}if(n.length===1)return n[0];let f=new Uint8Array(r),c=0;for(let l of n)f.set(l,c),c+=l.length;return f}function kR(i){let t=typeof i==="string"?{to:i}:i,n=(t.to??"").trim();if(n&&!/^[a-z][\w+.-]*:\/\//i.test(n))n=`https://${n}`;return n=n.replace(/\/+$/,""),{to:n,status:t.status??301,preservePath:t.preservePath??!0}}function ph(i,t,n){if(!i.preservePath)return i.to||"/";let r=`${t}${n}`;return r==="/"?`${i.to}/`:`${i.to}${r}`}import*as Qi from"node:path";function i$(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 Ee={".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 Ye(i){let t=Qi.extname(i).toLowerCase();return Ee[t]??"application/octet-stream"}function Be(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let n=Qi.posix.normalize(`/${t}`);if(n.split("/").includes(".."))return null;return n.replace(/^\/+/,"")}function ee(i,t){let n=Be(i);if(n===null)return null;let r=Qi.posix.extname(n);if(t.cleanUrls&&r===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Qi.join(t.dir,n),redirectTo:f||"/"}}if(n===""||i.endsWith("/"))return{filePath:Qi.join(t.dir,n,"index.html")};if(r!=="")return{filePath:Qi.join(t.dir,n)};if(t.pathRewriteStyle==="flat")return{filePath:Qi.join(t.dir,`${n}.html`)};return{filePath:Qi.join(t.dir,n,"index.html")}}async function t$(i,t){let n=ee(i,t);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(n.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":Ye(n.filePath),"Cache-Control":r}});if(t.spa){let c=Qi.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 Ce(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var me=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function Ue(i){let t=i.headers.get("host")||"",n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function c$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let n=i.slice(t.length);return n===""?"/":n}return i}function n$(i){if(i.upstreamPool)return qh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function r$(i,t,n,r){let f=n?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?c$(i,t.basePath):i,y=f$(l,t.pathRewrites);if(y)f=y.targetHost,l=y.targetPath,Y("request",`Path rewrite: ${i} → ${f}${l}`,r);return{targetHost:f,targetPath:l}}function je(i){let t=i.indexOf("://"),n=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(n===-1)return{pathname:"/",search:""};let r=i.indexOf("?",n);if(r===-1)return{pathname:i.slice(n),search:""};return{pathname:i.slice(n,r),search:i.slice(r)}}function Cl(i,t,n){let r=async(f,c)=>{let{pathname:l,search:y}=je(f.url),w=Ue(f),u=i(w,l);if(!u&&n){let B=await n(w,l,f);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=kh(f,l,u.auth);if(B)return Y("request",`401 challenge for ${w}${l}`,t),B}if(u.redirect){let B=ph(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 C=u.stripBasePathPrefix??!0?c$(l,u.basePath):l;return t$(C,u.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let B=n$(u);if(!c||!B)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:C,targetPath:U}=r$(l,u,B,t),W=`ws://${C}${U}${y}`,S={};for(let[G,o]of f.headers)if(!me.has(G.toLowerCase())&&G.toLowerCase()!=="host")S[G]=o;S.host=C,S["x-forwarded-for"]="127.0.0.1",S["x-forwarded-proto"]="https",S["x-forwarded-host"]=w;let R={targetUrl:W,forwardHeaders:S};if(c.upgrade(f,{data:R})){Y("ws",`upgraded ${w}${U} → ${W}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=n$(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}=r$(l,u,h,t),T=u.changeOrigin?`http://${$}`:void 0,e=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=u.upstreamPool;if(E)h.activeConnections++;try{let B=await vh({hostPort:$,method:f.method,path:`${A}${y}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body});if(E)Hf(E,h);return B}catch(B){if(B===el){if(Y("request",`Upstream timeout for ${w}`,t),E)xn(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===Vn||!e)try{let C=new Headers(f.headers);if(C.set("host",$),C.set("x-forwarded-for","127.0.0.1"),C.set("x-forwarded-proto","https"),C.set("x-forwarded-host",w),T!==void 0)C.set("origin",T);let U=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:C,body:f.body,redirect:"manual"});if(E)Hf(E,h);return U}catch(C){if(Y("request",`Proxy error for ${w}: ${C}`,t),E)xn(E,h);return new Response(`Proxy Error: ${C}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)xn(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)h.activeConnections--}};return async(f,c)=>{try{return await r(f,c)}catch(l){return Y("request",`Unhandled proxy handler error: ${l}`,t),new Response("Bad Gateway",{status:502})}}}function ml(i){let t=new WeakMap,n=Ce();return{open(r){let{targetUrl:f,forwardHeaders:c}=r.data,l;try{l=new WebSocket(f,{headers:c})}catch(w){Y("ws",`failed to open upstream ${f}: ${w}`,i),r.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(r,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)=>{r.send(w.data)}),l.addEventListener("close",(w)=>{try{r.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{Y("ws",`upstream error for ${f}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,f){let c=t.get(r);if(!c)return;let l=typeof f==="string"?f:new Uint8Array(f);if(c.upstreamOpen){c.upstream.send(l);return}let y=typeof l==="string"?Buffer.byteLength(l):l.byteLength;if(c.pendingBytes+y>n){Y("ws",`pending buffer would exceed ${n}B before upstream open; closing socket`,i);try{r.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(r);return}c.pending.push(l),c.pendingBytes+=y},close(r,f,c){let l=t.get(r);if(!l)return;t.delete(r);try{l.upstream.close(f||1000,c||"")}catch{}}}}import*as y$ from"node:fs";import*as w$ from"node:path";var l$="/.well-known/acme-challenge/";function u$(i,t){if(!i||!t.startsWith(l$))return null;let n=t.slice(l$.length);if(!n||!/^[A-Za-z0-9_-]+$/.test(n))return null;try{return y$.readFileSync(w$.join(i,n),"utf8")}catch{return null}}function Lf(i){return i.startsWith("*.")}function Ul(i,t){if(!Lf(t))return!1;let n=t.slice(1);return i.length>n.length&&i.endsWith(n)}function h$(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!Lf(c))continue;if(Ul(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Ot(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function Ne(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function jl(i){let t=new Map;for(let r of i){let f=Ot(r.path),c=t.get(r.host);if(!c)c=new Map,t.set(r.host,c);c.set(f,r.route)}let n=new Map;for(let[r,f]of t){let c=[];for(let[l,y]of f)c.push({path:l,route:y});c.sort((l,y)=>y.path.length-l.path.length),n.set(r,c)}return n}function Nl(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!Lf(c))continue;if(Ul(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Rl(i,t,n){let r=Nl(i,t);if(!r)return;for(let f of r)if(Ne(n,f.path))return f.route;return}import*as dn from"node:fs/promises";import*as Xl from"node:path";function Dn(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function Re(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 Xe(i,t,n,r){try{let[f,c]=await Promise.all([dn.readFile(t,"utf8"),dn.readFile(n,"utf8")]);return{serverName:i,cert:f,key:c}}catch(f){return Y("sni",`skipping ${i}: ${f.message}`,r),null}}async function Wl(i,t){let n=new Map;if(i.certsDir){let f=[];try{f=await dn.readdir(i.certsDir)}catch(c){Y("sni",`certsDir read failed (${i.certsDir}): ${c.message}`,t)}for(let c of f){let l=Re(c);if(!l)continue;let y=c.slice(0,-4);n.set(l,{certPath:Xl.join(i.certsDir,c),keyPath:Xl.join(i.certsDir,`${y}.key`)})}}if(i.domains)for(let[f,c]of Object.entries(i.domains))n.set(f,c);let r=[];for(let[f,c]of n){let l=await Xe(f,c.certPath,c.keyPath,t);if(l)r.push(l)}return r}import*as Xt from"node:fs/promises";import*as Sl from"node:path";var We=60000,$$=4096;function Se(i,t){if(!t||t.length===0)return!1;return t.some((n)=>{let r=n.startsWith(".")?n.slice(1):n;return i===r||i.endsWith(`.${r}`)})}function A$(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 sf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??kr,this.issuer=i.issuer??D0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??We;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(!A$(i))return!1;if(Se(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(!A$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let n=this.negativeCache.get(i);if(n!==void 0&&Date.now()<n){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return Y("on-demand",`${i} negatively cached for ${n-Date.now()}ms`,this.verbose),!1}let r=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,r),r}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);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let n={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,n),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>=$$){let t=Date.now();for(let[n,r]of this.negativeCache)if(r<=t)this.negativeCache.delete(n);if(this.negativeCache.size>=$$){let n=this.negativeCache.keys().next().value;if(n!==void 0)this.negativeCache.delete(n)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:n}=this.pathsFor(i);try{let[r,f]=await Promise.all([Xt.readFile(t,"utf8"),Xt.readFile(n,"utf8")]),c={serverName:i,cert:r,key:f};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:Sl.join(this.certsDir,`${i}.crt`),keyPath:Sl.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await Xt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([Xt.writeFile(r,t,"utf8"),Xt.writeFile(f,n,{encoding:"utf8",mode:384})])}}import{existsSync as ae,readdirSync as Je,readFileSync as Fe,statSync as Ie}from"node:fs";import{homedir as Y$}from"node:os";import{isAbsolute as Ke,join as Cn}from"node:path";var B$=["~/Code"],e$=["localhost","test"],_e=1800000,al={dirExists:(i)=>{try{return Ie(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return ae(i)}catch{return!1}},readText:(i)=>{try{return Fe(i,"utf8")}catch{return null}}};function Jl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Cn(t,i.slice(2));return i}function ze(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function T$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function Qe(i,t){for(let n of t){let r=`.${n}`;if(i.endsWith(r)){let f=i.slice(0,-r.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function Me(i,t){let n=t.readText(Cn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(Cn(i,"package.json"));if(r)try{let f=JSON.parse(r);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function Oe(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 Ge(i,t){let n=Me(i,t);if(n?.command)return Oe(n);let r=t.fileExists(Cn(i,"buddy")),f=t.readText(Cn(i,"package.json")),c=null;if(f)try{c=JSON.parse(f)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(r||Object.keys(l).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:r?"./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 Fl(i,t={}){let n={dirExists:t.dirExists??al.dirExists,fileExists:t.fileExists??al.fileExists,readText:t.readText??al.readText},r=t.detect??Ge,f=t.homeDir??Y$(),c=i.tlds??e$,l=(i.roots??B$).map((A)=>Jl(A,f)),y=i.idleTimeoutMs??_e,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=h$(w,A);if(!T)return null;let e=Ke(T.dir)?T.dir:Jl(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=r(e,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let C=E$({...T.env??{}},void 0,A);return{host:A,id:T$(A),dir:e,command:T.command,env:C,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=Qe(A,c);if(!T)return null;for(let e of l){let E=Cn(e,T);if(!n.dirExists(E))continue;let B=r(E,n);if(!B)continue;let C=B.selfRegisters??!1;return{host:A,id:T$(A),dir:E,command:B.command,env:E$({...B.env??{}},B.urlEnv,A),routes:C?[]:B.routes??[],selfRegisters:C,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=ze(A);if(!T)return null;return h(T)??$(T)}}}function He(i){try{return Je(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function TX(i,t={}){let n=t.homeDir??Y$(),r=i.tlds??e$,f=(i.roots??B$).map(($)=>Jl($,n)),c=t.readdir??He,l=Fl(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=r[0]??"localhost";for(let $ of f)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function E$(i,t,n){if(!t)return i;let r=`https://${n}`;for(let f of t)if(i[f]===void 0)i[f]=r;return i}import{closeSync as R$,openSync as xe,readFileSync as ke}from"node:fs";import*as X$ from"node:fs/promises";import{spawn as Ve}from"node:child_process";import{homedir as de}from"node:os";import*as Pn from"node:path";import*as xi from"node:process";import*as xf from"node:net";function m$(i,t,n){return Y("port",`Checking if port ${i} is in use on ${t}`,n),new Promise((r)=>{let f=xf.createServer(),c=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,n),r(!0);else Y("port",`Error checking port ${i}: ${l.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(c),Y("port",`Port ${i} is available`,n),f.close(),r(!1)});try{f.listen(i,t)}catch(l){clearTimeout(c),Y("port",`Exception checking port ${i}: ${l}`,n),r(!0)}})}async function Il(i,t,n,r=50){Y("port",`Finding available port starting from ${i} (max attempts: ${r})`,n);let f=i,c=0;while(c<r){if(c++,!await m$(f,t,n))return Y("port",`Found available port: ${f} after ${c} attempts`,n),f;Y("port",`Port ${f} is in use, trying ${f+1} (attempt ${c}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${i}`)}function C$(i,t,n=5000,r){return Y("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let c=xf.connect({host:t,port:i,timeout:n});c.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,r),c.end(),f(!0)}),c.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,r),c.destroy(),f(!1)}),c.once("error",(l)=>{Y("port",`Failed to connect to ${t}:${i}: ${l.message}`,r),c.destroy(),f(!1)})})}class U${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,n=50){this.hostname=i,this.verbose=t,this.maxRetries=n}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await m$(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await C$(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 n=await Il(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await C$(n,this.hostname,3000,this.verbose))if(n<i+this.maxRetries)return this.findNextAvailablePort(n+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var BX=new U$;import*as kf from"node:fs";import*as mi from"node:fs/promises";import{homedir as qe}from"node:os";import*as Kl from"node:path";import*as Vf from"node:process";var ge=/^[a-zA-Z0-9._-]+$/;function Wt(){return Kl.join(qe(),".stacks","rpx","registry.d")}function _l(i){return typeof i==="string"&&i.length>0&&i.length<=128&&ge.test(i)}function zl(i,t){if(!_l(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Kl.join(i,`${t}.json`)}function Ui(i){if(!Number.isInteger(i)||i<=0)return!1;try{return Vf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function j$(i){if(!i||typeof i!=="object")return!1;let t=i,n=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,r=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=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"&&_l(t.id)&&(r||f)&&typeof t.to==="string"&&t.to.length>0&&c&&n&&typeof t.createdAt==="string"}async function Le(i){await mi.mkdir(i,{recursive:!0})}async function N$(i,t=Wt(),n){if(!j$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await Le(t);let r=zl(t,i.id),f=`${r}.tmp.${Vf.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await mi.writeFile(f,c,{encoding:"utf8",mode:420}),await mi.rename(f,r),Y("registry",`wrote entry ${i.id} → ${r}`,n)}catch(l){throw await mi.unlink(f).catch(()=>{}),l}}async function Ql(i,t=Wt(),n){let r=zl(t,i);try{await mi.unlink(r),Y("registry",`removed entry ${i}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function se(i,t=Wt(),n){let r=zl(t,i);try{let f=await mi.readFile(r,"utf8"),c=JSON.parse(f);if(!j$(c))return Y("registry",`entry ${i} failed validation, removing`,n),await mi.unlink(r).catch(()=>{}),null;return c}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return Y("registry",`entry ${i} has invalid JSON, removing`,n),await mi.unlink(r).catch(()=>{}),null;throw f}}async function Tt(i=Wt(),t){let n;try{n=await mi.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let c=f.slice(0,-5);if(!_l(c))continue;let l=await se(c,i,t);if(l)r.push(l)}return r}async function bn(i=Wt(),t){let n=await Tt(i,t),r=0;for(let f of n){if(f.pid===void 0)continue;if(!Ui(f.pid))Y("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await Ql(f.id,i,t).catch(()=>{}),r++}return r}function df(i,t={}){let n=t.dir??Wt(),r=t.debounceMs??100,f=t.pollMs??Math.max(r*2,250),c=t.verbose;kf.mkdirSync(n,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((C)=>({id:C.id,from:C.from,to:C.to,path:C.path,pid:C.pid,pathRewrites:C.pathRewrites,cleanUrls:C.cleanUrls,changeOrigin:C.changeOrigin,static:C.static,loadBalancer:C.loadBalancer})).sort((C,U)=>C.id.localeCompare(U.id)))},$=()=>{if(l=null,y)return;Tt(n,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($,r)},e=setInterval(()=>{if(y||u)return;u=!0,Tt(n,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=kf.watch(n,{persistent:!0},(B,C)=>{if(C&&/\.tmp\.\d+\.\d+$/.test(C))return;A()});return E.on("error",(B)=>{Y("registry",`watcher error: ${B}`,c)}),A(),{close:()=>{if(y=!0,l)clearTimeout(l);clearInterval(e),E.close()}}}var De=120000,be=200,Pe=30000,Ze=3000,ve=4000;class Ol{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??Wt(),this.rpxDir=i.rpxDir??Pn.join(de(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??De,this.pollIntervalMs=i.pollIntervalMs??be,this.restartDelayMs=i.restartDelayMs??Ze,this.killGraceMs=i.killGraceMs??ve,this.launch=i.launcher??pe(this.verbose),this.probePort=i.probePort??oe,this.pickPort=i.pickPort??((n)=>Il(n,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??N$,this.removeEntry=i.removeEntry??Ql;let t=i.reapIntervalMs??Pe;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 n=this.resolver.resolve(i);if(!n)return{kind:"unknown"};t=await this.start(n)}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 n=Pn.join(this.rpxDir,"sites",`${i.id}.log`);await X$.mkdir(Pn.dirname(n),{recursive:!0}).catch(()=>{});let r=this.buildEnv(i,t),f=null,c;try{f=this.launch({command:i.command,cwd:i.dir,env:r,logPath:n})}catch(y){c=`failed to spawn: ${y.message}`}let l={site:i,status:c?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:c?this.now():0,error:c,logPath:n,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,l),c)return J.warn(`rpx: site ${i.host} ${c}`),l;return J.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.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"){J.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let n of i.routeIds)await this.removeEntry(n,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,n=this.now()+this.startupTimeoutMs,r=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<n&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await r()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",J.success(`rpx: ${t.host} ready`);return}await Ml(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 n=i.routes.filter((f)=>f.readyGate??Ot(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),r=n.length>0?n:[...t.values()];return async()=>{for(let f of r)if(!await this.probePort(f))return!1;return r.length>0}}async publishRoutes(i){let{site:t,ports:n}=i;if(t.selfRegisters||t.routes.length===0)return;let r=t.routes.find((w)=>Ot(w.path)==="/")??t.routes[0],f=n.get(r.portEnv);if(f===void 0)return;let c=[];for(let w of t.routes){if(w===r)continue;let u=n.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:${f}`,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 Ml(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),J.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(xi.env))if(typeof f==="string")n[r]=f;Object.assign(n,i.env);for(let[r,f]of t)n[r]=String(f);return n.RPX_SITE_HOST=i.host,n.RPX_SITE_URL=`https://${i.host}`,n}readLogTail(i,t=40){try{return ke(i.logPath,"utf8").split(`
186
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 n of t.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),J.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let n=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof n.unref==="function")n.unref();await Promise.race([t.exited.catch(()=>{}),Ql(this.killGraceMs+500)]),clearTimeout(n)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,n]of this.sites){let r=n.site.idleTimeoutMs;if(r<=0)continue;let f=i-n.lastAccess;if((n.status==="ready"||i-n.startedAt>this.startupTimeoutMs)&&f>r)Y("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function Ql(i){return new Promise((t)=>setTimeout(t,i))}async function ve(i){let t=new AbortController,n=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(n)}}function oe(i){let t=pe();return({command:n,cwd:r,env:f,logPath:c})=>{let l=Le(c,"a");try{let y=ke("sh",["-c",n],{cwd:r,env:f,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{N$(l)}catch{}});return Y("sites",`spawned pid ${w}: sh -c ${n} (cwd ${r})`,i),{pid:w,exited:u,stop:(h="SIGTERM")=>{try{xi.kill(-w,h)}catch{try{y.kill(h)}catch{}}}}}catch(y){try{N$(l)}catch{}throw y}}}function pe(){if(xi.platform==="win32")return null;if(!(typeof xi.getuid==="function"&&xi.getuid()===0))return null;let t=Number.parseInt(xi.env.SUDO_UID??"",10),n=Number.parseInt(xi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(n)||n<=0)return null;return{uid:t,gid:n}}function mn(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var iC=`
187
+ `).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let n of t.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),J.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let n=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof n.unref==="function")n.unref();await Promise.race([t.exited.catch(()=>{}),Ml(this.killGraceMs+500)]),clearTimeout(n)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,n]of this.sites){let r=n.site.idleTimeoutMs;if(r<=0)continue;let f=i-n.lastAccess;if((n.status==="ready"||i-n.startedAt>this.startupTimeoutMs)&&f>r)Y("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function Ml(i){return new Promise((t)=>setTimeout(t,i))}async function oe(i){let t=new AbortController,n=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(n)}}function pe(i){let t=iC();return({command:n,cwd:r,env:f,logPath:c})=>{let l=xe(c,"a");try{let y=Ve("sh",["-c",n],{cwd:r,env:f,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{R$(l)}catch{}});return Y("sites",`spawned pid ${w}: sh -c ${n} (cwd ${r})`,i),{pid:w,exited:u,stop:(h="SIGTERM")=>{try{xi.kill(-w,h)}catch{try{y.kill(h)}catch{}}}}}catch(y){try{R$(l)}catch{}throw y}}}function iC(){if(xi.platform==="win32")return null;if(!(typeof xi.getuid==="function"&&xi.getuid()===0))return null;let t=Number.parseInt(xi.env.SUDO_UID??"",10),n=Number.parseInt(xi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(n)||n<=0)return null;return{uid:t,gid:n}}function mn(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var tC=`
188
188
  :root { color-scheme: light dark }
189
189
  * { box-sizing: border-box }
190
190
  body {
@@ -210,43 +210,43 @@ x-forwarded-host: ${f}\r
210
210
  }
211
211
  .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
212
212
  @keyframes spin { to { transform: rotate(360deg) } }
213
- `;function X$(i,t,n){return`<!doctype html>
213
+ `;function W$(i,t,n){return`<!doctype html>
214
214
  <html lang="en">
215
215
  <head>
216
216
  <meta charset="utf-8">
217
217
  <meta name="viewport" content="width=device-width, initial-scale=1">
218
218
  ${n>0?`<meta http-equiv="refresh" content="${n}">`:""}
219
219
  <title>${mn(i)}</title>
220
- <style>${iC}</style>
220
+ <style>${tC}</style>
221
221
  </head>
222
222
  <body><main class="card">${t}</main></body>
223
- </html>`}function W$(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),n=i.logTail?`<pre>${mn(i.logTail)}</pre>`:"",r=`
223
+ </html>`}function S$(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),n=i.logTail?`<pre>${mn(i.logTail)}</pre>`:"",r=`
224
224
  <div class="row"><div class="spinner"></div><h1>Starting ${mn(i.host)}…</h1></div>
225
225
  <p>rpx is booting this site's dev server on demand. This page reloads itself —
226
226
  it'll switch to the app as soon as it's ready (usually a few seconds).</p>
227
227
  <p>Booting for ${t}s.</p>
228
- ${n}`;return new Response(X$(`Starting ${i.host}`,r,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function S$(i){let t=i.logTail?`<pre>${mn(i.logTail)}</pre>`:"<p>No output was captured.</p>",n=`
228
+ ${n}`;return new Response(W$(`Starting ${i.host}`,r,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function a$(i){let t=i.logTail?`<pre>${mn(i.logTail)}</pre>`:"<p>No output was captured.</p>",n=`
229
229
  <div class="row"><div class="dot"></div><h1>${mn(i.host)} failed to start</h1></div>
230
230
  <p>${mn(i.error)}</p>
231
231
  ${t}
232
- <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(X$(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as tC}from"node:child_process";import Zn from"node:fs";import nC from"node:os";import I$ from"node:path";import*as Gt from"node:process";import{promisify as rC}from"node:util";var Pn=rC(tC);function a$(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var bi=Gt.platform==="win32"?I$.join(Gt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",J$="# rpx",fC="# Added by rpx",vn=new Set(["127.0.0.1","::1"]),Ol=!1;async function K$(i){if(Gt.platform==="win32")throw Error("Administrator privileges required on Windows");if(F$()){let{stdout:r}=await Pn(i);return r}let t=Gl(),n=i.replace(/'/g,"'\\''");try{if(t){let{stdout:r}=await Pn(`echo '${t}' | sudo -S sh -c '${n}' 2>/dev/null`);return Ol=!0,r}if(Ol)try{let{stdout:r}=await Pn(`sudo -n sh -c '${n}'`);return r}catch(r){Y("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:r}=await Pn(`sudo -n sh -c '${n}'`);return Ol=!0,r}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}function on(i){let t=i.indexOf("#"),n=(t===-1?i:i.slice(0,t)).trim();if(!n)return null;let r=t===-1?"":i.slice(t+1).trim(),[f,...c]=n.split(/\s+/);if(!f||c.length===0)return null;let l=/^rpx(?::pid=(\d+))?$/.exec(r);return{address:f,names:c,comment:r,rpxPid:l?.[1]?Number.parseInt(l[1],10):null,rpxManaged:l!==null}}function _$(i,t){let n=on(i);return n!==null&&vn.has(n.address)&&n.names.includes(t)}function cC(i,t){let n=new Set(t),r=new Set,f=i.split(`
233
- `),c=[],l=0;while(l<f.length){let y=f[l];if(y.trim()===fC){let u=[],h=l+1;while(h<f.length){let A=f[h];if(A.trim()===""||A.trim().startsWith("#"))break;u.push(A),h++}let $=u.filter((A)=>{let T=on(A),e=T!==null&&vn.has(T.address)&&T.names.some((E)=>n.has(E));if(e){for(let E of T.names)if(n.has(E))r.add(E)}return!e});if($.length>0||u.length===0)c.push(y,...$);l=h;continue}let w=on(y);if(w?.rpxManaged&&vn.has(w.address)&&w.names.some((u)=>n.has(u))){for(let u of w.names)if(n.has(u))r.add(u);l++;continue}c.push(y),l++}while(c.length>0&&c[c.length-1].trim()==="")c.pop();return{content:`${c.join(`
232
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(W$(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as nC}from"node:child_process";import vn from"node:fs";import rC from"node:os";import K$ from"node:path";import*as Gt from"node:process";import{promisify as fC}from"node:util";var Zn=fC(nC);function J$(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var bi=Gt.platform==="win32"?K$.join(Gt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",F$="# rpx",cC="# Added by rpx",on=new Set(["127.0.0.1","::1"]),Gl=!1;async function _$(i){if(Gt.platform==="win32")throw Error("Administrator privileges required on Windows");if(I$()){let{stdout:r}=await Zn(i);return r}let t=Hl(),n=i.replace(/'/g,"'\\''");try{if(t){let{stdout:r}=await Zn(`echo '${t}' | sudo -S sh -c '${n}' 2>/dev/null`);return Gl=!0,r}if(Gl)try{let{stdout:r}=await Zn(`sudo -n sh -c '${n}'`);return r}catch(r){Y("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:r}=await Zn(`sudo -n sh -c '${n}'`);return Gl=!0,r}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}function pn(i){let t=i.indexOf("#"),n=(t===-1?i:i.slice(0,t)).trim();if(!n)return null;let r=t===-1?"":i.slice(t+1).trim(),[f,...c]=n.split(/\s+/);if(!f||c.length===0)return null;let l=/^rpx(?::pid=(\d+))?$/.exec(r);return{address:f,names:c,comment:r,rpxPid:l?.[1]?Number.parseInt(l[1],10):null,rpxManaged:l!==null}}function z$(i,t){let n=pn(i);return n!==null&&on.has(n.address)&&n.names.includes(t)}function lC(i,t){let n=new Set(t),r=new Set,f=i.split(`
233
+ `),c=[],l=0;while(l<f.length){let y=f[l];if(y.trim()===cC){let u=[],h=l+1;while(h<f.length){let A=f[h];if(A.trim()===""||A.trim().startsWith("#"))break;u.push(A),h++}let $=u.filter((A)=>{let T=pn(A),e=T!==null&&on.has(T.address)&&T.names.some((E)=>n.has(E));if(e){for(let E of T.names)if(n.has(E))r.add(E)}return!e});if($.length>0||u.length===0)c.push(y,...$);l=h;continue}let w=pn(y);if(w?.rpxManaged&&on.has(w.address)&&w.names.some((u)=>n.has(u))){for(let u of w.names)if(n.has(u))r.add(u);l++;continue}c.push(y),l++}while(c.length>0&&c[c.length-1].trim()==="")c.pop();return{content:`${c.join(`
234
234
  `)}
235
- `,removed:[...r]}}function lC(i,t){let n=[],r=new Set,f=[];for(let c of i.split(`
236
- `)){let l=on(c);if(l?.rpxManaged&&l.rpxPid!==null&&vn.has(l.address)&&!t(l.rpxPid)){n.push(...l.names),r.add(l.rpxPid);continue}f.push(c)}while(f.length>0&&f[f.length-1].trim()==="")f.pop();return{content:`${f.join(`
235
+ `,removed:[...r]}}function yC(i,t){let n=[],r=new Set,f=[];for(let c of i.split(`
236
+ `)){let l=pn(c);if(l?.rpxManaged&&l.rpxPid!==null&&on.has(l.address)&&!t(l.rpxPid)){n.push(...l.names),r.add(l.rpxPid);continue}f.push(c)}while(f.length>0&&f[f.length-1].trim()==="")f.pop();return{content:`${f.join(`
237
237
  `)}
238
- `,removed:n,stalePids:[...r]}}async function Hl(i){try{return await Zn.promises.readFile(bi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),K$(`cat "${bi}"`)}}async function ql(i,t){let n=I$.join(nC.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Zn.promises.writeFile(n,i,"utf8"),await K$(`cat "${n}" | tee "${bi}" > /dev/null`)}finally{await Zn.promises.unlink(n).catch((r)=>{Y("hosts",`Failed to remove temporary file: ${r}`,t)})}}async function GX(i,t){let n=i.filter((f)=>!a$(f)),r=i.filter((f)=>a$(f));if(r.length>0)Y("hosts",`Skipping /etc/hosts for loopback dev names: ${r.join(", ")}`,t);if(n.length===0)return;Y("hosts",`Adding hosts: ${n.join(", ")}`,t),Y("hosts",`Using hosts file at: ${bi}`,t);try{let f;try{f=await Hl(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=f.split(`
239
- `),l=n.filter((u)=>!c.some((h)=>_$(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} ${J$}:pid=${y}
241
- ::1 ${u} ${J$}:pid=${y}`).join(`
242
- `);try{await ql(f+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 ${bi}`)}}catch(f){Y("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function HX(i,t){Y("hosts",`Removing hosts: ${i.join(", ")}`,t);try{let n;try{n=await Hl(t)}catch(c){throw Y("hosts",`sudo read also failed: ${c}`,t),Error(`Cannot read hosts file: ${c}`)}let{content:r,removed:f}=cC(n,i);if(f.length===0){Y("hosts","No matching rpx-managed hosts found to remove",t);return}try{await ql(r,t),Y("hosts",`Hosts removed successfully: ${f.join(", ")}`,t)}catch(c){Y("hosts","Could not clean up hosts file automatically",t)}}catch(n){Y("hosts",`Failed to clean up hosts file: ${n.message}`,t)}}async function qX(i,t){Y("hosts",`Checking hosts: ${i}`,t);let n;try{n=await Zn.promises.readFile(bi,"utf-8")}catch(f){Y("hosts",`Error reading hosts file: ${f}`,t);try{let c=Gl(),l;if(c)l=`echo '${c}' | sudo -S cat "${bi}" 2>/dev/null`;else l=`sudo -n cat "${bi}" 2>/dev/null || cat "${bi}" 2>/dev/null || echo ""`;let{stdout:y}=await Pn(l);n=y}catch(c){return Y("hosts",`Cannot read hosts file, assuming entries don't exist: ${c}`,t),i.map(()=>!1)}}let r=n.split(`
243
- `);return i.map((f)=>r.some((c)=>_$(c,f)))}async function gX(i=Ui){let t;try{t=await Zn.promises.readFile(bi,"utf-8")}catch{return[]}let n=[];for(let r of t.split(`
244
- `)){let f=on(r);if(f?.rpxManaged&&f.rpxPid!==null&&vn.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function pn(i={}){let t=i.isAlive??Ui,n;try{n=await Hl(i.verbose)}catch(l){return Y("hosts",`stale hosts GC: cannot read hosts file: ${l}`,i.verbose),[]}let{content:r,removed:f,stalePids:c}=lC(n,t);if(f.length===0)return[];try{return await ql(r,i.verbose),Y("hosts",`stale hosts GC: removed ${f.join(", ")} (dead pid(s): ${c.join(", ")})`,i.verbose),[...new Set(f)]}catch(l){return Y("hosts",`stale hosts GC: write failed: ${l}`,i.verbose),[]}}var yC=5000;function ji(){return Pi.join(H$(),".stacks","rpx")}function Pf(i=ji()){return Pi.join(i,"daemon.pid")}async function jn(i=ji()){try{let t=await Ti.readFile(Pf(i),"utf8"),n=Number.parseInt(t.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wC(i=ji()){let t=await jn(i);return t!==null&&Ui(t)}async function q$(i=ji()){await Ti.mkdir(i,{recursive:!0});let t=Pf(i);while(!0){try{let r=await Ti.open(t,"wx");try{await r.write(`${j.pid}
245
- `)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await jn(i);if(n!==null&&Ui(n))throw Error(`rpx daemon already running (pid=${n})`);await Ti.unlink(t).catch(()=>{})}}async function Un(i=ji()){await Ti.unlink(Pf(i)).catch(()=>{})}var Df=new Map;function bf(i){for(let[t,n]of Df)if(!i.has(t))El(n),Df.delete(t)}function uC(i,t){let n=Mh(t??"localhost:1");if(i.upstreams.length!==n.length)return!1;return i.upstreams.every((r,f)=>r.url===n[f])}function g$(i){let t=i.cleanUrls??!1,n=Ot(i.path),r=Lh(i.auth);if(i.static)return{static:ph(i.static,t),cleanUrls:t,basePath:n,auth:r};let f=i.from??"localhost:1",c=Oh(f),l=new URL(c.startsWith("http")?c:`http://${c}`),y=Df.get(i.id);if(y&&!uC(y,f))El(y),y=void 0;if(!y)y=Gh(f,i.loadBalancer),qh(y),Df.set(i.id,y);return{sourceHost:l.host,upstreamPool:y,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:n,auth:r}}function hC(i){return i.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??i[0]??"rpx.localhost"}async function df(i,t,n=[],r=!1){let f=await Tt(t,i.verbose),c=[...new Set([...f.map((h)=>h.to).filter(Boolean),...n])],l=hC(c),y=[...new Set([l,...c,"rpx.localhost"])],w=Kh(c,l,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let u=await Al(w);if(u&&(r||!nl(ul,y)))Y("daemon",`regenerating shared cert for host(s): ${y.join(", ")}`,i.verbose),$l(),u=null;if(!u)Y("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await zh({...w,forceRegenerate:!0}),u=await Al(w);if(!u)throw Error("failed to bootstrap TLS for rpx daemon");return u}async function $C(i,t,n,r){let f=j.env.SUDO_PASSWORD,c=j.env.HOME??H$(),l=[j.execPath,...j.argv.slice(1)],y=[`HOME=${c}`,`PATH=${j.env.PATH??""}`];if(r)y.push("RPX_VERBOSE=1");for(let[e,E]of Object.entries(j.env))if(E!==void 0&&e!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(e))y.push(`${e}=${E}`);let w=f?["-S","-p","","env",...y,...l]:["-n","env",...y,...l];Y("daemon",`elevating daemon via sudo for privileged ports ${t}/${n}`,r);let u=G$("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,$=null;if(u.once("error",(e)=>{h=e}),u.once("exit",(e)=>{$=e??0}),f&&u.stdin)u.stdin.write(`${f}
246
- `),u.stdin.end();u.unref();let A=Pf(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let e=await jn(i);if(e!==null&&Ui(e)){if(r)J.success(`rpx daemon elevated to root (pid=${e}, https on :${t})`);return{httpsPort:t,httpPort:n,pidPath:A,done:Promise.resolve(),stop:async()=>{try{j.kill(e,"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 z$=!1;function gl(){if(z$)return;z$=!0,j.on("uncaughtException",(i)=>{J.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),j.on("unhandledRejection",(i)=>{J.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function s$(i,t,n){let r;try{r=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??r.hostname).split(":")[0];if(r.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let c=t.challengeStore.handlePath(r.pathname);if(c!==void 0)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(n){let c=w$(n,r.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(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${r.pathname}${r.search}`}})}async function wW(i={}){gl();let t=i.verbose??!1,n=i.rpxDir??ji(),r=i.registryDir??Pi.join(n,"registry.d"),f=i.httpsPort??443,c=i.httpPort??80,l=i.hostname??"0.0.0.0",y=i.gcIntervalMs??yC;if(j.env.RPX_DAEMON_WORKER==="1")return EC({rpxDir:j.env.RPX_WORKER_RPXDIR??n,registryDir:j.env.RPX_WORKER_REGISTRYDIR??r,httpsPort:Number.parseInt(j.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:j.env.RPX_WORKER_HOSTNAME??l,verbose:j.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||c>0&&c<1024,u=typeof j.getuid==="function"&&j.getuid()===0;if(j.platform!=="win32"&&w&&!u)return $C(n,f,c,t);let h=Math.max(1,i.workers??(Number.parseInt(j.env.RPX_WORKERS??"",10)||1));if(h>1){if(i.onDemandSites?.enabled)J.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return YC(i,{rpxDir:n,registryDir:r,httpsPort:f,httpPort:c,hostname:l,verbose:t,gcIntervalMs:y,workers:h})}let $=await q$(n),A=new Map,T=(m,F)=>Nl(A,m,F);function e(m){A=Ul(m.map((di)=>({host:di.to,path:di.path,route:g$(di)}))),bf(new Set(m.map((di)=>di.id)));let F=Array.from(A.keys());Y("daemon",`routing table now covers ${F.length} host(s): ${F.join(", ")||"<empty>"}`,t)}await Dn(r,t).catch((m)=>{Y("daemon",`initial gc failed: ${m}`,t)}),await pn({verbose:t}).catch((m)=>{Y("daemon",`stale hosts GC on start failed: ${m}`,t)});let E=await Tt(r,t);e(E),await Rn({rpxDir:n,verbose:t}).catch((m)=>{Y("daemon",`DNS reconcile on start failed: ${m}`,t)}),await ir(E,{rpxDir:n,verbose:t,ownerPid:j.pid}).catch((m)=>{Y("daemon",`DNS setup on start failed: ${m}`,t)});let B=[];if(i.productionCerts){if(B=await Xl(i.productionCerts,t),t&&B.length>0)J.info(`SNI: serving ${B.length} real cert(s): ${B.map((m)=>m.serverName).join(", ")}`)}let C=new Set,U=null,W;if(i.onDemandSites?.enabled){if(U=new Ml({resolver:Jl(i.onDemandSites),registryDir:r,rpxDir:n,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(m)=>jl(A,m)!==void 0,onSiteActivating:(m)=>{It(m)}}),W=async(m)=>{let F=await U.onRequest(m);switch(F.kind){case"ready":return{retry:!0};case"starting":return W$({host:F.host,sinceMs:F.sinceMs,logTail:F.logTail});case"failed":return S$({host:F.host,error:F.error,logTail:F.logTail});case"unknown":default:return}},t)J.info("rpx: on-demand sites enabled")}let S=el(T,t,W),R=Cl(t),a=null;if(B.length===0)a=await df(i,r);let G=i.onDemandTls,o=G?.enabled?new sf({config:G,certsDir:G.certsDir??i.productionCerts?.certsDir??Pi.join(n,"on-demand-certs"),initial:B,verbose:t,onCertAdded:(m)=>{qt(m)}}):null;function ki(m){if(m.length>0)return m.map((F)=>({serverName:F.serverName,cert:F.cert,key:F.key}));return{key:a.key,cert:a.cert,ca:a.ca,requestCert:!1,rejectUnauthorized:!1}}function rr(m){return Bun.serve({port:f,hostname:l,reusePort:O$(),tls:ki(m),fetch(F,di){return S(F,di)},websocket:R,error(F){return Y("daemon",`https server error: ${F}`,t),new Response(`Server Error: ${F.message}`,{status:500})}})}let at=(m)=>[...new Set(m.map((F)=>F.to).filter(Boolean))],Ht=(m)=>{if(!a)return B;return Ih([...at(m),...C,"rpx.localhost"],a)},Yt=rr(o?o.sniEntries():B.length>0?B:Ht(E)),Jt=null,Ft=!1;async function qt(m){if(Vi)return;if(Jt=m,Ft)return;Ft=!0;try{while(!Vi&&Jt){let F=Jt;Jt=null,Y("daemon",`rebuilding :443 with ${F.length} SNI cert(s)`,t),Yt.stop(!1);let di,n0=!1,Zl=60,n1=500;for(let r0=0;!Vi&&!n0;r0++)try{Yt=rr(F),n0=!0;break}catch(r1){if(di=r1,r0>=Zl)break;await new Promise((f1)=>setTimeout(f1,Math.min(25*2**Math.min(r0,4),n1)))}if(!n0)J.error(`rpx: CRITICAL — could not rebind :443 after ${Zl} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${di?.message}`)}}finally{Ft=!1}}let Zi=null;if(c>0)Zi=Bun.serve({port:c,hostname:l,fetch(m){return s$(m,o,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)J.success(`rpx daemon listening on https://${l}:${f}${Zi?` (http→https on :${c})`:""}`),J.info(`pid file: ${$}`),J.info(`registry: ${r}`);async function I(m){if(Vi||B.length>0||o||!a)return;try{a=await df(i,r,[...C]),await qt(Ht(m))}catch(F){Y("daemon",`TLS sync on registry change failed: ${F}`,t)}}async function It(m){if(Vi||B.length>0||o||!a||!m)return;if(C.has(m))return;C.add(m);try{a=await df(i,r,[...C],!0);let F=await Tt(r,t);await qt(Ht(F))}catch(F){Y("daemon",`dev cert refresh for ${m} failed: ${F}`,t)}}let i0=Vf((m)=>{e(m),I(m),ir(m,{rpxDir:n,verbose:t,ownerPid:j.pid}).catch((F)=>{Y("daemon",`DNS sync on registry change failed: ${F}`,t)})},{dir:r,verbose:t}),gt=setInterval(()=>{Dn(r,t).then((m)=>{if(m>0)Y("daemon",`gc reaped ${m} stale entries`,t)}).catch((m)=>{Y("daemon",`periodic gc failed: ${m}`,t)}),pn({verbose:t}).then((m)=>{if(m.length>0)Y("daemon",`gc reaped stale hosts entries: ${m.join(", ")}`,t)}).catch((m)=>{Y("daemon",`periodic hosts gc failed: ${m}`,t)})},y);if(typeof gt.unref==="function")gt.unref();let Vi=!1,Xn,st=new Promise((m)=>{Xn=m});async function t0(){if(Vi)return st;if(Vi=!0,clearInterval(gt),i0.close(),await U?.stopAll().catch((m)=>{Y("daemon",`site supervisor stopAll failed: ${m}`,t)}),Yt.stop(!1),Zi?.stop(!1),await Nn({rpxDir:n,verbose:t}).catch((m)=>{Y("daemon",`DNS teardown failed: ${m}`,t)}),bf(new Set),await Un(n),t)J.info("rpx daemon stopped");return Xn(),st}let Pl=(m)=>{Y("daemon",`received ${m}, shutting down`,t),t0().catch(()=>{})};return j.once("SIGINT",Pl),j.once("SIGTERM",Pl),{stop:t0,done:st,httpsPort:typeof Yt.port==="number"?Yt.port:f,httpPort:Zi&&typeof Zi.port==="number"?Zi.port:c,pidPath:$,ensureCert:(m)=>o?o.ensureCert(m):Promise.resolve(!1),listSites:()=>U?.list()??[]}}function sl(i){return Pi.join(i,"cluster-sni.json")}async function Q$(i,t,n){let r=sl(i),f=`${r}.${j.pid}.tmp`;await Ti.writeFile(f,JSON.stringify({sni:t,dev:n}),"utf8"),await Ti.rename(f,r)}async function M$(i){try{return JSON.parse(await Ti.readFile(sl(i),"utf8"))}catch{return{sni:[],dev:null}}}function AC(i){if(i.sni.length>0)return i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));if(i.dev)return{key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function TC(){let i=j.execPath,t=j.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let n=Pi.basename(i).toLowerCase();if((n==="bun"||n==="node"||n.startsWith("bun-"))&&j.argv[1])return[i,j.argv[1],"daemon:start"];return[i,"daemon:start"]}async function EC(i){gl();let{rpxDir:t,registryDir:n,httpsPort:r,hostname:f,verbose:c}=i,l=new Map,y=(R,a)=>Nl(l,R,a),w=(R)=>{l=Ul(R.map((a)=>({host:a.to,path:a.path,route:g$(a)}))),bf(new Set(R.map((a)=>a.id)))};w(await Tt(n,c));let u=el(y,c),h=Cl(c),$=!1,A=(R)=>Bun.serve({port:r,hostname:f,reusePort:!0,tls:AC(R),fetch(a,G){return u(a,G)},websocket:h,error(a){return Y("daemon",`worker https error: ${a}`,c),new Response(`Server Error: ${a.message}`,{status:500})}}),T=A(await M$(t));async function e(){if($)return;let R=await M$(t),a=null;for(let o=0;o<20&&!$;o++)try{a=A(R);break}catch{await new Promise((ki)=>setTimeout(ki,25))}if(!a){Y("daemon","worker reloadTls: could not bind new listener; keeping current",c);return}let G=T;T=a,G.stop(!1)}let E=Vf((R)=>w(R),{dir:n,verbose:c}),B=()=>{e().catch(()=>{})};j.on("SIGHUP",B);let C,U=new Promise((R)=>{C=R});async function W(){if($)return U;return $=!0,j.off("SIGHUP",B),E.close(),T.stop(!1),bf(new Set),C(),U}let S=()=>{W().then(()=>j.exit(0)).catch(()=>j.exit(0))};if(j.once("SIGTERM",S),j.once("SIGINT",S),c)J.success(`rpx worker (pid ${j.pid}) serving :${r}`);return{stop:W,done:U,httpsPort:typeof T.port==="number"?T.port:r,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function YC(i,t){gl();let{rpxDir:n,registryDir:r,httpsPort:f,httpPort:c,hostname:l,verbose:y,gcIntervalMs:w,workers:u}=t,h=await q$(n),$=[];if(i.productionCerts)$=await Xl(i.productionCerts,y);let A=null;if($.length===0)A=await df(i,r);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
247
- `):A.ca}:null,e=!1,E=[];function B(I){for(let It of E)try{It.kill(I)}catch{}}async function C(I){await Q$(n,I,T),B("SIGHUP")}let U=i.onDemandTls,W=U?.enabled?new sf({config:U,certsDir:U.certsDir??i.productionCerts?.certsDir??Pi.join(n,"on-demand-certs"),initial:$,verbose:y,onCertAdded:(I)=>{C(I)}}):null;await Q$(n,W?W.sniEntries():$,T);let S=await Tt(r,y);await Rn({rpxDir:n,verbose:y}).catch((I)=>{Y("daemon",`DNS reconcile on start failed: ${I}`,y)}),await ir(S,{rpxDir:n,verbose:y,ownerPid:j.pid}).catch((I)=>{Y("daemon",`DNS setup on start failed: ${I}`,y)}),await Dn(r,y).catch(()=>{}),await pn({verbose:y}).catch(()=>{});let R=Vf((I)=>{ir(I,{rpxDir:n,verbose:y,ownerPid:j.pid}).catch((It)=>{Y("daemon",`DNS sync on registry change failed: ${It}`,y)})},{dir:r,verbose:y}),a=setInterval(()=>{Dn(r,y).catch(()=>{}),pn({verbose:y}).catch(()=>{})},w);a.unref?.();let G=null;if(c>0)G=Bun.serve({port:c,hostname:l,fetch(I){return s$(I,W,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let o=10,ki=60000,rr=30000,at=0,Ht=Date.now();function Yt(){if(e)return;let I={...j.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:n,RPX_WORKER_REGISTRYDIR:r,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:l,RPX_WORKER_VERBOSE:y?"1":"0"},It=Bun.spawn(TC(),{env:I,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(i0,gt){if(e)return;let Vi=E.indexOf(i0);if(Vi!==-1)E.splice(Vi,1);let Xn=Date.now();if(Xn-Ht>ki)Ht=Xn,at=0;if(at++,at>o){J.error(`rpx: worker keeps exiting (code ${gt}); giving up after ${o} restarts in ${Math.round(ki/1000)}s`);return}let st=Math.min(rr,100*2**Math.min(at,8));Y("daemon",`worker exited (code ${gt}); respawning in ${st}ms (restart ${at}/${o})`,y),setTimeout(Yt,st).unref?.()}});E.push(It)}for(let I=0;I<u;I++)Yt();if(y)J.success(`rpx coordinator listening on https://${l}:${f} via ${u} worker(s)${G?` (http→https on :${c})`:""}`),J.info(`pid file: ${h}`);let Jt,Ft=new Promise((I)=>{Jt=I});async function qt(){if(e)return Ft;if(e=!0,clearInterval(a),R.close(),G?.stop(!1),B("SIGTERM"),await Promise.race([Promise.all(E.map((I)=>I.exited)),new Promise((I)=>setTimeout(I,3000))]),B("SIGKILL"),await Nn({rpxDir:n,verbose:y}).catch((I)=>{Y("daemon",`DNS teardown failed: ${I}`,y)}),await Un(n),await Ti.unlink(sl(n)).catch(()=>{}),y)J.info("rpx coordinator stopped");return Jt(),Ft}let Zi=(I)=>{Y("daemon",`coordinator received ${I}, shutting down`,y),qt().catch(()=>{})};return j.once("SIGINT",Zi),j.once("SIGTERM",Zi),{stop:qt,done:Ft,httpsPort:f,httpPort:c,pidPath:h,ensureCert:(I)=>W?W.ensureCert(I):Promise.resolve(!1),listSites:()=>[]}}function BC(){let i=j.execPath,t=Pi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&j.argv[1])return[i,j.argv[1],"daemon:start"];return[i,"daemon:start"]}async function uW(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1;await Rn({rpxDir:t,verbose:n}).catch((h)=>{Y("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,n)});let r=await jn(t);if(r!==null&&Ui(r))return Y("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)Y("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await Un(t);await Ti.mkdir(t,{recursive:!0});let f=i.spawnCommand??BC();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");Y("daemon",`spawning daemon: ${f.join(" ")}`,n);let c=G$(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??j.cwd(),env:i.spawnEnv?{...j.env,...i.spawnEnv}:j.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 jn(t);if(h!==null&&Ui(h))return Y("daemon",`daemon registered with pid=${h}`,n),{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 hW(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1,r=i.timeoutMs??5000,f=i.pollIntervalMs??50,c=i.forceAfterTimeout??!0,l=await jn(t);if(l===null||!Ui(l)){if(l!==null)await Un(t);return await Rn({rpxDir:t,verbose:n}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{j.kill(l,"SIGTERM")}catch(w){let u=w.code;if(u==="ESRCH")return await Un(t),{stopped:!1,pid:l,forced:!1};if(u==="EPERM")Nt(`kill -TERM ${l}`);else throw w}let y=Date.now()+r;while(Date.now()<y){if(!Ui(l))return Y("daemon",`daemon pid=${l} stopped cleanly`,n),{stopped:!0,pid:l,forced:!1};await new Promise((w)=>setTimeout(w,f))}if(!c)throw Error(`rpx daemon (pid=${l}) did not exit within ${r}ms`);Y("daemon",`daemon pid=${l} did not exit, escalating to SIGKILL`,n);try{j.kill(l,"SIGKILL")}catch(w){let u=w.code;if(u==="EPERM")Nt(`kill -KILL ${l}`);else if(u!=="ESRCH")throw w}return await Un(t),await Nn({rpxDir:t,verbose:n}).catch((w)=>{Y("daemon",`DNS teardown after SIGKILL: ${w}`,n)}),{stopped:!0,pid:l,forced:!0}}async function $W(i={}){let t=i.rpxDir??ji();if(await wC(t))return;await Rn({rpxDir:t,verbose:i.verbose})}import*as St from"node:fs/promises";import{homedir as eC}from"node:os";import*as Ll from"node:path";var Zf=1,CC="dns-state.json",L$=["com","test","dev","app","page","local","localhost","example","invalid"];function x$(){return Ll.join(eC(),".stacks","rpx")}function xl(i=x$()){return Ll.join(i,CC)}async function vf(i=x$()){try{let t=await St.readFile(xl(i),"utf8"),n=JSON.parse(t);if(n.version!==Zf||!Array.isArray(n.resolvers))return null;return{version:Zf,resolvers:n.resolvers.filter((r)=>typeof r==="string"),domains:Array.isArray(n.domains)?n.domains.filter((r)=>typeof r==="string"):[],ownerPid:typeof n.ownerPid==="number"?n.ownerPid:null,updatedAt:typeof n.updatedAt==="string"?n.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function k$(i,t){await St.mkdir(i,{recursive:!0}),await St.writeFile(xl(i),`${JSON.stringify(t,null,2)}
248
- `,"utf8")}async function kl(i){await St.rm(xl(i),{force:!0})}function V$(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function mC(i){let t=V$(i);if(!t)return null;let n=t.split(".");if(n.length<2)return null;return n.slice(-2).join(".")}function Vl(i){let t=new Set;for(let n of i){let r=mC(n);if(r)t.add(r)}return Array.from(t).sort()}function dl(i){let t=new Set;for(let n of i){let r=V$(n);if(r)t.add(r)}return Array.from(t).sort()}var pf=15353,UC="# managed-by: rpx",P$="/etc/resolver",Ni=null,of=new Set;function Z$(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 v$(i,t,n=0){let r=[],f=t,c=0;while(!0){if(f>=i.length||++c>128)break;let l=i[f];if(l===0){f++;break}if((l&192)===192){if(f+1>=i.length||n>=10)break;let y=i.readUInt16BE(f)&16383,{name:w}=v$(i,y,n+1);if(w)r.push(w);f+=2;break}if(f++,f+l>i.length)break;r.push(i.subarray(f,f+l).toString("ascii")),f+=l}return{name:r.join("."),newOffset:f}}function jC(i,t){let{name:n,newOffset:r}=v$(i,t),f=i.readUInt16BE(r),c=i.readUInt16BE(r+2);return{question:{name:n,type:f,class:c},newOffset:r+4}}function tr(i){let t=i.split("."),n=[];for(let r of t)n.push(Buffer.from([r.length])),n.push(Buffer.from(r,"ascii"));return n.push(Buffer.from([0])),Buffer.concat(n)}function NC(i,t,n){let r=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),r.push(f),r.push(tr(t.name));let c=Buffer.alloc(4);c.writeUInt16BE(t.type,0),c.writeUInt16BE(t.class,2),r.push(c),r.push(tr(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),r.push(l);let y=n.split(".").map((w)=>Number.parseInt(w,10));r.push(Buffer.from(y))}else if(t.type===28)l.writeUInt16BE(16,8),r.push(l),r.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,tr(t.name),c]);return Buffer.concat(r)}function RC(i,t){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(i,0),r.writeUInt16BE(33155,2),r.writeUInt16BE(1,4),r.writeUInt16BE(0,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(tr(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),n.push(f),Buffer.concat(n)}async function XC(i,t){if(Et.platform!=="darwin")return!1;let n=dl(i);if(n.length===0)return!1;if(Ni){for(let r of n)of.add(r);return Y("dns","DNS server already running — merged domains",t),!0}return of=new Set(n),new Promise((r)=>{Ni=d$.createSocket("udp4"),Ni.on("error",(f)=>{Y("dns",`DNS server error: ${f.message}`,t),Ni?.close(),Ni=null,r(!1)}),Ni.on("message",(f,c)=>{try{let l=Z$(f),{question:y}=jC(f,12);Y("dns",`Query for ${y.name} type ${y.type} from ${c.address}`,t);let w=y.name.toLowerCase(),u=!1;for(let $ of of)if(w===$||w.endsWith(`.${$}`)){u=!0;break}let h;if(u&&(y.type===1||y.type===28))h=NC(l.id,y,"127.0.0.1"),Y("dns",`Responding with localhost for ${y.name}`,t);else h=RC(l.id,y),Y("dns",`NXDOMAIN for ${y.name}`,t);Ni?.send(h,c.port,c.address)}catch(l){Y("dns",`Error processing DNS query: ${l}`,t)}}),Ni.on("listening",()=>{let f=Ni?.address();Y("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),r(!0)});try{Ni.bind(pf,"127.0.0.1")}catch(f){Y("dns",`Failed to bind DNS server: ${f}`,t),r(!1)}})}function o$(i){if(Ni)Y("dns","Stopping DNS server",i),Ni.close(),Ni=null,of=new Set}function UW(){return Ni!==null}async function WC(i,t=500){let n=i.trim().toLowerCase().replace(/\.$/,"");if(!n)return!1;return new Promise((r)=>{let f=d$.createSocket("udp4"),c=setTimeout(()=>{f.close(),r(!1)},t);f.on("message",(y)=>{clearTimeout(c),f.close();try{let w=Z$(y);r(w.ancount>0)}catch{r(!1)}}),f.on("error",()=>{clearTimeout(c),f.close(),r(!1)});let l=SC(n,1);f.send(l,pf,"127.0.0.1",(y)=>{if(y)clearTimeout(c),f.close(),r(!1)})})}function SC(i,t){let n=Buffer.alloc(12);n.writeUInt16BE(1,0),n.writeUInt16BE(256,2),n.writeUInt16BE(1,4);let r=Buffer.concat([tr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([n,r])}function aC(){return`${UC}
238
+ `,removed:n,stalePids:[...r]}}async function ql(i){try{return await vn.promises.readFile(bi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),_$(`cat "${bi}"`)}}async function gl(i,t){let n=K$.join(rC.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await vn.promises.writeFile(n,i,"utf8"),await _$(`cat "${n}" | tee "${bi}" > /dev/null`)}finally{await vn.promises.unlink(n).catch((r)=>{Y("hosts",`Failed to remove temporary file: ${r}`,t)})}}async function HX(i,t){let n=i.filter((f)=>!J$(f)),r=i.filter((f)=>J$(f));if(r.length>0)Y("hosts",`Skipping /etc/hosts for loopback dev names: ${r.join(", ")}`,t);if(n.length===0)return;Y("hosts",`Adding hosts: ${n.join(", ")}`,t),Y("hosts",`Using hosts file at: ${bi}`,t);try{let f;try{f=await ql(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=f.split(`
239
+ `),l=n.filter((u)=>!c.some((h)=>z$(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} ${F$}:pid=${y}
241
+ ::1 ${u} ${F$}:pid=${y}`).join(`
242
+ `);try{await gl(f+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 ${bi}`)}}catch(f){Y("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function qX(i,t){Y("hosts",`Removing hosts: ${i.join(", ")}`,t);try{let n;try{n=await ql(t)}catch(c){throw Y("hosts",`sudo read also failed: ${c}`,t),Error(`Cannot read hosts file: ${c}`)}let{content:r,removed:f}=lC(n,i);if(f.length===0){Y("hosts","No matching rpx-managed hosts found to remove",t);return}try{await gl(r,t),Y("hosts",`Hosts removed successfully: ${f.join(", ")}`,t)}catch(c){Y("hosts","Could not clean up hosts file automatically",t)}}catch(n){Y("hosts",`Failed to clean up hosts file: ${n.message}`,t)}}async function gX(i,t){Y("hosts",`Checking hosts: ${i}`,t);let n;try{n=await vn.promises.readFile(bi,"utf-8")}catch(f){Y("hosts",`Error reading hosts file: ${f}`,t);try{let c=Hl(),l;if(c)l=`echo '${c}' | sudo -S cat "${bi}" 2>/dev/null`;else l=`sudo -n cat "${bi}" 2>/dev/null || cat "${bi}" 2>/dev/null || echo ""`;let{stdout:y}=await Zn(l);n=y}catch(c){return Y("hosts",`Cannot read hosts file, assuming entries don't exist: ${c}`,t),i.map(()=>!1)}}let r=n.split(`
243
+ `);return i.map((f)=>r.some((c)=>z$(c,f)))}async function LX(i=Ui){let t;try{t=await vn.promises.readFile(bi,"utf-8")}catch{return[]}let n=[];for(let r of t.split(`
244
+ `)){let f=pn(r);if(f?.rpxManaged&&f.rpxPid!==null&&on.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function ir(i={}){let t=i.isAlive??Ui,n;try{n=await ql(i.verbose)}catch(l){return Y("hosts",`stale hosts GC: cannot read hosts file: ${l}`,i.verbose),[]}let{content:r,removed:f,stalePids:c}=yC(n,t);if(f.length===0)return[];try{return await gl(r,i.verbose),Y("hosts",`stale hosts GC: removed ${f.join(", ")} (dead pid(s): ${c.join(", ")})`,i.verbose),[...new Set(f)]}catch(l){return Y("hosts",`stale hosts GC: write failed: ${l}`,i.verbose),[]}}var wC=5000;function ji(){return Pi.join(q$(),".stacks","rpx")}function Zf(i=ji()){return Pi.join(i,"daemon.pid")}async function jn(i=ji()){try{let t=await Ti.readFile(Zf(i),"utf8"),n=Number.parseInt(t.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(t){if(t.code==="ENOENT")return null;throw t}}async function uC(i=ji()){let t=await jn(i);return t!==null&&Ui(t)}async function g$(i=ji()){await Ti.mkdir(i,{recursive:!0});let t=Zf(i);while(!0){try{let r=await Ti.open(t,"wx");try{await r.write(`${j.pid}
245
+ `)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await jn(i);if(n!==null&&Ui(n))throw Error(`rpx daemon already running (pid=${n})`);await Ti.unlink(t).catch(()=>{})}}async function Un(i=ji()){await Ti.unlink(Zf(i)).catch(()=>{})}var bf=new Map;function Pf(i){for(let[t,n]of bf)if(!i.has(t))Yl(n),bf.delete(t)}function hC(i,t){let n=Oh(t??"localhost:1");if(i.upstreams.length!==n.length)return!1;return i.upstreams.every((r,f)=>r.url===n[f])}function L$(i){let t=i.cleanUrls??!1,n=Ot(i.path),r=xh(i.auth);if(i.static)return{static:i$(i.static,t),cleanUrls:t,basePath:n,auth:r};let f=i.from??"localhost:1",c=Gh(f),l=new URL(c.startsWith("http")?c:`http://${c}`),y=bf.get(i.id);if(y&&!hC(y,f))Yl(y),y=void 0;if(!y)y=Hh(f,i.loadBalancer),gh(y),bf.set(i.id,y);return{sourceHost:l.host,upstreamPool:y,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:n,auth:r}}function $C(i){return i.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??i[0]??"rpx.localhost"}async function Df(i,t,n=[],r=!1){let f=await Tt(t,i.verbose),c=[...new Set([...f.map((h)=>h.to).filter(Boolean),...n])],l=$C(c),y=[...new Set([l,...c,"rpx.localhost"])],w=_h(c,l,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let u=await Tl(w);if(u&&(r||!rl(hl,y)))Y("daemon",`regenerating shared cert for host(s): ${y.join(", ")}`,i.verbose),Al(),u=null;if(!u)Y("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Qh({...w,forceRegenerate:!0}),u=await Tl(w);if(!u)throw Error("failed to bootstrap TLS for rpx daemon");return u}async function AC(i,t,n,r){let f=j.env.SUDO_PASSWORD,c=j.env.HOME??q$(),l=[j.execPath,...j.argv.slice(1)],y=[`HOME=${c}`,`PATH=${j.env.PATH??""}`];if(r)y.push("RPX_VERBOSE=1");for(let[e,E]of Object.entries(j.env))if(E!==void 0&&e!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(e))y.push(`${e}=${E}`);let w=f?["-S","-p","","env",...y,...l]:["-n","env",...y,...l];Y("daemon",`elevating daemon via sudo for privileged ports ${t}/${n}`,r);let u=H$("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,$=null;if(u.once("error",(e)=>{h=e}),u.once("exit",(e)=>{$=e??0}),f&&u.stdin)u.stdin.write(`${f}
246
+ `),u.stdin.end();u.unref();let A=Zf(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let e=await jn(i);if(e!==null&&Ui(e)){if(r)J.success(`rpx daemon elevated to root (pid=${e}, https on :${t})`);return{httpsPort:t,httpPort:n,pidPath:A,done:Promise.resolve(),stop:async()=>{try{j.kill(e,"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 Q$=!1;function Ll(){if(Q$)return;Q$=!0,j.on("uncaughtException",(i)=>{J.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),j.on("unhandledRejection",(i)=>{J.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function s$(i,t,n){let r;try{r=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??r.hostname).split(":")[0];if(r.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let c=t.challengeStore.handlePath(r.pathname);if(c!==void 0)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(n){let c=u$(n,r.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(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${r.pathname}${r.search}`}})}async function uW(i={}){Ll();let t=i.verbose??!1,n=i.rpxDir??ji(),r=i.registryDir??Pi.join(n,"registry.d"),f=i.httpsPort??443,c=i.httpPort??80,l=i.hostname??"0.0.0.0",y=i.gcIntervalMs??wC;if(j.env.RPX_DAEMON_WORKER==="1")return YC({rpxDir:j.env.RPX_WORKER_RPXDIR??n,registryDir:j.env.RPX_WORKER_REGISTRYDIR??r,httpsPort:Number.parseInt(j.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:j.env.RPX_WORKER_HOSTNAME??l,verbose:j.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||c>0&&c<1024,u=typeof j.getuid==="function"&&j.getuid()===0;if(j.platform!=="win32"&&w&&!u)return AC(n,f,c,t);let h=Math.max(1,i.workers??(Number.parseInt(j.env.RPX_WORKERS??"",10)||1));if(h>1){if(i.onDemandSites?.enabled)J.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return BC(i,{rpxDir:n,registryDir:r,httpsPort:f,httpPort:c,hostname:l,verbose:t,gcIntervalMs:y,workers:h})}let $=await g$(n),A=new Map,T=(m,F)=>Rl(A,m,F);function e(m){A=jl(m.map((di)=>({host:di.to,path:di.path,route:L$(di)}))),Pf(new Set(m.map((di)=>di.id)));let F=Array.from(A.keys());Y("daemon",`routing table now covers ${F.length} host(s): ${F.join(", ")||"<empty>"}`,t)}await bn(r,t).catch((m)=>{Y("daemon",`initial gc failed: ${m}`,t)}),await ir({verbose:t}).catch((m)=>{Y("daemon",`stale hosts GC on start failed: ${m}`,t)});let E=await Tt(r,t);e(E),await Rn({rpxDir:n,verbose:t}).catch((m)=>{Y("daemon",`DNS reconcile on start failed: ${m}`,t)}),await tr(E,{rpxDir:n,verbose:t,ownerPid:j.pid}).catch((m)=>{Y("daemon",`DNS setup on start failed: ${m}`,t)});let B=[];if(i.productionCerts){if(B=await Wl(i.productionCerts,t),t&&B.length>0)J.info(`SNI: serving ${B.length} real cert(s): ${B.map((m)=>m.serverName).join(", ")}`)}let C=new Set,U=null,W;if(i.onDemandSites?.enabled){if(U=new Ol({resolver:Fl(i.onDemandSites),registryDir:r,rpxDir:n,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(m)=>Nl(A,m)!==void 0,onSiteActivating:(m)=>{It(m)}}),W=async(m)=>{let F=await U.onRequest(m);switch(F.kind){case"ready":return{retry:!0};case"starting":return S$({host:F.host,sinceMs:F.sinceMs,logTail:F.logTail});case"failed":return a$({host:F.host,error:F.error,logTail:F.logTail});case"unknown":default:return}},t)J.info("rpx: on-demand sites enabled")}let S=Cl(T,t,W),R=ml(t),a=null;if(B.length===0)a=await Df(i,r);let G=i.onDemandTls,o=G?.enabled?new sf({config:G,certsDir:G.certsDir??i.productionCerts?.certsDir??Pi.join(n,"on-demand-certs"),initial:B,verbose:t,onCertAdded:(m)=>{qt(m)}}):null;function ki(m){if(m.length>0)return Dn(m.map((F)=>({serverName:F.serverName,cert:F.cert,key:F.key})));return Dn({key:a.key,cert:a.cert,ca:a.ca,requestCert:!1,rejectUnauthorized:!1})}function fr(m){return Bun.serve({port:f,hostname:l,reusePort:G$(),tls:ki(m),fetch(F,di){return S(F,di)},websocket:R,error(F){return Y("daemon",`https server error: ${F}`,t),new Response(`Server Error: ${F.message}`,{status:500})}})}let at=(m)=>[...new Set(m.map((F)=>F.to).filter(Boolean))],Ht=(m)=>{if(!a)return B;return Kh([...at(m),...C,"rpx.localhost"],a)},Yt=fr(o?o.sniEntries():B.length>0?B:Ht(E)),Jt=null,Ft=!1;async function qt(m){if(Vi)return;if(Jt=m,Ft)return;Ft=!0;try{while(!Vi&&Jt){let F=Jt;Jt=null,Y("daemon",`rebuilding :443 with ${F.length} SNI cert(s)`,t),Yt.stop(!1);let di,r0=!1,vl=60,r1=500;for(let f0=0;!Vi&&!r0;f0++)try{Yt=fr(F),r0=!0;break}catch(f1){if(di=f1,f0>=vl)break;await new Promise((c1)=>setTimeout(c1,Math.min(25*2**Math.min(f0,4),r1)))}if(!r0)J.error(`rpx: CRITICAL — could not rebind :443 after ${vl} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${di?.message}`)}}finally{Ft=!1}}let Zi=null;if(c>0)Zi=Bun.serve({port:c,hostname:l,fetch(m){return s$(m,o,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)J.success(`rpx daemon listening on https://${l}:${f}${Zi?` (http→https on :${c})`:""}`),J.info(`pid file: ${$}`),J.info(`registry: ${r}`);async function I(m){if(Vi||B.length>0||o||!a)return;try{a=await Df(i,r,[...C]),await qt(Ht(m))}catch(F){Y("daemon",`TLS sync on registry change failed: ${F}`,t)}}async function It(m){if(Vi||B.length>0||o||!a||!m)return;if(C.has(m))return;C.add(m);try{a=await Df(i,r,[...C],!0);let F=await Tt(r,t);await qt(Ht(F))}catch(F){Y("daemon",`dev cert refresh for ${m} failed: ${F}`,t)}}let t0=df((m)=>{e(m),I(m),tr(m,{rpxDir:n,verbose:t,ownerPid:j.pid}).catch((F)=>{Y("daemon",`DNS sync on registry change failed: ${F}`,t)})},{dir:r,verbose:t}),gt=setInterval(()=>{bn(r,t).then((m)=>{if(m>0)Y("daemon",`gc reaped ${m} stale entries`,t)}).catch((m)=>{Y("daemon",`periodic gc failed: ${m}`,t)}),ir({verbose:t}).then((m)=>{if(m.length>0)Y("daemon",`gc reaped stale hosts entries: ${m.join(", ")}`,t)}).catch((m)=>{Y("daemon",`periodic hosts gc failed: ${m}`,t)})},y);if(typeof gt.unref==="function")gt.unref();let Vi=!1,Xn,Lt=new Promise((m)=>{Xn=m});async function n0(){if(Vi)return Lt;if(Vi=!0,clearInterval(gt),t0.close(),await U?.stopAll().catch((m)=>{Y("daemon",`site supervisor stopAll failed: ${m}`,t)}),Yt.stop(!1),Zi?.stop(!1),await Nn({rpxDir:n,verbose:t}).catch((m)=>{Y("daemon",`DNS teardown failed: ${m}`,t)}),Pf(new Set),await Un(n),t)J.info("rpx daemon stopped");return Xn(),Lt}let Zl=(m)=>{Y("daemon",`received ${m}, shutting down`,t),n0().catch(()=>{})};return j.once("SIGINT",Zl),j.once("SIGTERM",Zl),{stop:n0,done:Lt,httpsPort:typeof Yt.port==="number"?Yt.port:f,httpPort:Zi&&typeof Zi.port==="number"?Zi.port:c,pidPath:$,ensureCert:(m)=>o?o.ensureCert(m):Promise.resolve(!1),listSites:()=>U?.list()??[]}}function sl(i){return Pi.join(i,"cluster-sni.json")}async function M$(i,t,n){let r=sl(i),f=`${r}.${j.pid}.tmp`;await Ti.writeFile(f,JSON.stringify({sni:t,dev:n}),"utf8"),await Ti.rename(f,r)}async function O$(i){try{return JSON.parse(await Ti.readFile(sl(i),"utf8"))}catch{return{sni:[],dev:null}}}function TC(i){if(i.sni.length>0)return Dn(i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(i.dev)return Dn({key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function EC(){let i=j.execPath,t=j.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let n=Pi.basename(i).toLowerCase();if((n==="bun"||n==="node"||n.startsWith("bun-"))&&j.argv[1])return[i,j.argv[1],"daemon:start"];return[i,"daemon:start"]}async function YC(i){Ll();let{rpxDir:t,registryDir:n,httpsPort:r,hostname:f,verbose:c}=i,l=new Map,y=(R,a)=>Rl(l,R,a),w=(R)=>{l=jl(R.map((a)=>({host:a.to,path:a.path,route:L$(a)}))),Pf(new Set(R.map((a)=>a.id)))};w(await Tt(n,c));let u=Cl(y,c),h=ml(c),$=!1,A=(R)=>Bun.serve({port:r,hostname:f,reusePort:!0,tls:TC(R),fetch(a,G){return u(a,G)},websocket:h,error(a){return Y("daemon",`worker https error: ${a}`,c),new Response(`Server Error: ${a.message}`,{status:500})}}),T=A(await O$(t));async function e(){if($)return;let R=await O$(t),a=null;for(let o=0;o<20&&!$;o++)try{a=A(R);break}catch{await new Promise((ki)=>setTimeout(ki,25))}if(!a){Y("daemon","worker reloadTls: could not bind new listener; keeping current",c);return}let G=T;T=a,G.stop(!1)}let E=df((R)=>w(R),{dir:n,verbose:c}),B=()=>{e().catch(()=>{})};j.on("SIGHUP",B);let C,U=new Promise((R)=>{C=R});async function W(){if($)return U;return $=!0,j.off("SIGHUP",B),E.close(),T.stop(!1),Pf(new Set),C(),U}let S=()=>{W().then(()=>j.exit(0)).catch(()=>j.exit(0))};if(j.once("SIGTERM",S),j.once("SIGINT",S),c)J.success(`rpx worker (pid ${j.pid}) serving :${r}`);return{stop:W,done:U,httpsPort:typeof T.port==="number"?T.port:r,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function BC(i,t){Ll();let{rpxDir:n,registryDir:r,httpsPort:f,httpPort:c,hostname:l,verbose:y,gcIntervalMs:w,workers:u}=t,h=await g$(n),$=[];if(i.productionCerts)$=await Wl(i.productionCerts,y);let A=null;if($.length===0)A=await Df(i,r);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
247
+ `):A.ca}:null,e=!1,E=[];function B(I){for(let It of E)try{It.kill(I)}catch{}}async function C(I){await M$(n,I,T),B("SIGHUP")}let U=i.onDemandTls,W=U?.enabled?new sf({config:U,certsDir:U.certsDir??i.productionCerts?.certsDir??Pi.join(n,"on-demand-certs"),initial:$,verbose:y,onCertAdded:(I)=>{C(I)}}):null;await M$(n,W?W.sniEntries():$,T);let S=await Tt(r,y);await Rn({rpxDir:n,verbose:y}).catch((I)=>{Y("daemon",`DNS reconcile on start failed: ${I}`,y)}),await tr(S,{rpxDir:n,verbose:y,ownerPid:j.pid}).catch((I)=>{Y("daemon",`DNS setup on start failed: ${I}`,y)}),await bn(r,y).catch(()=>{}),await ir({verbose:y}).catch(()=>{});let R=df((I)=>{tr(I,{rpxDir:n,verbose:y,ownerPid:j.pid}).catch((It)=>{Y("daemon",`DNS sync on registry change failed: ${It}`,y)})},{dir:r,verbose:y}),a=setInterval(()=>{bn(r,y).catch(()=>{}),ir({verbose:y}).catch(()=>{})},w);a.unref?.();let G=null;if(c>0)G=Bun.serve({port:c,hostname:l,fetch(I){return s$(I,W,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let o=10,ki=60000,fr=30000,at=0,Ht=Date.now();function Yt(){if(e)return;let I={...j.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:n,RPX_WORKER_REGISTRYDIR:r,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:l,RPX_WORKER_VERBOSE:y?"1":"0"},It=Bun.spawn(EC(),{env:I,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(t0,gt){if(e)return;let Vi=E.indexOf(t0);if(Vi!==-1)E.splice(Vi,1);let Xn=Date.now();if(Xn-Ht>ki)Ht=Xn,at=0;if(at++,at>o){J.error(`rpx: worker keeps exiting (code ${gt}); giving up after ${o} restarts in ${Math.round(ki/1000)}s`);return}let Lt=Math.min(fr,100*2**Math.min(at,8));Y("daemon",`worker exited (code ${gt}); respawning in ${Lt}ms (restart ${at}/${o})`,y),setTimeout(Yt,Lt).unref?.()}});E.push(It)}for(let I=0;I<u;I++)Yt();if(y)J.success(`rpx coordinator listening on https://${l}:${f} via ${u} worker(s)${G?` (http→https on :${c})`:""}`),J.info(`pid file: ${h}`);let Jt,Ft=new Promise((I)=>{Jt=I});async function qt(){if(e)return Ft;if(e=!0,clearInterval(a),R.close(),G?.stop(!1),B("SIGTERM"),await Promise.race([Promise.all(E.map((I)=>I.exited)),new Promise((I)=>setTimeout(I,3000))]),B("SIGKILL"),await Nn({rpxDir:n,verbose:y}).catch((I)=>{Y("daemon",`DNS teardown failed: ${I}`,y)}),await Un(n),await Ti.unlink(sl(n)).catch(()=>{}),y)J.info("rpx coordinator stopped");return Jt(),Ft}let Zi=(I)=>{Y("daemon",`coordinator received ${I}, shutting down`,y),qt().catch(()=>{})};return j.once("SIGINT",Zi),j.once("SIGTERM",Zi),{stop:qt,done:Ft,httpsPort:f,httpPort:c,pidPath:h,ensureCert:(I)=>W?W.ensureCert(I):Promise.resolve(!1),listSites:()=>[]}}function eC(){let i=j.execPath,t=Pi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&j.argv[1])return[i,j.argv[1],"daemon:start"];return[i,"daemon:start"]}async function hW(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1;await Rn({rpxDir:t,verbose:n}).catch((h)=>{Y("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,n)});let r=await jn(t);if(r!==null&&Ui(r))return Y("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)Y("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await Un(t);await Ti.mkdir(t,{recursive:!0});let f=i.spawnCommand??eC();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");Y("daemon",`spawning daemon: ${f.join(" ")}`,n);let c=H$(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??j.cwd(),env:i.spawnEnv?{...j.env,...i.spawnEnv}:j.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 jn(t);if(h!==null&&Ui(h))return Y("daemon",`daemon registered with pid=${h}`,n),{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 $W(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1,r=i.timeoutMs??5000,f=i.pollIntervalMs??50,c=i.forceAfterTimeout??!0,l=await jn(t);if(l===null||!Ui(l)){if(l!==null)await Un(t);return await Rn({rpxDir:t,verbose:n}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{j.kill(l,"SIGTERM")}catch(w){let u=w.code;if(u==="ESRCH")return await Un(t),{stopped:!1,pid:l,forced:!1};if(u==="EPERM")Nt(`kill -TERM ${l}`);else throw w}let y=Date.now()+r;while(Date.now()<y){if(!Ui(l))return Y("daemon",`daemon pid=${l} stopped cleanly`,n),{stopped:!0,pid:l,forced:!1};await new Promise((w)=>setTimeout(w,f))}if(!c)throw Error(`rpx daemon (pid=${l}) did not exit within ${r}ms`);Y("daemon",`daemon pid=${l} did not exit, escalating to SIGKILL`,n);try{j.kill(l,"SIGKILL")}catch(w){let u=w.code;if(u==="EPERM")Nt(`kill -KILL ${l}`);else if(u!=="ESRCH")throw w}return await Un(t),await Nn({rpxDir:t,verbose:n}).catch((w)=>{Y("daemon",`DNS teardown after SIGKILL: ${w}`,n)}),{stopped:!0,pid:l,forced:!0}}async function AW(i={}){let t=i.rpxDir??ji();if(await uC(t))return;await Rn({rpxDir:t,verbose:i.verbose})}import*as St from"node:fs/promises";import{homedir as CC}from"node:os";import*as xl from"node:path";var vf=1,mC="dns-state.json",x$=["com","test","dev","app","page","local","localhost","example","invalid"];function k$(){return xl.join(CC(),".stacks","rpx")}function kl(i=k$()){return xl.join(i,mC)}async function of(i=k$()){try{let t=await St.readFile(kl(i),"utf8"),n=JSON.parse(t);if(n.version!==vf||!Array.isArray(n.resolvers))return null;return{version:vf,resolvers:n.resolvers.filter((r)=>typeof r==="string"),domains:Array.isArray(n.domains)?n.domains.filter((r)=>typeof r==="string"):[],ownerPid:typeof n.ownerPid==="number"?n.ownerPid:null,updatedAt:typeof n.updatedAt==="string"?n.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function V$(i,t){await St.mkdir(i,{recursive:!0}),await St.writeFile(kl(i),`${JSON.stringify(t,null,2)}
248
+ `,"utf8")}async function Vl(i){await St.rm(kl(i),{force:!0})}function d$(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function UC(i){let t=d$(i);if(!t)return null;let n=t.split(".");if(n.length<2)return null;return n.slice(-2).join(".")}function dl(i){let t=new Set;for(let n of i){let r=UC(n);if(r)t.add(r)}return Array.from(t).sort()}function Dl(i){let t=new Set;for(let n of i){let r=d$(n);if(r)t.add(r)}return Array.from(t).sort()}var i0=15353,jC="# managed-by: rpx",Z$="/etc/resolver",Ni=null,pf=new Set;function v$(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 o$(i,t,n=0){let r=[],f=t,c=0;while(!0){if(f>=i.length||++c>128)break;let l=i[f];if(l===0){f++;break}if((l&192)===192){if(f+1>=i.length||n>=10)break;let y=i.readUInt16BE(f)&16383,{name:w}=o$(i,y,n+1);if(w)r.push(w);f+=2;break}if(f++,f+l>i.length)break;r.push(i.subarray(f,f+l).toString("ascii")),f+=l}return{name:r.join("."),newOffset:f}}function NC(i,t){let{name:n,newOffset:r}=o$(i,t),f=i.readUInt16BE(r),c=i.readUInt16BE(r+2);return{question:{name:n,type:f,class:c},newOffset:r+4}}function nr(i){let t=i.split("."),n=[];for(let r of t)n.push(Buffer.from([r.length])),n.push(Buffer.from(r,"ascii"));return n.push(Buffer.from([0])),Buffer.concat(n)}function RC(i,t,n){let r=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),r.push(f),r.push(nr(t.name));let c=Buffer.alloc(4);c.writeUInt16BE(t.type,0),c.writeUInt16BE(t.class,2),r.push(c),r.push(nr(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),r.push(l);let y=n.split(".").map((w)=>Number.parseInt(w,10));r.push(Buffer.from(y))}else if(t.type===28)l.writeUInt16BE(16,8),r.push(l),r.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,nr(t.name),c]);return Buffer.concat(r)}function XC(i,t){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(i,0),r.writeUInt16BE(33155,2),r.writeUInt16BE(1,4),r.writeUInt16BE(0,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(nr(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),n.push(f),Buffer.concat(n)}async function WC(i,t){if(Et.platform!=="darwin")return!1;let n=Dl(i);if(n.length===0)return!1;if(Ni){for(let r of n)pf.add(r);return Y("dns","DNS server already running — merged domains",t),!0}return pf=new Set(n),new Promise((r)=>{Ni=D$.createSocket("udp4"),Ni.on("error",(f)=>{Y("dns",`DNS server error: ${f.message}`,t),Ni?.close(),Ni=null,r(!1)}),Ni.on("message",(f,c)=>{try{let l=v$(f),{question:y}=NC(f,12);Y("dns",`Query for ${y.name} type ${y.type} from ${c.address}`,t);let w=y.name.toLowerCase(),u=!1;for(let $ of pf)if(w===$||w.endsWith(`.${$}`)){u=!0;break}let h;if(u&&(y.type===1||y.type===28))h=RC(l.id,y,"127.0.0.1"),Y("dns",`Responding with localhost for ${y.name}`,t);else h=XC(l.id,y),Y("dns",`NXDOMAIN for ${y.name}`,t);Ni?.send(h,c.port,c.address)}catch(l){Y("dns",`Error processing DNS query: ${l}`,t)}}),Ni.on("listening",()=>{let f=Ni?.address();Y("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),r(!0)});try{Ni.bind(i0,"127.0.0.1")}catch(f){Y("dns",`Failed to bind DNS server: ${f}`,t),r(!1)}})}function p$(i){if(Ni)Y("dns","Stopping DNS server",i),Ni.close(),Ni=null,pf=new Set}function jW(){return Ni!==null}async function SC(i,t=500){let n=i.trim().toLowerCase().replace(/\.$/,"");if(!n)return!1;return new Promise((r)=>{let f=D$.createSocket("udp4"),c=setTimeout(()=>{f.close(),r(!1)},t);f.on("message",(y)=>{clearTimeout(c),f.close();try{let w=v$(y);r(w.ancount>0)}catch{r(!1)}}),f.on("error",()=>{clearTimeout(c),f.close(),r(!1)});let l=aC(n,1);f.send(l,i0,"127.0.0.1",(y)=>{if(y)clearTimeout(c),f.close(),r(!1)})})}function aC(i,t){let n=Buffer.alloc(12);n.writeUInt16BE(1,0),n.writeUInt16BE(256,2),n.writeUInt16BE(1,4);let r=Buffer.concat([nr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([n,r])}function JC(){return`${jC}
249
249
  nameserver 127.0.0.1
250
- port ${pf}
251
- `}function nr(i){return b$.join(P$,i)}function JC(i){return i.includes("127.0.0.1")&&i.includes(String(pf))}async function FC(i){try{return await D$.readFile(nr(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Dl(i){if(Et.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:n,isProcessElevated:r}=await import("./chunk-22h4jf2c.js");if(!r()&&!n()){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(f){Y("dns",`Could not flush DNS cache: ${f}`,i)}}function p$(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function IC(i,t){p$(i);let{execSudoSync:n}=await import("./chunk-22h4jf2c.js"),r=aC().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${P$} && printf "%b" "${r}" > ${nr(i)}'`;n(f),Y("dns",`Created ${nr(i)}`,t)}async function KC(i,t){p$(i);let{execSudoSync:n}=await import("./chunk-22h4jf2c.js");n(`rm -f ${nr(i)}`),Y("dns",`Removed ${nr(i)}`,t)}async function jW(i,t){return t1({domains:t??[],verbose:i})}async function _C(i,t){if(Et.platform!=="darwin")return!0;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-22h4jf2c.js");if(!r()&&!n())return Y("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await IC(f,t);return await Dl(t),!0}catch(f){return Y("dns",`Failed to create resolver file: ${f}`,t),!1}}async function bl(i,t){if(Et.platform!=="darwin")return;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-22h4jf2c.js");if(!r()&&!n())return;try{for(let f of i)await KC(f,t);await Dl(t)}catch(f){Y("dns",`Failed to remove resolver files: ${f}`,t)}}async function i1(i){if(Et.platform!=="darwin")return[];let t=[];for(let n of L$){let r=await FC(n);if(r&&JC(r))await bl([n],i),t.push(n)}return t}async function t1(i){let t=i.rpxDir??ji(),n=dl(i.domains);if(n.length===0)return!1;let r=Vl(n),f=await XC(n,i.verbose);if(!f){let y=n[0];if(y&&await WC(y))f=!0;else Y("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await _C(r,i.verbose))return!1;let l={version:Zf,resolvers:r,domains:n,ownerPid:i.ownerPid??Et.pid,updatedAt:new Date().toISOString()};return await k$(t,l),!0}async function ir(i,t={}){let n=i.map((w)=>w.to).filter(Boolean),r=t.rpxDir??ji(),f=Vl(n),y=((await vf(r))?.resolvers??[]).filter((w)=>!f.includes(w));if(y.length>0)await bl(y,t.verbose);if(f.length===0){o$(t.verbose),await kl(r);return}await t1({domains:n,rpxDir:r,verbose:t.verbose,ownerPid:t.ownerPid??Et.pid})}async function Nn(i={}){let t=i.rpxDir??ji();o$(i.verbose);let r=(await vf(t))?.resolvers??[];await bl(r,i.verbose),await i1(i.verbose),await kl(t)}async function NW(i){await Nn({verbose:i})}async function Rn(i={}){let t=i.rpxDir??ji(),n=await vf(t),r=n?.ownerPid!=null&&Ui(n.ownerPid);if(n&&!r){Y("dns",`reconcile: owner pid ${n.ownerPid} is gone — tearing down DNS`,i.verbose),await Nn(i);return}let f=await i1(i.verbose);if(f.length>0)Y("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await Dl(i.verbose)}
252
- export{J as a,Nh as b,UB as c,Qt as d,tl as e,nl as f,jB as g,NB as h,Di as i,At as j,rl as k,gn as l,fl as m,Rh as n,Mf as o,sn as p,Ln as q,cl as r,ul as s,Ih as t,Kh as u,hl as v,KR as w,_R as x,zR as y,zh as z,$l as A,Al as B,Tl as C,QR as D,Qh as E,Oh as F,Gh as G,Hh as H,Gf as I,xn as J,qh as K,El as L,sB as M,Lh as N,xh as O,xR as P,oh as Q,ph as R,Ee as S,Ye as T,Be as U,i$ as V,f$ as W,el as X,Cl as Y,c$ as Z,w$ as _,gf as $,ml as aa,u$ as ba,Ot as ca,je as da,Ul as ea,jl as fa,Nl as ga,Ne as ha,Xl as ia,We as ja,$$ as ka,sf as la,al as ma,A$ as na,ze as oa,Qe as pa,Oe as qa,Jl as ra,AX as sa,C$ as ta,Fl as ua,m$ as va,YX as wa,Wt as xa,Kl as ya,Ui as za,j$ as Aa,zl as Ba,se as Ca,Tt as Da,Dn as Ea,Vf as Fa,Ml as Ga,mn as Ha,W$ as Ia,S$ as Ja,J$ as Ka,on as La,_$ as Ma,cC as Na,lC as Oa,GX as Pa,HX as Qa,qX as Ra,gX as Sa,pn as Ta,Zf as Ua,L$ as Va,V$ as Wa,mC as Xa,Vl as Ya,dl as Za,pf as _a,UC as $a,XC as ab,o$ as bb,UW as cb,WC as db,nr as eb,JC as fb,jW as gb,i1 as hb,t1 as ib,ir as jb,Nn as kb,NW as lb,Rn as mb,ji as nb,Pf as ob,jn as pb,wC as qb,q$ as rb,Un as sb,wW as tb,BC as ub,uW as vb,hW as wb,$W as xb};
250
+ port ${i0}
251
+ `}function rr(i){return P$.join(Z$,i)}function FC(i){return i.includes("127.0.0.1")&&i.includes(String(i0))}async function IC(i){try{return await b$.readFile(rr(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function bl(i){if(Et.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:n,isProcessElevated:r}=await import("./chunk-q0831dgh.js");if(!r()&&!n()){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(f){Y("dns",`Could not flush DNS cache: ${f}`,i)}}function i1(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function KC(i,t){i1(i);let{execSudoSync:n}=await import("./chunk-q0831dgh.js"),r=JC().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${Z$} && printf "%b" "${r}" > ${rr(i)}'`;n(f),Y("dns",`Created ${rr(i)}`,t)}async function _C(i,t){i1(i);let{execSudoSync:n}=await import("./chunk-q0831dgh.js");n(`rm -f ${rr(i)}`),Y("dns",`Removed ${rr(i)}`,t)}async function NW(i,t){return n1({domains:t??[],verbose:i})}async function zC(i,t){if(Et.platform!=="darwin")return!0;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-q0831dgh.js");if(!r()&&!n())return Y("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await KC(f,t);return await bl(t),!0}catch(f){return Y("dns",`Failed to create resolver file: ${f}`,t),!1}}async function Pl(i,t){if(Et.platform!=="darwin")return;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-q0831dgh.js");if(!r()&&!n())return;try{for(let f of i)await _C(f,t);await bl(t)}catch(f){Y("dns",`Failed to remove resolver files: ${f}`,t)}}async function t1(i){if(Et.platform!=="darwin")return[];let t=[];for(let n of x$){let r=await IC(n);if(r&&FC(r))await Pl([n],i),t.push(n)}return t}async function n1(i){let t=i.rpxDir??ji(),n=Dl(i.domains);if(n.length===0)return!1;let r=dl(n),f=await WC(n,i.verbose);if(!f){let y=n[0];if(y&&await SC(y))f=!0;else Y("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await zC(r,i.verbose))return!1;let l={version:vf,resolvers:r,domains:n,ownerPid:i.ownerPid??Et.pid,updatedAt:new Date().toISOString()};return await V$(t,l),!0}async function tr(i,t={}){let n=i.map((w)=>w.to).filter(Boolean),r=t.rpxDir??ji(),f=dl(n),y=((await of(r))?.resolvers??[]).filter((w)=>!f.includes(w));if(y.length>0)await Pl(y,t.verbose);if(f.length===0){p$(t.verbose),await Vl(r);return}await n1({domains:n,rpxDir:r,verbose:t.verbose,ownerPid:t.ownerPid??Et.pid})}async function Nn(i={}){let t=i.rpxDir??ji();p$(i.verbose);let r=(await of(t))?.resolvers??[];await Pl(r,i.verbose),await t1(i.verbose),await Vl(t)}async function RW(i){await Nn({verbose:i})}async function Rn(i={}){let t=i.rpxDir??ji(),n=await of(t),r=n?.ownerPid!=null&&Ui(n.ownerPid);if(n&&!r){Y("dns",`reconcile: owner pid ${n.ownerPid} is gone — tearing down DNS`,i.verbose),await Nn(i);return}let f=await t1(i.verbose);if(f.length>0)Y("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await bl(i.verbose)}
252
+ export{J as a,Rh as b,jB as c,Qt as d,nl as e,rl as f,NB as g,RB as h,Di as i,At as j,fl as k,gn as l,cl as m,Xh as n,Of as o,Ln as p,sn as q,ll as r,hl as s,Kh as t,_h as u,$l as v,_R as w,zR as x,QR as y,Qh as z,Al as A,Tl as B,El as C,MR as D,Mh as E,Gh as F,Hh as G,qh as H,Hf as I,xn as J,gh as K,Yl as L,sB as M,xh as N,kh as O,kR as P,ph as Q,i$ as R,Ye as S,Be as T,ee as U,t$ as V,c$ as W,Cl as X,ml as Y,l$ as Z,u$ as _,Lf as $,Ul as aa,h$ as ba,Ot as ca,Ne as da,jl as ea,Nl as fa,Rl as ga,Dn as ha,Re as ia,Wl as ja,Se as ka,A$ as la,sf as ma,Jl as na,T$ as oa,Qe as pa,Me as qa,Ge as ra,Fl as sa,TX as ta,m$ as ua,Il as va,U$ as wa,BX as xa,Wt as ya,_l as za,Ui as Aa,N$ as Ba,Ql as Ca,se as Da,Tt as Ea,bn as Fa,df as Ga,Ol as Ha,mn as Ia,S$ as Ja,a$ as Ka,F$ as La,pn as Ma,z$ as Na,lC as Oa,yC as Pa,HX as Qa,qX as Ra,gX as Sa,LX as Ta,ir as Ua,vf as Va,x$ as Wa,d$ as Xa,UC as Ya,dl as Za,Dl as _a,i0 as $a,jC as ab,WC as bb,p$ as cb,jW as db,SC as eb,rr as fb,FC as gb,NW as hb,t1 as ib,n1 as jb,tr as kb,Nn as lb,RW as mb,Rn as nb,ji as ob,Zf as pb,jn as qb,uC as rb,g$ as sb,Un as tb,uW as ub,eC as vb,hW as wb,$W as xb,AW as yb};