@stacksjs/rpx 0.11.34 → 0.11.35
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,24 +1,24 @@
|
|
|
1
|
-
import{Ab as Hl,Bb as I$,Db as Rt,Eb as Y,Fb as G$,Jb as ah,Kb as hl,Mb as Gf,Nb as Jh,Pb as f$,Qb as Fh,zb as L}from"./chunk-35444zrq.js";import D$ from"node:dgram";import*as b$ from"node:fs/promises";import*as P$ from"node:path";import*as Yt from"node:process";import{spawn as H$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as q$}from"node:os";import*as Zi from"node:path";import*as U from"node:process";var S={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as wl}from"node:child_process";import Z from"node:fs/promises";import*as ul from"node:os";import{homedir as Cn}from"node:os";import*as Ih from"node:path";import{join as D}from"node:path";import*as xi from"node:process";import{createRequire as l1}from"node:module";import{Resolver as l0}from"node:dns/promises";import{createHash as w1,sign as u1}from"node:crypto";import{createHash as h1}from"node:crypto";import{sign as $1}from"node:crypto";import{generateKeyPairSync as rw,X509Certificate as U1}from"node:crypto";import y0 from"node:os";import w0 from"node:path";import{existsSync as pl,statSync as iy}from"fs";import{existsSync as N1,mkdirSync as dC,readdirSync as DC,readFileSync as R1,writeFileSync as bC}from"fs";import{homedir as xt}from"os";import{dirname as vC,resolve as Ji}from"path";import Vr from"process";import{existsSync as ty,statSync as ny}from"fs";import{existsSync as _0,mkdirSync as X1,readdirSync as W1,writeFileSync as S1}from"fs";import{homedir as kt}from"os";import{dirname as ry,resolve as Yi}from"path";import _t from"process";import{join as a1,relative as J1,resolve as fy}from"path";import Jr from"process";import{existsSync as fw,mkdirSync as ym,readdirSync as wm,writeFileSync as um}from"fs";import{homedir as u0}from"os";import{dirname as Am,resolve as Ei}from"path";import In from"process";import{join as F1,relative as I1,resolve as cy}from"path";import Fr from"process";import{existsSync as cw,mkdirSync as em,readdirSync as Cm,writeFileSync as mm}from"fs";import{dirname as jm,resolve as Ir}from"path";import z0 from"process";import{Buffer as et}from"buffer";import{createCipheriv as K1,createDecipheriv as _1,randomBytes as h0}from"crypto";import{closeSync as $0,createReadStream as ly,createWriteStream as z1,existsSync as A0,fsyncSync as yy,openSync as wy,writeFileSync as Q1}from"fs";import{access as M1,constants as uy,mkdir as O1,readdir as cr,rename as hy,stat as Vt,unlink as lr,writeFile as T0}from"fs/promises";import{join as dt}from"path";import yi from"process";import{pipeline as G1}from"stream/promises";import{createGzip as $y}from"zlib";import Dt from"process";import tt from"process";import{Buffer as oi}from"buffer";import{createCipheriv as H1,createDecipheriv as q1,randomBytes as E0}from"crypto";import{closeSync as Y0,createReadStream as Ay,createWriteStream as g1,existsSync as yr,fsyncSync as Ty,openSync as Ey,writeFileSync as L1}from"fs";import{access as s1,constants as Yy,mkdir as x1,readdir as wr,rename as By,stat as bt,unlink as ur,writeFile as B0}from"fs/promises";import{isAbsolute as k1,join as Pt,resolve as V1}from"path";import H from"process";import{pipeline as d1}from"stream/promises";import{createGzip as ey}from"zlib";import Zt from"process";import nt from"process";import hr from"process";import{existsSync as $r}from"fs";import{resolve as e0}from"path";import{existsSync as D1}from"fs";import{existsSync as b1,readdirSync as P1}from"fs";import{extname as C0,resolve as Cy}from"path";import Z1 from"process";import{join as v1,relative as o1,resolve as my}from"path";import Kr from"process";import{Buffer as pi}from"buffer";import{createCipheriv as p1,createDecipheriv as iA,randomBytes as m0}from"crypto";import{closeSync as U0,createReadStream as Uy,createWriteStream as tA,existsSync as Ar,fsyncSync as jy,openSync as Ny,writeFileSync as nA}from"fs";import{access as rA,constants as Ry,mkdir as fA,readdir as Tr,rename as Xy,stat as vt,unlink as Er,writeFile as j0}from"fs/promises";import{isAbsolute as cA,join as ot,resolve as lA}from"path";import q from"process";import{pipeline as yA}from"stream/promises";import{createGzip as Wy}from"zlib";import pt from"process";import rt from"process";import Yr from"process";import{existsSync as Br}from"fs";import{resolve as N0}from"path";import{existsSync as wA}from"fs";import{exec as IT}from"node:child_process";import k0 from"node:fs";import KT from"node:os";import Oi from"node:path";import Lw from"node:process";import{promisify as _T}from"node:util";import fn from"node:crypto";import ft from"node:fs";import D0 from"node:path";import tE from"node:crypto";import nE from"node:fs";import rE from"node:tls";import{execSync as lE}from"node:child_process";import xr from"node:os";var y1=l1(import.meta.url),xy=30000;async function mr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function ky(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new l0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new l0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new l0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Fn{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Fn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Fn.PATH_PREFIX.length);return this.get(n)}}var kr=new Fn;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function J0(i){return Buffer.from(i,"base64url")}function Vy(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function dy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return w1("sha256").update(t).digest("base64url")}function Dy(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),c=n===""?"":Ur(JSON.stringify(n)),l=`${f}.${c}`,y=u1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Ur(y)}}var by="https://acme-staging-v02.api.letsencrypt.org/directory",Py="https://acme-v02.api.letsencrypt.org/directory";class Sr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class ar{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=Vy(i.accountPublicKey),this.thumbprint=dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??xy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await mr(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await mr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=Dy({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await mr(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Sr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return h1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Sr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Zy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
|
|
1
|
+
import{Ab as Hl,Bb as I$,Db as Rt,Eb as Y,Fb as G$,Jb as ah,Kb as hl,Mb as Gf,Nb as Jh,Pb as f$,Qb as Fh,zb as L}from"./chunk-35444zrq.js";import D$ from"node:dgram";import*as b$ from"node:fs/promises";import*as P$ from"node:path";import*as Yt from"node:process";import{spawn as H$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as q$}from"node:os";import*as Zi from"node:path";import*as U from"node:process";var S={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as wl}from"node:child_process";import Z from"node:fs/promises";import*as ul from"node:os";import{homedir as en}from"node:os";import*as Ih from"node:path";import{join as D}from"node:path";import*as xi from"node:process";import{createRequire as l1}from"node:module";import{Resolver as l0}from"node:dns/promises";import{createHash as w1,sign as u1}from"node:crypto";import{createHash as h1}from"node:crypto";import{sign as $1}from"node:crypto";import{generateKeyPairSync as rw,X509Certificate as U1}from"node:crypto";import y0 from"node:os";import w0 from"node:path";import{existsSync as pl,statSync as iy}from"fs";import{existsSync as N1,mkdirSync as de,readdirSync as De,readFileSync as R1,writeFileSync as be}from"fs";import{homedir as xt}from"os";import{dirname as ve,resolve as Ji}from"path";import Vr from"process";import{existsSync as ty,statSync as ny}from"fs";import{existsSync as _0,mkdirSync as X1,readdirSync as W1,writeFileSync as S1}from"fs";import{homedir as kt}from"os";import{dirname as ry,resolve as Yi}from"path";import _t from"process";import{join as a1,relative as J1,resolve as fy}from"path";import Jr from"process";import{existsSync as fw,mkdirSync as ym,readdirSync as wm,writeFileSync as um}from"fs";import{homedir as u0}from"os";import{dirname as Am,resolve as Ei}from"path";import In from"process";import{join as F1,relative as I1,resolve as cy}from"path";import Fr from"process";import{existsSync as cw,mkdirSync as Cm,readdirSync as em,writeFileSync as mm}from"fs";import{dirname as jm,resolve as Ir}from"path";import z0 from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as K1,createDecipheriv as _1,randomBytes as h0}from"crypto";import{closeSync as $0,createReadStream as ly,createWriteStream as z1,existsSync as A0,fsyncSync as yy,openSync as wy,writeFileSync as Q1}from"fs";import{access as M1,constants as uy,mkdir as O1,readdir as cr,rename as hy,stat as Vt,unlink as lr,writeFile as T0}from"fs/promises";import{join as dt}from"path";import yi from"process";import{pipeline as G1}from"stream/promises";import{createGzip as $y}from"zlib";import Dt from"process";import tt from"process";import{Buffer as oi}from"buffer";import{createCipheriv as H1,createDecipheriv as q1,randomBytes as E0}from"crypto";import{closeSync as Y0,createReadStream as Ay,createWriteStream as g1,existsSync as yr,fsyncSync as Ty,openSync as Ey,writeFileSync as L1}from"fs";import{access as s1,constants as Yy,mkdir as x1,readdir as wr,rename as By,stat as bt,unlink as ur,writeFile as B0}from"fs/promises";import{isAbsolute as k1,join as Pt,resolve as V1}from"path";import H from"process";import{pipeline as d1}from"stream/promises";import{createGzip as Cy}from"zlib";import Zt from"process";import nt from"process";import hr from"process";import{existsSync as $r}from"fs";import{resolve as C0}from"path";import{existsSync as D1}from"fs";import{existsSync as b1,readdirSync as P1}from"fs";import{extname as e0,resolve as ey}from"path";import Z1 from"process";import{join as v1,relative as o1,resolve as my}from"path";import Kr from"process";import{Buffer as pi}from"buffer";import{createCipheriv as p1,createDecipheriv as iA,randomBytes as m0}from"crypto";import{closeSync as U0,createReadStream as Uy,createWriteStream as tA,existsSync as Ar,fsyncSync as jy,openSync as Ny,writeFileSync as nA}from"fs";import{access as rA,constants as Ry,mkdir as fA,readdir as Tr,rename as Xy,stat as vt,unlink as Er,writeFile as j0}from"fs/promises";import{isAbsolute as cA,join as ot,resolve as lA}from"path";import q from"process";import{pipeline as yA}from"stream/promises";import{createGzip as Wy}from"zlib";import pt from"process";import rt from"process";import Yr from"process";import{existsSync as Br}from"fs";import{resolve as N0}from"path";import{existsSync as wA}from"fs";import{exec as IT}from"node:child_process";import k0 from"node:fs";import KT from"node:os";import Oi from"node:path";import Lw from"node:process";import{promisify as _T}from"node:util";import fn from"node:crypto";import ft from"node:fs";import D0 from"node:path";import tE from"node:crypto";import nE from"node:fs";import rE from"node:tls";import{execSync as lE}from"node:child_process";import xr from"node:os";var y1=l1(import.meta.url),xy=30000;async function mr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function ky(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new l0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new l0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new l0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Fn{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Fn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Fn.PATH_PREFIX.length);return this.get(n)}}var kr=new Fn;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function J0(i){return Buffer.from(i,"base64url")}function Vy(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function dy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return w1("sha256").update(t).digest("base64url")}function Dy(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),c=n===""?"":Ur(JSON.stringify(n)),l=`${f}.${c}`,y=u1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Ur(y)}}var by="https://acme-staging-v02.api.letsencrypt.org/directory",Py="https://acme-v02.api.letsencrypt.org/directory";class Sr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class ar{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=Vy(i.accountPublicKey),this.thumbprint=dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??xy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await mr(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await mr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=Dy({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await mr(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Sr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return h1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Sr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Zy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
|
|
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 vy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function ol(i){return new Promise((t)=>setTimeout(t,i))}function A1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Ut(i,t){return Buffer.concat([Buffer.from([i]),A1(t.length),t])}function oy(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ut(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return Ut(6,Buffer.from(n))}function ai(...i){return Ut(48,Buffer.concat(i))}function F0(...i){return Ut(49,Buffer.concat(i))}function I0(i){return Ut(3,Buffer.concat([Buffer.from([0]),i]))}function py(i){return Ut(4,i)}function iw(i){return Ut(12,Buffer.from(i,"utf8"))}function K0(i,t,n){let r=128|(n?32:0)|i;return Ut(r,t)}var T1="1.2.840.10045.2.1",E1="1.2.840.10045.3.1.7",Y1="1.2.840.10045.4.3.2",B1="2.5.4.3",e1="1.2.840.113549.1.9.14",C1="2.5.29.17";function m1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=J0(t.x),r=J0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function tw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(F0(ai(Kt(B1),iw(t[0])))),c=ai(ai(Kt(T1),Kt(E1)),I0(m1(n))),l=t.map((E)=>K0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(C1),py(y)),u=ai(w),h=ai(Kt(e1),F0(u)),$=K0(0,h,!0),A=ai(oy(0),f,c,$),T=$1("sha256",A,r),e=ai(Kt(Y1));return ai(A,e,I0(T))}function nw(i){return tw(i).toString("base64url")}function j1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=y1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=rw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function b0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Py:by),f=j1(i.accountKeyPem),c=new ar({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??kr,u=[],h=[];try{for(let F of l.authorizations){let a=await c.getAuthorization(F);if(a.status==="valid")continue;let J=ar.selectChallenge(a,n);if(n==="dns-01"){let v=vy(a.identifier.value),Mi=c.dns01TxtValue(J.token);await i.dnsProvider.setTxt(v,Mi),u.push({name:v,value:Mi}),await ky(v,Mi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(J.token,c.keyAuthorization(J.token)),h.push(J.token);await c.notifyChallengeReady(J.url),await c.pollAuthorization(F,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=rw("ec",{namedCurve:"P-256"}),T=nw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let e=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(e),{certPem:B,chainPem:C}=Zy(E),j=C?`${B}${C}`:B,X=$.export({format:"pem",type:"pkcs8"}).toString(),W=new Date(new U1(B).validTo);return{certPem:B,keyPem:X,chainPem:C,fullChainPem:j,accountKeyPem:f.pem,notAfter:W}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class lw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!pl(i))return!0;return iy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=pl(n)?iy(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class yw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new lw,P0=new yw,uA=Object.defineProperty,hA=(i)=>i;function $A(i,t){this[i]=hA.bind(null,t)}var AA=(i,t)=>{for(var n in t)uA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:$A.bind(t,n)})},TA=(i,t)=>()=>(i&&(t=i(i=0)),t),ww={};AA(ww,{withErrorRecovery:()=>$w,tryLoadConfig:()=>OA,loadConfigWithResult:()=>QA,loadConfig:()=>Bw,isRetryableError:()=>JA,isConfigNotFoundError:()=>aA,isBunfigError:()=>Aw,globalPerformanceMonitor:()=>Qn,globalCache:()=>nn,getEnvOrDefault:()=>FA,generateConfigTypes:()=>GA,defaultGeneratedDir:()=>Xw,defaultConfigDir:()=>Rw,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>Tw,createLibraryConfig:()=>HA,config:()=>MA,bunfigPlugin:()=>qA,applyEnvVarsToConfig:()=>an,TypeGenerationError:()=>g0,SchemaValidationError:()=>_n,PluginError:()=>s0,PerformanceMonitor:()=>v0,FileSystemError:()=>q0,ErrorFactory:()=>mt,EnvVarError:()=>Hr,EnvProcessor:()=>dr,ConfigValidator:()=>tc,ConfigValidationError:()=>G0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>H0,ConfigLoader:()=>nc,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>Dr,ConfigCache:()=>Z0,CacheUtils:()=>Cw,BunfigError:()=>Ri,BrowserConfigError:()=>L0,ArrayMergeStrategies:()=>jw});class Z0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ty(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ty(n)?ny(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class v0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function EA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function YA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function BA(i){return i.getStats().size*2}function o0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>zr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=o0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>zr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function zr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function eA(i,t){if(!cw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return o0(t,r)}catch{return null}}catch{return null}}async function CA({name:i="",cwd:t,defaultConfig:n}){let r=t||z0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Ir(r,`${l}${y}`),u=await eA(w,n);if(u!==null)return u}try{let l=Ir(r,"package.json");if(cw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(n,y)}catch{}}}catch{}return n}function mA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=cy(n,"..");let r=cy(n,i||"");if(t?.relative)return I1(Fr.cwd(),r);return r}async function UA(){try{let i=await CA({name:"clarity",defaultConfig:Nr,cwd:Fr.cwd(),endpoint:"",headers:{}});return{...Nr,...i}}catch{return Nr}}function b(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class uw{async format(i){let t=await jA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...M0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rr};return{...Rr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:M0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await M1(this.config.logDirectory,uy.F_OK|uy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await O1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:et.from(i);try{if(!A0(this.currentLogFile))await T0(this.currentLogFile,"",{mode:420});if(r=wy(this.currentLogFile,"a",420),Q1(r,y,{flag:"a"}),yy(r),r!==void 0)$0(r),r=void 0;if((await Vt(this.currentLogFile)).size===0){if(await T0(this.currentLogFile,y,{flag:"w",mode:420}),(await Vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{$0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return dt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return dt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return dt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return h0(16).toString("hex")}generateKey(){return h0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=h0(16),r=K1("aes-256-gcm",t,n),f=et.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:et.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=$y(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(et.from(et.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await Vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Vt(n).catch(()=>null))try{if(await hy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await lr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await T0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Vt(n).catch(()=>null))await hy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await cr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await lr(dt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=ly(i),r=z1(t),f=$y();await G1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),A0(this.currentLogFile))try{let i=wy(this.currentLogFile,"r+");yy(i),$0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await lr(dt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=mw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
|
|
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 Ut(i,t){return Buffer.concat([Buffer.from([i]),A1(t.length),t])}function oy(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ut(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return Ut(6,Buffer.from(n))}function ai(...i){return Ut(48,Buffer.concat(i))}function F0(...i){return Ut(49,Buffer.concat(i))}function I0(i){return Ut(3,Buffer.concat([Buffer.from([0]),i]))}function py(i){return Ut(4,i)}function iw(i){return Ut(12,Buffer.from(i,"utf8"))}function K0(i,t,n){let r=128|(n?32:0)|i;return Ut(r,t)}var T1="1.2.840.10045.2.1",E1="1.2.840.10045.3.1.7",Y1="1.2.840.10045.4.3.2",B1="2.5.4.3",C1="1.2.840.113549.1.9.14",e1="2.5.29.17";function m1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=J0(t.x),r=J0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function tw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(F0(ai(Kt(B1),iw(t[0])))),c=ai(ai(Kt(T1),Kt(E1)),I0(m1(n))),l=t.map((E)=>K0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(e1),py(y)),u=ai(w),h=ai(Kt(C1),F0(u)),$=K0(0,h,!0),A=ai(oy(0),f,c,$),T=$1("sha256",A,r),C=ai(Kt(Y1));return ai(A,C,I0(T))}function nw(i){return tw(i).toString("base64url")}function j1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=y1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=rw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function b0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Py:by),f=j1(i.accountKeyPem),c=new ar({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??kr,u=[],h=[];try{for(let F of l.authorizations){let a=await c.getAuthorization(F);if(a.status==="valid")continue;let J=ar.selectChallenge(a,n);if(n==="dns-01"){let v=vy(a.identifier.value),Mi=c.dns01TxtValue(J.token);await i.dnsProvider.setTxt(v,Mi),u.push({name:v,value:Mi}),await ky(v,Mi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(J.token,c.keyAuthorization(J.token)),h.push(J.token);await c.notifyChallengeReady(J.url),await c.pollAuthorization(F,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=rw("ec",{namedCurve:"P-256"}),T=nw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let C=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(C),{certPem:B,chainPem:e}=Zy(E),j=e?`${B}${e}`:B,X=$.export({format:"pem",type:"pkcs8"}).toString(),W=new Date(new U1(B).validTo);return{certPem:B,keyPem:X,chainPem:e,fullChainPem:j,accountKeyPem:f.pem,notAfter:W}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class lw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!pl(i))return!0;return iy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=pl(n)?iy(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class yw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new lw,P0=new yw,uA=Object.defineProperty,hA=(i)=>i;function $A(i,t){this[i]=hA.bind(null,t)}var AA=(i,t)=>{for(var n in t)uA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:$A.bind(t,n)})},TA=(i,t)=>()=>(i&&(t=i(i=0)),t),ww={};AA(ww,{withErrorRecovery:()=>$w,tryLoadConfig:()=>OA,loadConfigWithResult:()=>QA,loadConfig:()=>Bw,isRetryableError:()=>JA,isConfigNotFoundError:()=>aA,isBunfigError:()=>Aw,globalPerformanceMonitor:()=>Qn,globalCache:()=>nn,getEnvOrDefault:()=>FA,generateConfigTypes:()=>GA,defaultGeneratedDir:()=>Xw,defaultConfigDir:()=>Rw,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>Tw,createLibraryConfig:()=>HA,config:()=>MA,bunfigPlugin:()=>qA,applyEnvVarsToConfig:()=>an,TypeGenerationError:()=>g0,SchemaValidationError:()=>_n,PluginError:()=>s0,PerformanceMonitor:()=>v0,FileSystemError:()=>q0,ErrorFactory:()=>mt,EnvVarError:()=>Hr,EnvProcessor:()=>dr,ConfigValidator:()=>tc,ConfigValidationError:()=>G0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>H0,ConfigLoader:()=>nc,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>Dr,ConfigCache:()=>Z0,CacheUtils:()=>ew,BunfigError:()=>Ri,BrowserConfigError:()=>L0,ArrayMergeStrategies:()=>jw});class Z0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ty(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ty(n)?ny(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class v0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function EA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function YA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function BA(i){return i.getStats().size*2}function o0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>zr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=o0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>zr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function zr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function CA(i,t){if(!cw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return o0(t,r)}catch{return null}}catch{return null}}async function eA({name:i="",cwd:t,defaultConfig:n}){let r=t||z0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Ir(r,`${l}${y}`),u=await CA(w,n);if(u!==null)return u}try{let l=Ir(r,"package.json");if(cw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(n,y)}catch{}}}catch{}return n}function mA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=cy(n,"..");let r=cy(n,i||"");if(t?.relative)return I1(Fr.cwd(),r);return r}async function UA(){try{let i=await eA({name:"clarity",defaultConfig:Nr,cwd:Fr.cwd(),endpoint:"",headers:{}});return{...Nr,...i}}catch{return Nr}}function b(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class uw{async format(i){let t=await jA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...M0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rr};return{...Rr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:M0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await M1(this.config.logDirectory,uy.F_OK|uy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await O1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Ct.from(i);try{if(!A0(this.currentLogFile))await T0(this.currentLogFile,"",{mode:420});if(r=wy(this.currentLogFile,"a",420),Q1(r,y,{flag:"a"}),yy(r),r!==void 0)$0(r),r=void 0;if((await Vt(this.currentLogFile)).size===0){if(await T0(this.currentLogFile,y,{flag:"w",mode:420}),(await Vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{$0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return dt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return dt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return dt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return h0(16).toString("hex")}generateKey(){return h0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=h0(16),r=K1("aes-256-gcm",t,n),f=Ct.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Ct.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(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(b())return;let i=await Vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Vt(n).catch(()=>null))try{if(await hy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await lr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await T0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Vt(n).catch(()=>null))await hy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await cr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await lr(dt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=ly(i),r=z1(t),f=$y();await G1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),A0(this.currentLogFile))try{let i=wy(this.currentLogFile,"r+");yy(i),$0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await lr(dt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=mw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
|
|
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 Qr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!A0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ly(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=
|
|
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(!A0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ly(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Ct.isBuffer(i)?i:Ct.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),Ct.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
|
-
`.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,
|
|
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=dt(this.config.logDirectory,r);if(i.before)try{if((await Vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await lr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let r=[...t];for(let f of i)if(g(f)&&"name"in f){if(!r.find((c)=>g(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(g(f)&&"path"in f){if(!r.find((c)=>g(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!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 p0(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]=p0(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 p0(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=In.env[T]||In.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||In.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 j of C)for(let X of h){let W=Ei(B,`${j}${X}`),F=await er(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from: ${W}`);return F}}}if(i){let B=Ei(u0(),".config",i),C=["config",`${i}.config`];if(t)C.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${B}`);for(let j of C)for(let X of h){let W=Ei(B,`${j}${X}`),F=await er(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory: ${W}`);return F}}}if(i){let B=Ei(u0(),".config"),C=[`.${i}.config`];if(t)C.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of C)for(let X of h){let W=Ei(B,`${j}${X}`),F=await er(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${W}`);return F}}}if(i){let B=u0(),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 j of C)for(let X of h){let W=Ei(B,`${j}${X}`),F=await er(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user home directory: ${W}`);return F}}}try{let B=Ei(u,"package.json");if(fw(B)){let C=await import(B),j=C[i];if(!j&&t){if(j=C[t],j&&c)ui.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)ui.success(`Configuration loaded from package.json: ${j===C[i]?i:t}`);return p0(w,j,y)}catch(X){if(c)ui.warn("Failed to merge package.json config:",X)}}}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(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SA(){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 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:Zt.pid,hostname:t(),environment:Zt.env.NODE_ENV||"development",platform:Zt.platform,version:Zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zt.env.NODE_ENV||Zt.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={...O0},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:O0.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:oi.from(i);try{if(!yr(this.currentLogFile))await B0(this.currentLogFile,"",{mode:420});if(r=Ey(this.currentLogFile,"a",420),L1(r,y,{flag:"a"}),Ty(r),r!==void 0)Y0(r),r=void 0;if((await bt(this.currentLogFile)).size===0){if(await B0(this.currentLogFile,y,{flag:"w",mode:420}),(await bt(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{Y0(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 Pt(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 Pt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Pt(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 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=H1("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=ey(),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(p())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let 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 bt(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 B0(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 bt(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(Pt(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),Y0(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(Pt(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()?Q.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} ${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(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?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(`
|
|
14
|
-
`);for(let E of
|
|
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,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,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 cr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=dt(this.config.logDirectory,r);if(i.before)try{if((await Vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await lr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let r=[...t];for(let f of i)if(g(f)&&"name"in f){if(!r.find((c)=>g(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(g(f)&&"path"in f){if(!r.find((c)=>g(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!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 p0(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]=p0(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 Cr(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 p0(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("_")}`,C=`${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=In.env[T]||In.env[C];if(E!==void 0){if(n)ui.info(`Using environment variable ${E?T:C} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(E);else if(typeof h==="boolean")w[u]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let B=JSON.parse(E);if(Array.isArray(B))w[u]=B;else w[u]=E.split(",").map((e)=>e.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||In.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}`]:[],C=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 e=[Ei(u,"config"),Ei(u,".config")].concat(r?[Ei(u,r)]:[]).includes(B)?[...$,...A,...T,...C]:[...A,...$,...C,...T];for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from: ${W}`);return F}}}if(i){let B=Ei(u0(),".config",i),e=["config",`${i}.config`];if(t)e.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${B}`);for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory: ${W}`);return F}}}if(i){let B=Ei(u0(),".config"),e=[`.${i}.config`];if(t)e.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${W}`);return F}}}if(i){let B=u0(),e=[`.${i}.config`,`.${i}`];if(t)e.push(`.${t}.config`),e.push(`.${t}`);if(c)ui.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user home directory: ${W}`);return F}}}try{let B=Ei(u,"package.json");if(fw(B)){let e=await import(B),j=e[i];if(!j&&t){if(j=e[t],j&&c)ui.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)ui.success(`Configuration loaded from package.json: ${j===e[i]?i:t}`);return p0(w,j,y)}catch(X){if(c)ui.warn("Failed to merge package.json config:",X)}}}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(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SA(){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 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:Zt.pid,hostname:t(),environment:Zt.env.NODE_ENV||"development",platform:Zt.platform,version:Zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zt.env.NODE_ENV||Zt.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={...O0},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:O0.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:oi.from(i);try{if(!yr(this.currentLogFile))await B0(this.currentLogFile,"",{mode:420});if(r=Ey(this.currentLogFile,"a",420),L1(r,y,{flag:"a"}),Ty(r),r!==void 0)Y0(r),r=void 0;if((await bt(this.currentLogFile)).size===0){if(await B0(this.currentLogFile,y,{flag:"w",mode:420}),(await bt(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{Y0(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 Pt(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 Pt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Pt(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 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=H1("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=Cy(),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(p())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let 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 bt(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 B0(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 bt(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(Pt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Ay(i),r=g1(t),f=Cy();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),Y0(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(Pt(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()?Q.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} ${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(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?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 C=y.split(`
|
|
14
|
+
`);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:Q.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?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),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
18
18
|
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=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: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=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=q1("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 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: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(!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(`${Q.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?Q.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${y}${l} ${Q.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
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=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=H.stdout.columns||80,
|
|
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=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=H.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
|
|
22
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=Pt(this.config.logDirectory,r);if(i.before)try{if((await bt(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 Qn.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 mt.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 mt.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}
|
|
@@ -31,24 +31,24 @@ import{Ab as Hl,Bb as I$,Db as Rt,Eb as Y,Fb as G$,Jb as ah,Kb as hl,Mb as Gf,Nb
|
|
|
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 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)=>Q0(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 ic(i,t,n="replace"){return Tw(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Q0(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(!Q0(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(!Q0(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=nn.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 Kn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Kn(i,Error("Configuration must export a valid object"),"unknown");let e={config:ic(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)nn.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?mt.configLoad(i,u):mt.configLoad(i,Error(String(u)))}};if(l)return Qn.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(e0(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=e0(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=e0(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 tc{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 Qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!D1(t))throw new _n(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 _n(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 nc{fileLoader=new Dr;envProcessor=new dr;validator=new tc;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||_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 mt.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?an(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?an(i,n,f):n,y=[Yi(kt(),".config",i),Yi(kt(),".config"),kt()];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?an(i,r,c):r;try{let w=Yi(n,"package.json");if(!_0(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:ic(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:an(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 mt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return nn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);nn.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(kt(),".config",i),Yi(kt(),".config"),kt()],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 ct.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 ct.loadConfig(i);else r=await ct.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 l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ct.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 ct.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 ct.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ct.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 ct.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 an(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(!_0(ry(r)))X1(ry(r),{recursive:!0,mode:511});let f=_0(t)?W1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${AT}
|
|
34
|
+
`;return n}}function FA(i,t){let n=Cw("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)=>Q0(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 ic(i,t,n="replace"){return Tw(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Q0(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(!Q0(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(!Q0(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=nn.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 Kn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Kn(i,Error("Configuration must export a valid object"),"unknown");let C={config:ic(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)nn.setWithFileCheck("file",C,i,c);return C}catch(u){throw u instanceof Error?mt.configLoad(i,u):mt.configLoad(i,Error(String(u)))}};if(l)return Qn.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(C0(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=C0(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=C0(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 tc{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 Qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!D1(t))throw new _n(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 _n(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 nc{fileLoader=new Dr;envProcessor=new dr;validator=new tc;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||_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 C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,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 mt.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?an(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?an(i,n,f):n,y=[Yi(kt(),".config",i),Yi(kt(),".config"),kt()];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?an(i,r,c):r;try{let w=Yi(n,"package.json");if(!_0(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:ic(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:an(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 mt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return nn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);nn.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(kt(),".config",i),Yi(kt(),".config"),kt()],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 ct.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 ct.loadConfig(i);else r=await ct.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 l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ct.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 ct.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 ct.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ct.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 ct.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 an(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,C;for(let E of A)if(T=_t.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function GA(i){let t=Yi(_t.cwd(),i.configDir),n=Yi(_t.cwd(),i.generatedDir),r=Yi(n,"config-types.ts");if(!_0(ry(r)))X1(ry(r),{recursive:!0,mode:511});let f=_0(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
|
-
`;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)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 qA(i){let t=
|
|
37
|
-
${f.map((w)=>{let u=
|
|
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)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 qA(i){let t=ey(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=ey(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 ew,nn,Qn,Cw,gA,LA,ay,Nr,M0,wi,x,sA,Jy,xA,Fy,kA,VA,R0,dA,Iy,Ky,X0,DA,bA,PA,ZA,Rr,mw,vA,ui,oA,pA,_y,Xr,O0,ii,Q,iT,zy,tT,Qy,nT,rT,W0,fT,My,Oy,cT,S0,lT,yT,wT,uT,hT,Wr,Uw,$T,AT="0.15.6",Ri,Gr,Kn,G0,H0,Hr,q0,g0,_n,L0,s0,mt,jw,Nw,Gi,ct,Rw,Xw,TT=TA(async()=>{ew=import.meta.require,nn=new Z0,Qn=new v0,Cw={createKey:EA,isEquivalent:YA,estimateMemoryUsage:BA},gA=Ir(z0.cwd(),"config"),LA=Ir(z0.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},M0=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,R0=wi.white,dA=wi.gray,Iy=wi.bgRed,Ky=wi.bgYellow,X0=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(R0(X0(" WARN "))),error:Iy(R0(X0(" ERROR ")))},vA=new Qr("stacks"),ui=new Qr("bunfig",{showTags:!0}),oA=Ei(In.cwd(),"config"),pA=Ei(In.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},O0=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"},Q=ii,iT=ii.red,zy=ii.green,tT=ii.yellow,Qy=ii.blue,nT=ii.magenta,rT=ii.cyan,W0=ii.white,fT=ii.gray,My=ii.bgRed,Oy=ii.bgYellow,cT=ii.bgGray,S0=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(W0(S0(" WARN "))),error:My(W0(S0(" 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})}},Kn=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}},G0=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})}},H0=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})}},q0=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}},g0=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}},_n=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})}},L0=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})}},s0=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}},mt={configNotFound(i,t,n){return new Gr(i,t,n)},configLoad(i,t,n){return new Kn(i,t,n)},configValidation(i,t,n){return new G0(i,t,n)},configMerge(i,t,n,r){return new H0(i,t,n,r)},envVar(i,t,n,r){return new Hr(i,t,n,r)},fileSystem(i,t,n){return new q0(i,t,n)},typeGeneration(i,t,n){return new g0(i,t,n)},schemaValidation(i,t,n){return new _n(i,t,n)},browserConfig(i,t,n,r){return new L0(i,t,n,r)},plugin(i,t,n){return new s0(i,t,n)}},jw={replace:"replace",concat:"concat",smart:"smart"},Nw=/^https?:\/\//,Gi=new Or("bunfig",{showTags:!0}),ct=new nc,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},AU=(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(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BT(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rt<"u"){let i=rt.type;if(i==="renderer"||i==="worker")return!1;return!!(rt.versions&&(rt.versions.node||rt.versions.bun))}return!1}class 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:pt.pid,hostname:t(),environment:pt.env.NODE_ENV||"development",platform:pt.platform,version:pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pt.env.NODE_ENV||pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var 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"},O=ci,TU=ci.red,eT=ci.green,EU=ci.yellow,CT=ci.blue,YU=ci.magenta,BU=ci.cyan,Gy=ci.white,eU=ci.gray,mT=ci.bgRed,UT=ci.bgYellow,CU=ci.bgGray,Hy=ci.bold,mU=ci.dim,UU=ci.italic,jU=ci.underline,NU=ci.strikethrough,RU=ci.reset,a0={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{...a0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...a0};return{...a0,...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:pi.from(i);try{if(!Ar(this.currentLogFile))await j0(this.currentLogFile,"",{mode:420});if(r=Ny(this.currentLogFile,"a",420),nA(r,y,{flag:"a"}),jy(r),r!==void 0)U0(r),r=void 0;if((await vt(this.currentLogFile)).size===0){if(await j0(this.currentLogFile,y,{flag:"w",mode:420}),(await vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{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 ot(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ot(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ot(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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 m0(16).toString("hex")}generateKey(){return m0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=m0(16),r=p1("aes-256-gcm",t,n),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=pi.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(pi.from(pi.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 vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await 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 vt(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 j0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await vt(n).catch(()=>null))await 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(ot(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),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(!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(ot(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()?O.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} ${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(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?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(`
|
|
44
|
-
`);for(let E of
|
|
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 Cw,nn,Qn,ew,gA,LA,ay,Nr,M0,wi,x,sA,Jy,xA,Fy,kA,VA,R0,dA,Iy,Ky,X0,DA,bA,PA,ZA,Rr,mw,vA,ui,oA,pA,_y,Xr,O0,ii,Q,iT,zy,tT,Qy,nT,rT,W0,fT,My,Oy,cT,S0,lT,yT,wT,uT,hT,Wr,Uw,$T,AT="0.15.6",Ri,Gr,Kn,G0,H0,Hr,q0,g0,_n,L0,s0,mt,jw,Nw,Gi,ct,Rw,Xw,TT=TA(async()=>{Cw=import.meta.require,nn=new Z0,Qn=new v0,ew={createKey:EA,isEquivalent:YA,estimateMemoryUsage:BA},gA=Ir(z0.cwd(),"config"),LA=Ir(z0.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},M0=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,R0=wi.white,dA=wi.gray,Iy=wi.bgRed,Ky=wi.bgYellow,X0=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(R0(X0(" WARN "))),error:Iy(R0(X0(" ERROR ")))},vA=new Qr("stacks"),ui=new Qr("bunfig",{showTags:!0}),oA=Ei(In.cwd(),"config"),pA=Ei(In.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},O0=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"},Q=ii,iT=ii.red,zy=ii.green,tT=ii.yellow,Qy=ii.blue,nT=ii.magenta,rT=ii.cyan,W0=ii.white,fT=ii.gray,My=ii.bgRed,Oy=ii.bgYellow,cT=ii.bgGray,S0=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(W0(S0(" WARN "))),error:My(W0(S0(" 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})}},Kn=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}},G0=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})}},H0=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})}},q0=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}},g0=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}},_n=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})}},L0=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})}},s0=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}},mt={configNotFound(i,t,n){return new Gr(i,t,n)},configLoad(i,t,n){return new Kn(i,t,n)},configValidation(i,t,n){return new G0(i,t,n)},configMerge(i,t,n,r){return new H0(i,t,n,r)},envVar(i,t,n,r){return new Hr(i,t,n,r)},fileSystem(i,t,n){return new q0(i,t,n)},typeGeneration(i,t,n){return new g0(i,t,n)},schemaValidation(i,t,n){return new _n(i,t,n)},browserConfig(i,t,n,r){return new L0(i,t,n,r)},plugin(i,t,n){return new s0(i,t,n)}},jw={replace:"replace",concat:"concat",smart:"smart"},Nw=/^https?:\/\//,Gi=new Or("bunfig",{showTags:!0}),ct=new nc,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},AU=(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(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BT(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rt<"u"){let i=rt.type;if(i==="renderer"||i==="worker")return!1;return!!(rt.versions&&(rt.versions.node||rt.versions.bun))}return!1}class 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:pt.pid,hostname:t(),environment:pt.env.NODE_ENV||"development",platform:pt.platform,version:pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pt.env.NODE_ENV||pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var 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"},O=ci,TU=ci.red,CT=ci.green,EU=ci.yellow,eT=ci.blue,YU=ci.magenta,BU=ci.cyan,Gy=ci.white,CU=ci.gray,mT=ci.bgRed,UT=ci.bgYellow,eU=ci.bgGray,Hy=ci.bold,mU=ci.dim,UU=ci.italic,jU=ci.underline,NU=ci.strikethrough,RU=ci.reset,a0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jT={debug:"\uD83D\uDD0D",info:eT("ℹ"),success:CT("✓"),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{...a0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...a0};return{...a0,...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:pi.from(i);try{if(!Ar(this.currentLogFile))await j0(this.currentLogFile,"",{mode:420});if(r=Ny(this.currentLogFile,"a",420),nA(r,y,{flag:"a"}),jy(r),r!==void 0)U0(r),r=void 0;if((await vt(this.currentLogFile)).size===0){if(await j0(this.currentLogFile,y,{flag:"w",mode:420}),(await vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{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 ot(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ot(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ot(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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 m0(16).toString("hex")}generateKey(){return m0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=m0(16),r=p1("aes-256-gcm",t,n),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=pi.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(pi.from(pi.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 vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await 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 vt(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 j0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await vt(n).catch(()=>null))await 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(ot(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),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(!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(ot(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()?O.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} ${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(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?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 C=y.split(`
|
|
44
|
+
`);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:O.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?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),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
48
48
|
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":O.green("✓"),tag:u,message:`${c}${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=pi.isBuffer(i)?i:pi.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,$=pi.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: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(!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(`${O.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?O.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${y}${l} ${O.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
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=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=q.stdout.columns||80,
|
|
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=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=q.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
|
|
52
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=ot(this.config.logDirectory,r);if(i.before)try{if((await vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await 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 XU=new br("stacks");class gi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class aw extends gi{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 gi{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 gi{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 gi{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 rc extends gi{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 gi{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 gi{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 gi{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 gi{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 gi{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 rn={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 rc(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 fc{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 P0.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 rc)throw $;throw rn.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 rn.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}
|
|
@@ -61,7 +61,7 @@ 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 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)=>x0(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 x0(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(!x0(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(!x0(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?rn.configLoad(i,u):rn.configLoad(i,Error(String(u)))}};if(l)return P0.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(N0(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=N0(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=N0(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 P0.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 it=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 fc;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)it.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 it.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 rn.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)it.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)it.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(xt(),".config",i),Ji(xt(),".config"),xt()];for(let w of y){if(f)it.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)it.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)it.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)it.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)it.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 rn.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(xt(),".config",i),Ji(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)}}var WU=new qw;function Cr(i,t,n=!1){let r=new fc,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 SU=Ji(Vr.cwd(),"config"),aU=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:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var o=gw,Hi={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 R={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},tn={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 k0.readFileSync(i,"utf8")}function V0(i,t){let n=[];function r(f){let c;try{c=k0.readdirSync(f)}catch{return}for(let l of c){let y=Oi.join(f,l);try{if(k0.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||o.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 Ct(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}
|
|
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)=>x0(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 x0(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(!x0(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(!x0(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 C={config:Ow(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)_r.setWithFileCheck("file",C,i,c);return C}catch(u){throw u instanceof Error?rn.configLoad(i,u):rn.configLoad(i,Error(String(u)))}};if(l)return P0.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(N0(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=N0(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=N0(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 P0.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 it=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 fc;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)it.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 it.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 C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,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 rn.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?er(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)it.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)it.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(xt(),".config",i),Ji(xt(),".config"),xt()];for(let w of y){if(f)it.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)it.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(!N1(w))return null;let u={};try{u=JSON.parse(R1(w,"utf8"))}catch(A){if(c)it.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)it.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)it.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 rn.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(xt(),".config",i),Ji(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)}}var WU=new qw;function er(i,t,n=!1){let r=new fc,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,C;for(let E of A)if(T=Vr.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var SU=Ji(Vr.cwd(),"config"),aU=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:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var o=gw,Hi={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 R={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},tn={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 k0.readFileSync(i,"utf8")}function V0(i,t){let n=[];function r(f){let c;try{c=k0.readdirSync(f)}catch{return}for(let l of c){let y=Oi.join(f,l);try{if(k0.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||o.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
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 cc(i){let t=Oi.join(KT.homedir(),".stacks","ssl"),n=i.basePath&&i.basePath.trim()!==""?i.basePath:o.basePath&&o.basePath.trim()!==""?o.basePath:t,r=i.certPath?Oi.isAbsolute(i.certPath)?i.certPath:Oi.join(n,i.certPath):Oi.join(n,o.certPath),f=i.keyPath?Oi.isAbsolute(i.keyPath)?i.keyPath:Oi.join(n,i.keyPath):Oi.join(n,o.keyPath),c=i.caCertPath?Oi.isAbsolute(i.caCertPath)?i.caCertPath:Oi.join(n,i.caCertPath):Oi.join(n,o.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(R.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function lc(i){let t=i.notBeforeDays??Hi.DEFAULT_NOT_BEFORE_DAYS,n=i.validityDays??(i.validityYears?i.validityYears*365:Hi.DEFAULT_VALIDITY_DAYS);N(R.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(R.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:r,notAfter:f}}var qi={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 Jn(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=Jn(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function zn(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(qi.OID,Buffer.from(n))}function d0(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(qi.INTEGER,t)}function dw(i,t=0){return Wi(qi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Dw(i){return Wi(qi.OCTET_STRING,i)}function Xi(...i){return Wi(qi.SEQUENCE,Buffer.concat(i))}function HT(...i){return Wi(qi.SET,Buffer.concat(i))}function qT(i){return Wi(qi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function gT(i){return Wi(qi.UTF8_STRING,Buffer.from(i,"utf8"))}function LT(){return Buffer.from([qi.NULL,0])}function gy(i,t,n=!0){let r=160|i|(n?0:0),f=Jn(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(qi.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(qi.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(zn(r),f);t.push(HT(c))}return Xi(...t)}function bw(i){return Xi(zn(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=Jn(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=Jn(r.length);t.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=Jn(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])),d0(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(zn(Bi.SERVER_AUTH));if(i.clientAuth)t.push(zn(Bi.CLIENT_AUTH));return Xi(...t)}function Sn(i,t,n){let r=[zn(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,d0(2))),t.push(d0(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(Sn(Bi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,dT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)n.push(Sn(Bi.KEY_USAGE,i.extensions.keyUsage.critical??!0,DT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)n.push(Sn(Bi.EXTENDED_KEY_USAGE,!1,bT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)n.push(Sn(Bi.SUBJECT_ALT_NAME,!1,VT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)n.push(Sn(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=fn.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
|
`)}
|
|
@@ -69,24 +69,24 @@ ${r.join(`
|
|
|
69
69
|
`}function yc(){let i=fn.randomBytes(20);return i[0]=i[0]&127||1,i}function Pw(i=2048){let{privateKey:t,publicKey:n}=fn.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:n}}function oT(i){let t=i.export({type:"spki",format:"der"});return fn.createHash("sha1").update(t).digest()}function Zw(i){let t={serialNumber:i.serialNumber||yc(),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 fn.createPrivateKey(i)}function iE(i){let t=new fn.X509Certificate(i),n=t.publicKey,r=[],f=t.subject.split(`
|
|
70
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 wc(i={}){N("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Hi.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||o.countryName},{shortName:"ST",value:i.stateName||o.stateName},{shortName:"L",value:i.localityName||o.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}=lc({validityYears:i.validityYears||Hi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:y}=Zw({serialNumber:yc(),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 uc(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 ${Hi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let r=Hi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:c}=Pw(r),l=i.commonName||kw(i),y=i.certificateAttributes||[{shortName:"C",value:i.countryName||o.countryName},{shortName:"ST",value:i.stateName||o.stateName},{shortName:"L",value:i.localityName||o.localityName},{shortName:"O",value:i.organizationName||o.organizationName},{shortName:"CN",value:l}],{notBefore:w,notAfter:u}=lc({validityDays:i.validityDays||Hi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=Vw(i),$=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=Zw({serialNumber:yc(),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(R.STORAGE,`Storing certificate and private key with options: ${Pr(t)}`,t?.verbose);let{certPath:n,keyPath:r}=cc({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});N(R.STORAGE,`Certificate path: ${n}`,t?.verbose),N(R.STORAGE,`Private key path: ${r}`,t?.verbose);let f=D0.dirname(n);if(!ft.existsSync(f))N(R.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),ft.mkdirSync(f,{recursive:!0});N(R.STORAGE,"Writing certificate file",t?.verbose),ft.writeFileSync(n,i.certificate);let c=D0.dirname(r);if(!ft.existsSync(c))N(R.STORAGE,`Creating private key directory: ${c}`,t?.verbose),ft.mkdirSync(c,{recursive:!0});return N(R.STORAGE,"Writing private key file",t?.verbose),ft.writeFileSync(r,i.privateKey),N(R.STORAGE,"Certificate and private key stored successfully",t?.verbose),n}function pw(i,t){N(R.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:n}=cc({basePath:t?.basePath,caCertPath:t?.caCertPath});N(R.STORAGE,`CA certificate path: ${n}`,t?.verbose);let r=D0.dirname(n);if(!ft.existsSync(r))N(R.STORAGE,`Creating CA certificate directory: ${r}`,t?.verbose),ft.mkdirSync(r,{recursive:!0});return N(R.STORAGE,"Writing CA certificate file",t?.verbose),ft.writeFileSync(n,i),N(R.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 hc(i){return iu(Zr(i).subject)}function $c(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
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 Ac(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(R.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(R.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return N(R.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return N(R.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var wE={platform:"darwin",async addCertificate(i,t){if(await yE(i,t?.verbose)){N(R.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),tn.success("Certificate is already trusted in system keychain");return}N(R.TRUST,"Adding certificate to macOS keychain",t?.verbose),await Ct(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await Ct(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(R.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw N(R.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},uE={platform:"win32",async addCertificate(i,t){N(R.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await Ct(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await Ct(`certutil -delstore -enterprise Root "${r}"`),N(R.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw N(R.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},hE={platform:"linux",async addCertificate(i,t){N(R.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=xr.homedir(),r=Hi.LINUX_CERT_DB_FILENAME,f=Hi.LINUX_TRUST_ARGS;N(R.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let c=V0(n,r);if(c.length===0){tn.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){N(R.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{N(R.TRUST,`Attempting to delete existing cert for ${o.commonName}`,t?.verbose),await Ct(`certutil -d sql:${l} -D -n ${o.commonName}`)}catch(y){N(R.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}N(R.TRUST,`Adding new certificate to ${l}`,t?.verbose),await Ct(`certutil -d sql:${l} -A -t ${f} -n ${o.commonName} -i ${i}`),tn.info(`Cert added to ${l}`)}},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=xr.homedir(),c=Hi.LINUX_CERT_DB_FILENAME;N(R.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=V0(f,c);if(l.length===0){tn.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){N(R.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await Ct(`certutil -d sql:${y} -D -n "${r}"`),tn.info(`Cert removed from ${y}`)}catch(w){N(R.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 Tc(i,t,n){N(R.TRUST,`Adding certificate to system trust store with options: ${Pr(n)}`,n?.verbose),N(R.TRUST,"Storing certificate and private key",n?.verbose);let r=ow(i,n);N(R.TRUST,"Storing CA certificate",n?.verbose);let f=pw(t,n),c=xr.platform();N(R.TRUST,`Detected platform: ${c}`,n?.verbose);let l=$E[c];if(!l){let y=`Unsupported platform: ${c}`;throw N(R.TRUST,`Error: ${y}`,n?.verbose),Error(y)}return await l.addCertificate(f,n),N(R.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as tl}from"node:os";import{join as nl,resolve as $R}from"node:path";import{existsSync as tu,statSync as nu}from"fs";import{existsSync as AE,mkdirSync as Wj,readdirSync as Sj,readFileSync as TE,writeFileSync as aj}from"fs";import{homedir as cn}from"os";import{dirname as Ij,resolve as Ki}from"path";import _f from"process";import{existsSync as ru,statSync as fu}from"fs";import{existsSync as zc,mkdirSync as EE,readdirSync as YE,writeFileSync as BE}from"fs";import{homedir as ln}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 gj,readdirSync as Lj,writeFileSync as sj}from"fs";import{homedir as Ec}from"os";import{dirname as Vj,resolve as ei}from"path";import On from"process";import{join as mE,relative as UE,resolve as yu}from"path";import Uf from"process";import{existsSync as ku,mkdirSync as Zj,readdirSync as vj,writeFileSync as oj}from"fs";import{dirname as iN,resolve as jf}from"path";import Qc from"process";import{Buffer as jt}from"buffer";import{createCipheriv as jE,createDecipheriv as NE,randomBytes as Yc}from"crypto";import{closeSync as Bc,createReadStream as wu,createWriteStream as RE,existsSync as ec,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 yn,unlink as pr,writeFile as Cc}from"fs/promises";import{join as wn}from"path";import hi from"process";import{pipeline as aE}from"stream/promises";import{createGzip as Tu}from"zlib";import un from"process";import ut from"process";import{Buffer as lt}from"buffer";import{createCipheriv as JE,createDecipheriv as FE,randomBytes as mc}from"crypto";import{closeSync as Uc,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 hn,unlink as rf,writeFile as jc}from"fs/promises";import{isAbsolute as QE,join as $n,resolve as ME}from"path";import _ from"process";import{pipeline as OE}from"stream/promises";import{createGzip as mu}from"zlib";import An from"process";import ht from"process";import ff from"process";import{existsSync as cf}from"fs";import{resolve as Nc}from"path";import{existsSync as GE}from"fs";import{existsSync as HE,readdirSync as qE}from"fs";import{extname as Rc,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 yt}from"buffer";import{createCipheriv as xE,createDecipheriv as kE,randomBytes as Xc}from"crypto";import{closeSync as Wc,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 Tn,unlink as wf,writeFile as Sc}from"fs/promises";import{isAbsolute as PE,join as En,resolve as ZE}from"path";import z from"process";import{pipeline as vE}from"stream/promises";import{createGzip as au}from"zlib";import Yn from"process";import $t from"process";import hf from"process";import{existsSync as $f}from"fs";import{resolve as _c}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,Vc=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:()=>qn,globalCache:()=>Bn,getEnvOrDefault:()=>CY,generateConfigTypes:()=>SY,defaultGeneratedDir:()=>yh,defaultConfigDir:()=>lh,deepMergeWithArrayStrategy:()=>Zc,deepMerge:()=>Zu,createLibraryConfig:()=>aY,config:()=>XY,bunfigPlugin:()=>JY,applyEnvVarsToConfig:()=>Mn,TypeGenerationError:()=>Lc,SchemaValidationError:()=>Hn,PluginError:()=>xc,PerformanceMonitor:()=>Dc,FileSystemError:()=>gc,ErrorFactory:()=>Nt,EnvVarError:()=>Jf,EnvProcessor:()=>zf,ConfigValidator:()=>vc,ConfigValidationError:()=>Hc,ConfigNotFoundError:()=>af,ConfigMergeError:()=>qc,ConfigLoader:()=>oc,ConfigLoadError:()=>Gn,ConfigFileLoader:()=>Qf,ConfigCache:()=>dc,CacheUtils:()=>th,BunfigError:()=>Si,BrowserConfigError:()=>sc,ArrayMergeStrategies:()=>fh});class dc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let 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 bc(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]=bc(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 bc(t,r)}catch{return null}}catch{return null}}async function yY({name:i="",cwd:t,defaultConfig:n}){let r=t||Qc.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 bc(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(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hY(){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 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:un.pid,hostname:t(),environment:un.env.NODE_ENV||"development",platform:un.platform,version:un.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:un.env.NODE_ENV||un.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={...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??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:Oc.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:jt.from(i);try{if(!ec(this.currentLogFile))await Cc(this.currentLogFile,"",{mode:420});if(f=hu(this.currentLogFile,"a",420),XE(f,w,{flag:"a"}),uu(f),f!==void 0)Bc(f),f=void 0;if((await yn(this.currentLogFile)).size===0){if(await Cc(this.currentLogFile,w,{flag:"w",mode:420}),(await yn(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{Bc(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 wn(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 wn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return wn(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 Yc(16).toString("hex")}generateKey(){return Yc(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=Yc(16),r=jE("aes-256-gcm",t,n),f=jt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:jt.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(jt.from(jt.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 yn(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 yn(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 Cc(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 yn(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(wn(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()})),ec(this.currentLogFile))try{let i=hu(this.currentLogFile,"r+");uu(i),Bc(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(wn(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(`
|
|
72
|
+
`).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return N(R.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return N(R.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return N(R.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var wE={platform:"darwin",async addCertificate(i,t){if(await yE(i,t?.verbose)){N(R.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),tn.success("Certificate is already trusted in system keychain");return}N(R.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||o.commonName;N(R.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await et(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(R.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw N(R.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},uE={platform:"win32",async addCertificate(i,t){N(R.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||o.commonName;N(R.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await et(`certutil -delstore -enterprise Root "${r}"`),N(R.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw N(R.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},hE={platform:"linux",async addCertificate(i,t){N(R.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=xr.homedir(),r=Hi.LINUX_CERT_DB_FILENAME,f=Hi.LINUX_TRUST_ARGS;N(R.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let c=V0(n,r);if(c.length===0){tn.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){N(R.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{N(R.TRUST,`Attempting to delete existing cert for ${o.commonName}`,t?.verbose),await et(`certutil -d sql:${l} -D -n ${o.commonName}`)}catch(y){N(R.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}N(R.TRUST,`Adding new certificate to ${l}`,t?.verbose),await et(`certutil -d sql:${l} -A -t ${f} -n ${o.commonName} -i ${i}`),tn.info(`Cert added to ${l}`)}},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=xr.homedir(),c=Hi.LINUX_CERT_DB_FILENAME;N(R.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=V0(f,c);if(l.length===0){tn.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){N(R.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await et(`certutil -d sql:${y} -D -n "${r}"`),tn.info(`Cert removed from ${y}`)}catch(w){N(R.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 Tc(i,t,n){N(R.TRUST,`Adding certificate to system trust store with options: ${Pr(n)}`,n?.verbose),N(R.TRUST,"Storing certificate and private key",n?.verbose);let r=ow(i,n);N(R.TRUST,"Storing CA certificate",n?.verbose);let f=pw(t,n),c=xr.platform();N(R.TRUST,`Detected platform: ${c}`,n?.verbose);let l=$E[c];if(!l){let y=`Unsupported platform: ${c}`;throw N(R.TRUST,`Error: ${y}`,n?.verbose),Error(y)}return await l.addCertificate(f,n),N(R.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as tl}from"node:os";import{join as nl,resolve as $R}from"node:path";import{existsSync as tu,statSync as nu}from"fs";import{existsSync as AE,mkdirSync as Wj,readdirSync as Sj,readFileSync as TE,writeFileSync as aj}from"fs";import{homedir as cn}from"os";import{dirname as Ij,resolve as Ki}from"path";import _f from"process";import{existsSync as ru,statSync as fu}from"fs";import{existsSync as zc,mkdirSync as EE,readdirSync as YE,writeFileSync as BE}from"fs";import{homedir as ln}from"os";import{dirname as cu,resolve as ei}from"path";import zt from"process";import{join as CE,relative as eE,resolve as lu}from"path";import mf from"process";import{existsSync as xu,mkdirSync as gj,readdirSync as Lj,writeFileSync as sj}from"fs";import{homedir as Ec}from"os";import{dirname as Vj,resolve as Ci}from"path";import On from"process";import{join as mE,relative as UE,resolve as yu}from"path";import Uf from"process";import{existsSync as ku,mkdirSync as Zj,readdirSync as vj,writeFileSync as oj}from"fs";import{dirname as iN,resolve as jf}from"path";import Qc from"process";import{Buffer as jt}from"buffer";import{createCipheriv as jE,createDecipheriv as NE,randomBytes as Yc}from"crypto";import{closeSync as Bc,createReadStream as wu,createWriteStream as RE,existsSync as Cc,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 yn,unlink as pr,writeFile as ec}from"fs/promises";import{join as wn}from"path";import hi from"process";import{pipeline as aE}from"stream/promises";import{createGzip as Tu}from"zlib";import un from"process";import ut from"process";import{Buffer as lt}from"buffer";import{createCipheriv as JE,createDecipheriv as FE,randomBytes as mc}from"crypto";import{closeSync as Uc,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 Cu,mkdir as zE,readdir as nf,rename as eu,stat as hn,unlink as rf,writeFile as jc}from"fs/promises";import{isAbsolute as QE,join as $n,resolve as ME}from"path";import _ from"process";import{pipeline as OE}from"stream/promises";import{createGzip as mu}from"zlib";import An from"process";import ht from"process";import ff from"process";import{existsSync as cf}from"fs";import{resolve as Nc}from"path";import{existsSync as GE}from"fs";import{existsSync as HE,readdirSync as qE}from"fs";import{extname as Rc,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 yt}from"buffer";import{createCipheriv as xE,createDecipheriv as kE,randomBytes as Xc}from"crypto";import{closeSync as Wc,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 Tn,unlink as wf,writeFile as Sc}from"fs/promises";import{isAbsolute as PE,join as En,resolve as ZE}from"path";import z from"process";import{pipeline as vE}from"stream/promises";import{createGzip as au}from"zlib";import Yn from"process";import $t from"process";import hf from"process";import{existsSync as $f}from"fs";import{resolve as _c}from"path";import{existsSync as CB}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 ef=new Lu,Vc=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:()=>CY,isConfigNotFoundError:()=>BY,isBunfigError:()=>Pu,globalPerformanceMonitor:()=>qn,globalCache:()=>Bn,getEnvOrDefault:()=>eY,generateConfigTypes:()=>SY,defaultGeneratedDir:()=>yh,defaultConfigDir:()=>lh,deepMergeWithArrayStrategy:()=>Zc,deepMerge:()=>Zu,createLibraryConfig:()=>aY,config:()=>XY,bunfigPlugin:()=>JY,applyEnvVarsToConfig:()=>Mn,TypeGenerationError:()=>Lc,SchemaValidationError:()=>Hn,PluginError:()=>xc,PerformanceMonitor:()=>Dc,FileSystemError:()=>gc,ErrorFactory:()=>Nt,EnvVarError:()=>Jf,EnvProcessor:()=>zf,ConfigValidator:()=>vc,ConfigValidationError:()=>Hc,ConfigNotFoundError:()=>af,ConfigMergeError:()=>qc,ConfigLoader:()=>oc,ConfigLoadError:()=>Gn,ConfigFileLoader:()=>Qf,ConfigCache:()=>dc,CacheUtils:()=>th,BunfigError:()=>Si,BrowserConfigError:()=>sc,ArrayMergeStrategies:()=>fh});class dc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let 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 bc(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]=bc(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 bc(t,r)}catch{return null}}catch{return null}}async function yY({name:i="",cwd:t,defaultConfig:n}){let r=t||Qc.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 bc(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(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hY(){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 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:un.pid,hostname:t(),environment:un.env.NODE_ENV||"development",platform:un.platform,version:un.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:un.env.NODE_ENV||un.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={...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??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:Oc.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:jt.from(i);try{if(!Cc(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)Bc(f),f=void 0;if((await yn(this.currentLogFile)).size===0){if(await ec(this.currentLogFile,w,{flag:"w",mode:420}),(await yn(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{Bc(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 wn(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 wn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return wn(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 Yc(16).toString("hex")}generateKey(){return Yc(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=Yc(16),r=jE("aes-256-gcm",t,n),f=jt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:jt.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(jt.from(jt.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 yn(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 yn(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 yn(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(wn(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()})),Cc(this.currentLogFile))try{let i=hu(this.currentLogFile,"r+");uu(i),Bc(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(wn(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 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(!
|
|
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(!Cc(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=jt.isBuffer(i)?i:jt.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),jt.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
|
-
`.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,
|
|
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=wn(this.config.logDirectory,r);if(i.before)try{if((await yn(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 Pc(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]=Pc(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 Pc(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=On.env[T]||On.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||On.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 j=[ei(u,"config"),ei(u,".config")].concat(r?[ei(u,r)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let X of j)for(let W of h){let F=ei(B,`${X}${W}`),a=await uf(F,w,y);if(a!==null){if(c)Ai.success(`Configuration loaded from: ${F}`);return a}}}if(i){let B=ei(Ec(),".config",i),C=["config",`${i}.config`];if(t)C.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${B}`);for(let j of C)for(let X of h){let W=ei(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${W}`);return F}}}if(i){let B=ei(Ec(),".config"),C=[`.${i}.config`];if(t)C.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of C)for(let X of h){let W=ei(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${W}`);return F}}}if(i){let B=Ec(),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 j of C)for(let X of h){let W=ei(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${W}`);return F}}}try{let B=ei(u,"package.json");if(xu(B)){let C=await import(B),j=C[i];if(!j&&t){if(j=C[t],j&&c)Ai.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)Ai.success(`Configuration loaded from package.json: ${j===C[i]?i:t}`);return Pc(w,j,y)}catch(X){if(c)Ai.warn("Failed to merge package.json config:",X)}}}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(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YY(){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 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:An.pid,hostname:t(),environment:An.env.NODE_ENV||"development",platform:An.platform,version:An.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:An.env.NODE_ENV||An.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={...Gc},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??_.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:Gc.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:lt.from(i);try{if(!tf(this.currentLogFile))await jc(this.currentLogFile,"",{mode:420});if(f=Bu(this.currentLogFile,"a",420),KE(f,w,{flag:"a"}),Yu(f),f!==void 0)Uc(f),f=void 0;if((await hn(this.currentLogFile)).size===0){if(await jc(this.currentLogFile,w,{flag:"w",mode:420}),(await hn(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{Uc(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 $n(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 $n(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return $n(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 mc(16).toString("hex")}generateKey(){return mc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=mc(16),r=JE("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=mu(),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(ni())return;if(!this.shouldWriteToFile())return;let i=await hn(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 hn(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 jc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await hn(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($n(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),Uc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await nf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await rf($n(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()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())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} ${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(ni())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(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?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(`
|
|
81
|
-
`);for(let E of
|
|
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,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,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 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=wn(this.config.logDirectory,r);if(i.before)try{if((await yn(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 Pc(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]=Pc(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 Pc(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("_")}`,C=`${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=On.env[T]||On.env[C];if(E!==void 0){if(n)Ai.info(`Using environment variable ${E?T:C} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(E);else if(typeof h==="boolean")w[u]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let B=JSON.parse(E);if(Array.isArray(B))w[u]=B;else w[u]=E.split(",").map((e)=>e.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||On.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}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Ci(u,"config"),Ci(u,".config"),r?Ci(u,r):void 0].filter(Boolean)));for(let B of E){if(c)Ai.info(`Searching for configuration in: ${B}`);let j=[Ci(u,"config"),Ci(u,".config")].concat(r?[Ci(u,r)]:[]).includes(B)?[...$,...A,...T,...C]:[...A,...$,...C,...T];for(let X of j)for(let W of h){let F=Ci(B,`${X}${W}`),a=await uf(F,w,y);if(a!==null){if(c)Ai.success(`Configuration loaded from: ${F}`);return a}}}if(i){let B=Ci(Ec(),".config",i),e=["config",`${i}.config`];if(t)e.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${B}`);for(let j of e)for(let X of h){let W=Ci(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${W}`);return F}}}if(i){let B=Ci(Ec(),".config"),e=[`.${i}.config`];if(t)e.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ci(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${W}`);return F}}}if(i){let B=Ec(),e=[`.${i}.config`,`.${i}`];if(t)e.push(`.${t}.config`),e.push(`.${t}`);if(c)Ai.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ci(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${W}`);return F}}}try{let B=Ci(u,"package.json");if(xu(B)){let e=await import(B),j=e[i];if(!j&&t){if(j=e[t],j&&c)Ai.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)Ai.success(`Configuration loaded from package.json: ${j===e[i]?i:t}`);return Pc(w,j,y)}catch(X){if(c)Ai.warn("Failed to merge package.json config:",X)}}}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 eE(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(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YY(){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 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:An.pid,hostname:t(),environment:An.env.NODE_ENV||"development",platform:An.platform,version:An.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:An.env.NODE_ENV||An.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={...Gc},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??_.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{...Cf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Cf};return{...Cf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Gc.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,Cu.F_OK|Cu.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:lt.from(i);try{if(!tf(this.currentLogFile))await jc(this.currentLogFile,"",{mode:420});if(f=Bu(this.currentLogFile,"a",420),KE(f,w,{flag:"a"}),Yu(f),f!==void 0)Uc(f),f=void 0;if((await hn(this.currentLogFile)).size===0){if(await jc(this.currentLogFile,w,{flag:"w",mode:420}),(await hn(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{Uc(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 $n(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 $n(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return $n(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 mc(16).toString("hex")}generateKey(){return mc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=mc(16),r=JE("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=mu(),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(ni())return;if(!this.shouldWriteToFile())return;let i=await hn(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 hn(n).catch(()=>null))try{if(await eu(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 jc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await hn(n).catch(()=>null))await eu(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($n(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),Uc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await nf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await rf($n(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()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())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} ${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(ni())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(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?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 C=y.split(`
|
|
81
|
+
`);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:M.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()&&_.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()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ni()&&_.stdout.isTTY)_.stdout.write(`
|
|
84
84
|
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&_.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),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
|
|
85
85
|
`,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=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: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=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=FE("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 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: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(!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(`${M.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?M.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${u}${w} ${M.cyan(r)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
88
|
-
`.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=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=_.stdout.columns||80,
|
|
89
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!_.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=$n(this.config.logDirectory,r);if(i.before)try{if((await hn(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
|
|
88
|
+
`.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=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=_.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
|
|
89
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!_.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=$n(this.config.logDirectory,r);if(i.before)try{if((await hn(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 CY(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 qn.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 Nt.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 Nt.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,7 +98,7 @@ ${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 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)=>Mc(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 Zc(i,t,n="replace"){return Zu(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Mc(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(!Mc(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(!Mc(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=Bn.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 Gn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Gn(i,Error("Configuration must export a valid object"),"unknown");let B={config:Zc(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Bn.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Nt.configLoad(i,u):Nt.configLoad(i,Error(String(u)))}};if(l)return qn.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(Nc(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=Nc(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=Nc(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 vc{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 qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!GE(t))throw new Hn(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 Hn(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 oc{fileLoader=new Qf;envProcessor=new zf;validator=new vc;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)Li.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Li.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 Nt.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?Mn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Li.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)Li.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?Mn(i,n,f):n,y=[Ci(ln(),".config",i),Ci(ln(),".config"),ln()];for(let w of y){if(f)Li.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)Li.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?Mn(i,r,c):r;try{let w=Ci(n,"package.json");if(!zc(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)Li.success(`Configuration loaded from package.json: ${$}`);return{config:Zc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Li.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:Mn(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 Nt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Bn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Bn.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(ln(),".config",i),Ci(ln(),".config"),ln()],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 At.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 At.loadConfig(i);else r=await At.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)Li.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 At.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 At.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 At.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await At.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 At.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 Mn(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(!zc(cu(r)))EE(cu(r),{recursive:!0,mode:511});let f=zc(t)?YE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${tB}
|
|
101
|
+
`;return n}}function eY(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)=>Mc(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 Zc(i,t,n="replace"){return Zu(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Mc(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(!Mc(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(!Mc(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=Bn.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 Gn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Gn(i,Error("Configuration must export a valid object"),"unknown");let B={config:Zc(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Bn.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Nt.configLoad(i,u):Nt.configLoad(i,Error(String(u)))}};if(l)return qn.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(Nc(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=Nc(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=Nc(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 vc{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 qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!GE(t))throw new Hn(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 Hn(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 oc{fileLoader=new Qf;envProcessor=new zf;validator=new vc;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)Li.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Li.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 C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(ei($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Nt.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?Mn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Li.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)Li.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?Mn(i,n,f):n,y=[ei(ln(),".config",i),ei(ln(),".config"),ln()];for(let w of y){if(f)Li.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)Li.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?Mn(i,r,c):r;try{let w=ei(n,"package.json");if(!zc(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)Li.success(`Configuration loaded from package.json: ${$}`);return{config:Zc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Li.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:Mn(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 Nt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Bn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Bn.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,ei(i,"config"),ei(i,".config"),t?ei(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(ei(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=[ei(ln(),".config",i),ei(ln(),".config"),ln()],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 At.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 At.loadConfig(i);else r=await At.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)Li.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 At.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 At.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 At.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await At.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 At.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 Mn(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,C;for(let E of A)if(T=zt.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function SY(i){let t=ei(zt.cwd(),i.configDir),n=ei(zt.cwd(),i.generatedDir),r=ei(n,"config-types.ts");if(!zc(cu(r)))EE(cu(r),{recursive:!0,mode:511});let f=zc(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
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)Li.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(Rc(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=Rc(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=Rc($).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
104
|
${f.map((u)=>{let h=Uu(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
|
|
@@ -107,16 +107,16 @@ ${f.map((u)=>{let h=Uu(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof
|
|
|
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 ih,Bn,qn,th,FY,IY,Fu,Ef,Oc,$i,k,KY,Iu,_Y,Ku,zY,QY,ac,MY,_u,zu,Jc,OY,GY,HY,qY,Yf,nh,gY,Ai,LY,sY,Qu,Bf,Gc,ri,M,xY,Mu,kY,Ou,VY,dY,Fc,DY,Gu,Hu,bY,Ic,PY,ZY,vY,oY,pY,ef,rh,iB,tB="0.15.6",Si,af,Gn,Hc,qc,Jf,gc,Lc,Hn,sc,xc,Nt,fh,ch,Li,At,lh,yh,nB=nY(async()=>{ih=import.meta.require,Bn=new dc,qn=new Dc,th={createKey:rY,isEquivalent:fY,estimateMemoryUsage:cY},FY=jf(Qc.cwd(),"config"),IY=jf(Qc.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},Oc=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,ac=$i.white,MY=$i.gray,_u=$i.bgRed,zu=$i.bgYellow,Jc=$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(ac(Jc(" WARN "))),error:_u(ac(Jc(" ERROR ")))},gY=new Xf("stacks"),Ai=new Xf("bunfig",{showTags:!0}),LY=ei(On.cwd(),"config"),sY=ei(On.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},Gc=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"},M=ri,xY=ri.red,Mu=ri.green,kY=ri.yellow,Ou=ri.blue,VY=ri.magenta,dY=ri.cyan,Fc=ri.white,DY=ri.gray,Gu=ri.bgRed,Hu=ri.bgYellow,bY=ri.bgGray,Ic=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(Fc(Ic(" WARN "))),error:Gu(Fc(Ic(" 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})}},Gn=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}},Hc=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})}},qc=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})}},gc=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}},Lc=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}},Hn=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})}},sc=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})}},xc=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}},Nt={configNotFound(i,t,n){return new af(i,t,n)},configLoad(i,t,n){return new Gn(i,t,n)},configValidation(i,t,n){return new Hc(i,t,n)},configMerge(i,t,n,r){return new qc(i,t,n,r)},envVar(i,t,n,r){return new Jf(i,t,n,r)},fileSystem(i,t,n){return new gc(i,t,n)},typeGeneration(i,t,n){return new Lc(i,t,n)},schemaValidation(i,t,n){return new Hn(i,t,n)},browserConfig(i,t,n,r){return new sc(i,t,n,r)},plugin(i,t,n){return new xc(i,t,n)}},fh={replace:"replace",concat:"concat",smart:"smart"},ch=/^https?:\/\//,Li=new Sf("bunfig",{showTags:!0}),At=new oc,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},LN=(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($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cB(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class 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:Yn.pid,hostname:t(),environment:Yn.env.NODE_ENV||"development",platform:Yn.platform,version:Yn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yn.env.NODE_ENV||Yn.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"},G=li,sN=li.red,lB=li.green,xN=li.yellow,yB=li.blue,kN=li.magenta,VN=li.cyan,qu=li.white,dN=li.gray,wB=li.bgRed,uB=li.bgYellow,DN=li.bgGray,gu=li.bold,bN=li.dim,PN=li.italic,ZN=li.underline,vN=li.strikethrough,oN=li.reset,Kc={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??z.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{...Kc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Kc};return{...Kc,...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:yt.from(i);try{if(!lf(this.currentLogFile))await Sc(this.currentLogFile,"",{mode:420});if(f=Xu(this.currentLogFile,"a",420),dE(f,w,{flag:"a"}),Ru(f),f!==void 0)Wc(f),f=void 0;if((await Tn(this.currentLogFile)).size===0){if(await Sc(this.currentLogFile,w,{flag:"w",mode:420}),(await Tn(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{Wc(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 En(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 En(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return En(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 Xc(16).toString("hex")}generateKey(){return Xc(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=Xc(16),r=xE("aes-256-gcm",t,n),f=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=yt.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(yt.from(yt.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 Tn(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 Tn(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 Sc(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 Tn(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(En(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),Wc(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(En(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()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof z.env.NO_COLOR<"u",t=z.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof z.stderr<"u"&&z.stderr.isTTY||typeof z.stdout<"u"&&z.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=z.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} ${G.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=G.underline(G.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)=>G.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>G.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>G.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>G.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>G.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=z.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=z.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?G.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:G.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:G.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
|
-
`);for(let E of
|
|
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,Bn,qn,th,FY,IY,Fu,Ef,Oc,$i,k,KY,Iu,_Y,Ku,zY,QY,ac,MY,_u,zu,Jc,OY,GY,HY,qY,Yf,nh,gY,Ai,LY,sY,Qu,Bf,Gc,ri,M,xY,Mu,kY,Ou,VY,dY,Fc,DY,Gu,Hu,bY,Ic,PY,ZY,vY,oY,pY,Cf,rh,iB,tB="0.15.6",Si,af,Gn,Hc,qc,Jf,gc,Lc,Hn,sc,xc,Nt,fh,ch,Li,At,lh,yh,nB=nY(async()=>{ih=import.meta.require,Bn=new dc,qn=new Dc,th={createKey:rY,isEquivalent:fY,estimateMemoryUsage:cY},FY=jf(Qc.cwd(),"config"),IY=jf(Qc.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},Oc=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,ac=$i.white,MY=$i.gray,_u=$i.bgRed,zu=$i.bgYellow,Jc=$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(ac(Jc(" WARN "))),error:_u(ac(Jc(" ERROR ")))},gY=new Xf("stacks"),Ai=new Xf("bunfig",{showTags:!0}),LY=Ci(On.cwd(),"config"),sY=Ci(On.cwd(),"src/generated"),Qu=mf.env.CLARITY_LOG_DIR||CE(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},Gc=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"},M=ri,xY=ri.red,Mu=ri.green,kY=ri.yellow,Ou=ri.blue,VY=ri.magenta,dY=ri.cyan,Fc=ri.white,DY=ri.gray,Gu=ri.bgRed,Hu=ri.bgYellow,bY=ri.bgGray,Ic=ri.bold,PY=ri.dim,ZY=ri.italic,vY=ri.underline,oY=ri.strikethrough,pY=ri.reset,Cf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rh={debug:"\uD83D\uDD0D",info:Ou("ℹ"),success:Mu("✓"),warning:Hu(Fc(Ic(" WARN "))),error:Gu(Fc(Ic(" 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})}},Gn=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}},Hc=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})}},qc=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})}},gc=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}},Lc=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}},Hn=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})}},sc=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})}},xc=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}},Nt={configNotFound(i,t,n){return new af(i,t,n)},configLoad(i,t,n){return new Gn(i,t,n)},configValidation(i,t,n){return new Hc(i,t,n)},configMerge(i,t,n,r){return new qc(i,t,n,r)},envVar(i,t,n,r){return new Jf(i,t,n,r)},fileSystem(i,t,n){return new gc(i,t,n)},typeGeneration(i,t,n){return new Lc(i,t,n)},schemaValidation(i,t,n){return new Hn(i,t,n)},browserConfig(i,t,n,r){return new sc(i,t,n,r)},plugin(i,t,n){return new xc(i,t,n)}},fh={replace:"replace",concat:"concat",smart:"smart"},ch=/^https?:\/\//,Li=new Sf("bunfig",{showTags:!0}),At=new oc,lh=ei(zt.cwd(),"config"),yh=ei(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},LN=(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($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cB(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class 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:Yn.pid,hostname:t(),environment:Yn.env.NODE_ENV||"development",platform:Yn.platform,version:Yn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yn.env.NODE_ENV||Yn.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"},G=li,sN=li.red,lB=li.green,xN=li.yellow,yB=li.blue,kN=li.magenta,VN=li.cyan,qu=li.white,dN=li.gray,wB=li.bgRed,uB=li.bgYellow,DN=li.bgGray,gu=li.bold,bN=li.dim,PN=li.italic,ZN=li.underline,vN=li.strikethrough,oN=li.reset,Kc={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??z.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{...Kc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Kc};return{...Kc,...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:yt.from(i);try{if(!lf(this.currentLogFile))await Sc(this.currentLogFile,"",{mode:420});if(f=Xu(this.currentLogFile,"a",420),dE(f,w,{flag:"a"}),Ru(f),f!==void 0)Wc(f),f=void 0;if((await Tn(this.currentLogFile)).size===0){if(await Sc(this.currentLogFile,w,{flag:"w",mode:420}),(await Tn(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{Wc(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 En(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 En(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return En(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 Xc(16).toString("hex")}generateKey(){return Xc(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=Xc(16),r=xE("aes-256-gcm",t,n),f=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=yt.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(yt.from(yt.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 Tn(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 Tn(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 Sc(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 Tn(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(En(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),Wc(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(En(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()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof z.env.NO_COLOR<"u",t=z.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof z.stderr<"u"&&z.stderr.isTTY||typeof z.stdout<"u"&&z.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=z.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} ${G.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=G.underline(G.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)=>G.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>G.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>G.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>G.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>G.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=z.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=z.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?G.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:G.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:G.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 C=y.split(`
|
|
111
|
+
`);for(let E of C)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:G.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()&&z.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()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!fi()&&z.stdout.isTTY)z.stdout.write(`
|
|
114
114
|
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:n,message:`${G.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
115
|
`,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":G.green("✓"),tag:h,message:`${c}${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=yt.isBuffer(i)?i:yt.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,$=yt.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:G.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:G.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(`${G.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();z.stdin.removeListener("data",n);try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!1)}catch{}z.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!0)}catch{}z.stdin.resume(),z.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?G.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${u}${w} ${G.cyan(r)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
118
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!z.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=G.green("━".repeat(r)),l=G.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?G.green("✓"):G.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=z.stdout.columns||80,
|
|
119
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!z.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=En(this.config.logDirectory,r);if(i.before)try{if((await Tn(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 pN=new Mf("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 hh 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 If 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 $h 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 Ah 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 pc 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 Th 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 Eh 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 Kf 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 Yh 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 Bh 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
|
|
118
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!z.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=G.green("━".repeat(r)),l=G.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?G.green("✓"):G.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=z.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,z.stdout.write(i.lastRenderedLine),t)z.stdout.write(`
|
|
119
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!z.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=En(this.config.logDirectory,r);if(i.before)try{if((await Tn(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 pN=new Mf("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 hh 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 If 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 $h 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 Ah 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 pc 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 Th 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 Eh 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 Kf 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 Yh 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 Bh 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 Cn={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 pc(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 il{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 Vc.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 pc)throw $;throw Cn.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 Cn.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 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)=>kc(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 kc(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(!kc(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(!kc(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?en.configLoad(i,u):en.configLoad(i,Error(String(u)))}};if(l)return Vc.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(_c(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=_c(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=_c(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 Vc.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 wt=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 il;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)wt.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 wt.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 en.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)wt.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)wt.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(cn(),".config",i),Ki(cn(),".config"),cn()];for(let w of y){if(f)wt.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)wt.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)wt.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)wt.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)wt.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 en.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(cn(),".config",i),Ki(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)}}var fR=new Nh;function Af(i,t,n=!1){let r=new il,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 cR=Ki(_f.cwd(),"config"),lR=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:nl(tl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:nl(tl(),".stacks","ssl","stacks.localhost.crt"),keyPath:nl(tl(),".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 gn}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 rl(i){try{return hc(i)||null}catch{return null}}function fl(i,t){try{return t.every((n)=>Ac(i,n))}catch{return!1}}function NB(i,t,n=443){return $c(i,t,n)}function RB(i){let t=[];for(let n of i.split(`
|
|
131
|
+
`;return n}}function AB(i,t,n={}){return Ch(i,t,n,new WeakMap)}function Ch(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 BB(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 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)=>kc(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]=Ch(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 mh(i,t,n="replace"){return AB(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function kc(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(!kc(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(!kc(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=ef.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)ef.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Cn.configLoad(i,u):Cn.configLoad(i,Error(String(u)))}};if(l)return Vc.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(_c(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=_c(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=_c(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 eB=/^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 Vc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!CB(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:eB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var wt=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 il;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)wt.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 wt.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 C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,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 Cn.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)wt.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)wt.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(cn(),".config",i),Ki(cn(),".config"),cn()];for(let w of y){if(f)wt.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)wt.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)wt.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)wt.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)wt.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 Cn.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(cn(),".config",i),Ki(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)}}var fR=new Nh;function Af(i,t,n=!1){let r=new il,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,C;for(let E of A)if(T=_f.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var cR=Ki(_f.cwd(),"config"),lR=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:nl(tl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:nl(tl(),".stacks","ssl","stacks.localhost.crt"),keyPath:nl(tl(),".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 gn}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 rl(i){try{return hc(i)||null}catch{return null}}function fl(i,t){try{return t.every((n)=>Ac(i,n))}catch{return!1}}function NB(i,t,n=443){return $c(i,t,n)}function RB(i){let t=[];for(let n of i.split(`
|
|
132
132
|
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var bi="-d -r trustRoot -p ssl -p basic",Tt="/Library/Keychains/System.keychain",cl="rpx.localhost";function Ln(){return WB(XB(),"Library/Keychains/login.keychain-db")}function ll(){return[Tt,Ln()]}function Xh(i,t=cl){let n=gn(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
133
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??cl,r=i.keychains??ll();for(let f of r)for(let c of Xh(f,n)){if(c===t)continue;try{if(f.startsWith("/Library"))Rt(`security delete-certificate -Z ${c} "${f}"`);else gn(`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 xn(i,n);try{let f=gn(`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 xn(i,t){let n=Qt(i);if(!n)return!1;for(let r of ll())try{let f=gn(`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 yl(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Of({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=Ln();try{gn(`security add-trusted-cert ${bi} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{Rt(`security add-trusted-cert ${bi} -k ${Tt} "${i}"`)}catch{return!1}return sn(i,n,{verbose:t.verbose})||xn(i,{verbose:t.verbose})}var Xt=null,$l=D(
|
|
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 yl(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Of({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=Ln();try{gn(`security add-trusted-cert ${bi} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{Rt(`security add-trusted-cert ${bi} -k ${Tt} "${i}"`)}catch{return!1}return sn(i,n,{verbose:t.verbose})||xn(i,{verbose:t.verbose})}var Xt=null,$l=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:$l,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 Al(i){return{caCertPath:D(i,SB),caKeyPath:D(i,aB)}}function zR(i){return{certPath:D(i,"rpx.localhost.crt"),keyPath:D(i,"rpx.localhost.key"),caCertPath:D(i,"rpx.localhost.ca.crt"),rootCA:Al(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=hl(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 QR(i){Y("ssl","Loading SSL configuration",i.verbose);let t={...Rh,...i};if(i.https=Yl(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 MR(i,t){if(xi.platform==="darwin")return FB(i,t);if(xi.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(xi.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),yl(i,{serverName:n,verbose:r})}catch{return!1}}async function Qh(i){if(Xt&&!i.forceRegenerate){Y("ssl","Using cached SSL configuration",i.verbose);return}Tl();let t=Gf(i)?i.proxies.map((h)=>h.to):[i.to];Y("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let n=Yl(i,i.verbose),r=n.basePath||D(en(),".stacks","ssl");await Z.mkdir(r,{recursive:!0});let f=Al(r),c=await JB(f,i.verbose),l=!1;if(!c){if(i.verbose)S.info("Generating Root CA certificate (one-time)...");c=await wc(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)S.info(`Generating host certificate for: ${t.join(", ")}`);let y=await uc({...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)S.success("Root CA is already trusted in system trust store");if(Xt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)S.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)S.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(xi.platform==="darwin")try{Of({caPath:f.caCertPath,verbose:i.verbose});let h=Ln();try{wl(`security add-trusted-cert ${bi} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Rt(`security add-trusted-cert ${bi} -k ${Tt} "${f.caCertPath}"`),i.verbose)S.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.
|
|
@@ -162,29 +162,29 @@ 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(ul.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((
|
|
165
|
+
`,T=D(ul.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((C)=>{h(`sudo bash "${T}"`,(E)=>{if(E){if(i.verbose)S.warn(`Could not trust certificates: ${E}`);C(!1)}else{if(i.verbose)S.success("Successfully added certificates to system trust store");C(!0)}})}),await Z.unlink(T).catch(()=>{}),u=!0}catch(h){if(i.verbose)S.warn(`Failed to trust certificates: ${h}`)}else if(xi.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(ul.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),wl(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)S.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)S.warn(`Could not trust certificate: ${h}`)}else try{await Tc(y,c.certificate,n),u=!0}catch(h){if(i.verbose)S.warn(`Could not add certificate to trust store: ${h}`)}if(Xt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)S.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}function Tl(){Xt=null}async function El(i){if(!i)return null;if(Xt)return Xt;let t=Yl(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(
|
|
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(Vn(c,w.username)&&Vn(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,dn=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
|
|
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,
|
|
175
|
-
`,E);if(B===-1)B=r.length;let
|
|
172
|
+
`,$=D(ul.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),wl(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)S.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)S.warn(`Could not trust certificate: ${h}`)}else try{await Tc(y,c.certificate,n),u=!0}catch(h){if(i.verbose)S.warn(`Could not add certificate to trust store: ${h}`)}if(Xt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)S.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}function Tl(){Xt=null}async function El(i){if(!i)return null;if(Xt)return Xt;let t=Yl(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=Al(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:C}=await import("node:crypto"),B=new C(A).subjectAltName||"",j=i.proxies.map((X)=>X.to).filter((X)=>!B.includes(`DNS:${X}`));if(j.length>0)return Y("ssl",`Certificate missing SANs for: ${j.join(", ")}, will regenerate`,i.verbose),null}catch(C){Y("ssl",`Could not verify cert SANs: ${C}`,i.verbose)}return Y("ssl","Successfully loaded existing certificates",i.verbose),Xt={key:$,cert:A,ca:T},Xt}catch(n){return Y("ssl",`Error checking existing certificates: ${n}`,i.verbose),null}}function Yl(i,t){let n=hl(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 OR(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),xi.platform==="darwin"){if(t?.serverName)return sn(i,t.serverName,{verbose:t?.verbose});return xn(i,{verbose:t?.verbose})}else if(xi.platform==="win32")try{let n=rl(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(wl(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(xi.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 ${xi.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 kn(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{kn(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 Bl(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 Vn(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 C="",E=A;for(let B=0;B<T;B++)C+=w[E&63],E>>=6;return C},h=y,$="";return $+=u(h[0]<<16|h[6]<<8|h[12],4),$+=u(h[1]<<16|h[7]<<8|h[13],4),$+=u(h[2]<<16|h[8]<<8|h[14],4),$+=u(h[3]<<16|h[9]<<8|h[15],4),$+=u(h[4]<<16|h[10]<<8|h[5],4),$+=u(h[11],2),`$apr1$${t}$${$}`}function 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 Vn(gB(i,r),t)}if(t.startsWith("{SHA}")){let n=sh("sha1").update(i,"utf8").digest("base64");return Vn(`{SHA}${n}`,t)}return Vn(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(Vn(c,w.username)&&Vn(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,dn=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 Cl=30000,vB=16384,Dh=262144,oB=2097152,pB=524288,iC=8192,tC=4096,nC=new TextEncoder,bh=new TextDecoder,rC=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(Cl,this.checkoutIdleMs):Cl;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-Cl;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 fC(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 cC(i,t,n){let r=bh.decode(i.subarray(t,n)),f=r.indexOf(`\r
|
|
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,C=!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 e=r.slice(E,B);if(E=B+2,e==="")continue;let j=e.indexOf(":");if(j===-1)continue;let X=e.slice(0,j),W=e.slice(j+1).trim(),F=X.charCodeAt(0)|32;if(F===99||F===116||F===107){let a=X.toLowerCase();if(a==="content-length"){let J=/^\d+$/.test(W)?Number(W):Number.NaN;if(!Number.isSafeInteger(J)||h>=0&&h!==J)C=!0;else h=J;continue}if(a==="transfer-encoding"){if(W.toLowerCase().includes("chunked"))$=!0;continue}if(a==="connection"){let J=W.toLowerCase();if(J.includes("close"))A=!0;if(J.includes("keep-alive"))T=!0;continue}if(a==="keep-alive")continue}u.push([X,W])}if(w&&T)A=!1;if($&&h>=0)h=-1;return{status:y,headerEnd:n,headers:u,contentLength:h,chunked:$,closeConn:A,malformed:C}}function lC(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 dn;let u=null;if(y){let T=f.get("content-length"),C=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(C)||C>dh)throw dn;if(u=await TC(y),u===null)throw dn}let h=AC(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=fC(t,i.maxPerHost??ZB());for(let T=0;;T++){if(T>0)await new Promise((E)=>{setTimeout(E,T)});let C;try{C=A.acquireIdleSync()??await A.acquireOrDial()}catch(E){if(E!==Mt&&T<4)continue;throw E}try{let E=C.socket.write($);if(E<$.length)await C.writeAll($.subarray(E));return await wC(A,C,w)}catch(E){let B=E===qf&&T<4&&(C.fresh||VB(n));if(A.destroy(C),B)continue;if(E===qf)throw Error("upstream closed connection");throw E}}}async function yC(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 wC(i,t,n){let r;for(;;){let c=await yC(t);if(r=cC(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(lC(r.status,n))return oh(i,t,r.closeConn),new Response(null,{status:r.status,headers:f});if(r.chunked)return new Response($C(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>=iC)w=t.buf.subarray(t.pos,l),t.buf=new Uint8Array(tC);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(uC(i,t,r.contentLength,r.closeConn),{status:r.status,headers:f})}return new Response(hC(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 uC(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 hC(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 $C(i,t,n){t.streamingBody=!0;let r=0,f=!1,c=!1;async function l(){for(;;){for(let y=t.pos;y+1<t.len;y++)if(t.buf[y]===13&&t.buf[y+1]===10){let w=bh.decode(t.buf.subarray(t.pos,y));return t.pos=y+2,w}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(y){try{for(;;){if(r>0){if(t.len===t.pos){if(t.closed){i.destroy(t),y.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let $=Math.min(r,t.len-t.pos);if(y.enqueue(t.buf.slice(t.pos,t.pos+$)),t.pos+=$,r-=$,t.resumeIfDrained(),r===0)f=!0;return}if(f)await l(),f=!1;let w=await l(),u=w.indexOf(";"),h=Number.parseInt(u===-1?w:w.slice(0,u),16);if(!Number.isInteger(h)||h<0){i.destroy(t),y.error(Error("upstream sent malformed chunk size"));return}if(h===0){for(;;)if(await l()==="")break;oh(i,t,n),y.close();return}r=h}}catch(w){if(i.destroy(t),!c)y.error(w)}},cancel(){c=!0,i.destroy(t)}})}function AC(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(
|
|
181
|
+
`;let w=!1;for(let[u,h]of n){let $=u.toLowerCase();if(rC.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
|
-
`,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 VR(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 ml(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:j}=r$(l,u,B,t),X=`ws://${C}${j}${y}`,W={};for(let[J,v]of f.headers)if(!me.has(J.toLowerCase())&&J.toLowerCase()!=="host")W[J]=v;W.host=C,W["x-forwarded-for"]="127.0.0.1",W["x-forwarded-proto"]="https",W["x-forwarded-host"]=w;let F={targetUrl:X,forwardHeaders:W};if(c.upgrade(f,{data:F})){Y("ws",`upgraded ${w}${j} → ${X}`,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===Cl){if(Y("request",`Upstream timeout for ${w}`,t),E)kn(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===dn||!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 j=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:C,body:f.body,redirect:"manual"});if(E)Hf(E,h);return j}catch(C){if(Y("request",`Proxy error for ${w}: ${C}`,t),E)kn(E,h);return new Response(`Proxy Error: ${C}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)kn(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 Ul(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 jl(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(jl(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 Nl(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 Rl(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(jl(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Xl(i,t,n){let r=Rl(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 Wl from"node:path";function bn(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 Sl(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:Wl.join(i.certsDir,c),keyPath:Wl.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 ki from"node:fs/promises";import*as sf from"node:path";var We="acme-account.key",Se=60000,$$=4096;function ae(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 xf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??kr,this.issuer=i.issuer??b0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??Se;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(ae(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),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(i,t.fullChainPem,t.keyPem);let 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([ki.readFile(t,"utf8"),ki.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:sf.join(this.certsDir,`${i}.crt`),keyPath:sf.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([ki.writeFile(r,t,"utf8"),ki.writeFile(f,n,{encoding:"utf8",mode:384})])}get accountKeyPath(){return sf.join(this.certsDir,We)}async loadAccountKey(){try{return await ki.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(i){if(!i||this.accountKeyPem===i)return;this.accountKeyPem=i,await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await ki.writeFile(this.accountKeyPath,i,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as Je,readdirSync as Fe,readFileSync as Ie,statSync as Ke}from"node:fs";import{homedir as Y$}from"node:os";import{isAbsolute as _e,join as mn}from"node:path";var B$=["~/Code"],e$=["localhost","test"],ze=1800000,al={dirExists:(i)=>{try{return Ke(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return Je(i)}catch{return!1}},readText:(i)=>{try{return Ie(i,"utf8")}catch{return null}}};function Jl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return mn(t,i.slice(2));return i}function Qe(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 Me(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 Oe(i,t){let n=t.readText(mn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(mn(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 Ge(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 He(i,t){let n=Oe(i,t);if(n?.command)return Ge(n);let r=t.fileExists(mn(i,"buddy")),f=t.readText(mn(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??He,f=t.homeDir??Y$(),c=i.tlds??e$,l=(i.roots??B$).map((A)=>Jl(A,f)),y=i.idleTimeoutMs??ze,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=_e(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=Me(A,c);if(!T)return null;for(let e of l){let E=mn(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=Qe(A);if(!T)return null;return h(T)??$(T)}}}function qe(i){try{return Fe(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function EX(i,t={}){let n=t.homeDir??Y$(),r=i.tlds??e$,f=(i.roots??B$).map(($)=>Jl($,n)),c=t.readdir??qe,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 ke,readFileSync as Ve}from"node:fs";import*as X$ from"node:fs/promises";import{spawn as de}from"node:child_process";import{homedir as De}from"node:os";import*as Zn from"node:path";import*as Vi from"node:process";import*as kf 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=kf.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=kf.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 eX=new U$;import*as Vf from"node:fs";import*as mi from"node:fs/promises";import{homedir as ge}from"node:os";import*as Kl from"node:path";import*as df from"node:process";var Le=/^[a-zA-Z0-9._-]+$/;function Wt(){return Kl.join(ge(),".stacks","rpx","registry.d")}function _l(i){return typeof i==="string"&&i.length>0&&i.length<=128&&Le.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 df.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 se(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 se(t);let r=zl(t,i.id),f=`${r}.tmp.${df.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 xe(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 Et(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 xe(c,i,t);if(l)r.push(l)}return r}async function Pn(i=Wt(),t){let n=await Et(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;Vf.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,j)=>C.id.localeCompare(j.id)))},$=()=>{if(l=null,y)return;Et(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,Et(n,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=Vf.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 be=120000,Pe=200,Ze=30000,ve=3000,oe=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??Zn.join(De(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??be,this.pollIntervalMs=i.pollIntervalMs??Pe,this.restartDelayMs=i.restartDelayMs??ve,this.killGraceMs=i.killGraceMs??oe,this.launch=i.launcher??iC(this.verbose),this.probePort=i.probePort??pe,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??Ze;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=Zn.join(this.rpxDir,"sites",`${i.id}.log`);await X$.mkdir(Zn.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 S.warn(`rpx: site ${i.host} ${c}`),l;return S.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"){S.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",S.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(),S.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(Vi.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 Ve(i.logPath,"utf8").split(`
|
|
185
|
+
`,nC.encode(y)}async function TC(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 VR(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 EC={".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 YC(i){let t=Qi.extname(i).toLowerCase();return EC[t]??"application/octet-stream"}function BC(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 CC(i,t){let n=BC(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=CC(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":YC(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 eC(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var mC=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function UC(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 jC(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 ml(i,t,n){let r=async(f,c)=>{let{pathname:l,search:y}=jC(f.url),w=UC(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 e=u.stripBasePathPrefix??!0?c$(l,u.basePath):l;return t$(e,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:e,targetPath:j}=r$(l,u,B,t),X=`ws://${e}${j}${y}`,W={};for(let[J,v]of f.headers)if(!mC.has(J.toLowerCase())&&J.toLowerCase()!=="host")W[J]=v;W.host=e,W["x-forwarded-for"]="127.0.0.1",W["x-forwarded-proto"]="https",W["x-forwarded-host"]=w;let F={targetUrl:X,forwardHeaders:W};if(c.upgrade(f,{data:F})){Y("ws",`upgraded ${w}${j} → ${X}`,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,C=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)kn(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===dn||!C)try{let e=new Headers(f.headers);if(e.set("host",$),e.set("x-forwarded-for","127.0.0.1"),e.set("x-forwarded-proto","https"),e.set("x-forwarded-host",w),T!==void 0)e.set("origin",T);let j=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:e,body:f.body,redirect:"manual"});if(E)Hf(E,h);return j}catch(e){if(Y("request",`Proxy error for ${w}: ${e}`,t),E)kn(E,h);return new Response(`Proxy Error: ${e}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)kn(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 Ul(i){let t=new WeakMap,n=eC();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 jl(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(jl(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 NC(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Nl(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 Rl(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(jl(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Xl(i,t,n){let r=Rl(i,t);if(!r)return;for(let f of r)if(NC(n,f.path))return f.route;return}import*as Dn from"node:fs/promises";import*as Wl from"node:path";function bn(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function RC(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 XC(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 Sl(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=RC(c);if(!l)continue;let y=c.slice(0,-4);n.set(l,{certPath:Wl.join(i.certsDir,c),keyPath:Wl.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 XC(f,c.certPath,c.keyPath,t);if(l)r.push(l)}return r}import*as ki from"node:fs/promises";import*as sf from"node:path";var WC="acme-account.key",SC=60000,$$=4096;function aC(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 xf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??kr,this.issuer=i.issuer??b0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??SC;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(aC(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),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(i,t.fullChainPem,t.keyPem);let 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([ki.readFile(t,"utf8"),ki.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:sf.join(this.certsDir,`${i}.crt`),keyPath:sf.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([ki.writeFile(r,t,"utf8"),ki.writeFile(f,n,{encoding:"utf8",mode:384})])}get accountKeyPath(){return sf.join(this.certsDir,WC)}async loadAccountKey(){try{return await ki.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(i){if(!i||this.accountKeyPem===i)return;this.accountKeyPem=i,await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await ki.writeFile(this.accountKeyPath,i,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as JC,readdirSync as FC,readFileSync as IC,statSync as KC}from"node:fs";import{homedir as Y$}from"node:os";import{isAbsolute as _C,join as mn}from"node:path";var B$=["~/Code"],C$=["localhost","test"],zC=1800000,al={dirExists:(i)=>{try{return KC(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return JC(i)}catch{return!1}},readText:(i)=>{try{return IC(i,"utf8")}catch{return null}}};function Jl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return mn(t,i.slice(2));return i}function QC(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 MC(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 OC(i,t){let n=t.readText(mn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(mn(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 GC(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 HC(i,t){let n=OC(i,t);if(n?.command)return GC(n);let r=t.fileExists(mn(i,"buddy")),f=t.readText(mn(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??HC,f=t.homeDir??Y$(),c=i.tlds??C$,l=(i.roots??B$).map((A)=>Jl(A,f)),y=i.idleTimeoutMs??zC,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 C=_C(T.dir)?T.dir:Jl(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=r(C,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let e=E$({...T.env??{}},void 0,A);return{host:A,id:T$(A),dir:C,command:T.command,env:e,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=MC(A,c);if(!T)return null;for(let C of l){let E=mn(C,T);if(!n.dirExists(E))continue;let B=r(E,n);if(!B)continue;let e=B.selfRegisters??!1;return{host:A,id:T$(A),dir:E,command:B.command,env:E$({...B.env??{}},B.urlEnv,A),routes:e?[]:B.routes??[],selfRegisters:e,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=QC(A);if(!T)return null;return h(T)??$(T)}}}function qC(i){try{return FC(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function EX(i,t={}){let n=t.homeDir??Y$(),r=i.tlds??C$,f=(i.roots??B$).map(($)=>Jl($,n)),c=t.readdir??qC,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 kC,readFileSync as VC}from"node:fs";import*as X$ from"node:fs/promises";import{spawn as dC}from"node:child_process";import{homedir as DC}from"node:os";import*as Zn from"node:path";import*as Vi from"node:process";import*as kf 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=kf.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 e$(i,t,n=5000,r){return Y("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let c=kf.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 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 Il(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 CX=new U$;import*as Vf from"node:fs";import*as mi from"node:fs/promises";import{homedir as gC}from"node:os";import*as Kl from"node:path";import*as df from"node:process";var LC=/^[a-zA-Z0-9._-]+$/;function Wt(){return Kl.join(gC(),".stacks","rpx","registry.d")}function _l(i){return typeof i==="string"&&i.length>0&&i.length<=128&&LC.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 df.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 sC(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 sC(t);let r=zl(t,i.id),f=`${r}.tmp.${df.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 xC(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 Et(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 xC(c,i,t);if(l)r.push(l)}return r}async function Pn(i=Wt(),t){let n=await Et(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;Vf.mkdirSync(n,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((e)=>({id:e.id,from:e.from,to:e.to,path:e.path,pid:e.pid,pathRewrites:e.pathRewrites,cleanUrls:e.cleanUrls,changeOrigin:e.changeOrigin,static:e.static,loadBalancer:e.loadBalancer})).sort((e,j)=>e.id.localeCompare(j.id)))},$=()=>{if(l=null,y)return;Et(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)},C=setInterval(()=>{if(y||u)return;u=!0,Et(n,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=Vf.watch(n,{persistent:!0},(B,e)=>{if(e&&/\.tmp\.\d+\.\d+$/.test(e))return;A()});return E.on("error",(B)=>{Y("registry",`watcher error: ${B}`,c)}),A(),{close:()=>{if(y=!0,l)clearTimeout(l);clearInterval(C),E.close()}}}var bC=120000,PC=200,ZC=30000,vC=3000,oC=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??Zn.join(DC(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??bC,this.pollIntervalMs=i.pollIntervalMs??PC,this.restartDelayMs=i.restartDelayMs??vC,this.killGraceMs=i.killGraceMs??oC,this.launch=i.launcher??ie(this.verbose),this.probePort=i.probePort??pC,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??ZC;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=Zn.join(this.rpxDir,"sites",`${i.id}.log`);await X$.mkdir(Zn.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 S.warn(`rpx: site ${i.host} ${c}`),l;return S.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"){S.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",S.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(),S.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(Vi.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 VC(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),S.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
|
|
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),S.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 pC(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 ie(i){let t=te();return({command:n,cwd:r,env:f,logPath:c})=>{let l=kC(c,"a");try{let y=dC("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{Vi.kill(-w,h)}catch{try{y.kill(h)}catch{}}}}}catch(y){try{R$(l)}catch{}throw y}}}function te(){if(Vi.platform==="win32")return null;if(!(typeof Vi.getuid==="function"&&Vi.getuid()===0))return null;let t=Number.parseInt(Vi.env.SUDO_UID??"",10),n=Number.parseInt(Vi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(n)||n<=0)return null;return{uid:t,gid:n}}function Un(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var ne=`
|
|
188
188
|
:root { color-scheme: light dark }
|
|
189
189
|
* { box-sizing: border-box }
|
|
190
190
|
body {
|
|
@@ -217,7 +217,7 @@ x-forwarded-host: ${f}\r
|
|
|
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>${Un(i)}</title>
|
|
220
|
-
<style>${
|
|
220
|
+
<style>${ne}</style>
|
|
221
221
|
</head>
|
|
222
222
|
<body><main class="card">${t}</main></body>
|
|
223
223
|
</html>`}function S$(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),n=i.logTail?`<pre>${Un(i.logTail)}</pre>`:"",r=`
|
|
@@ -229,24 +229,24 @@ ${n>0?`<meta http-equiv="refresh" content="${n}">`:""}
|
|
|
229
229
|
<div class="row"><div class="dot"></div><h1>${Un(i.host)} failed to start</h1></div>
|
|
230
230
|
<p>${Un(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(W$(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as
|
|
233
|
-
`),c=[],l=0;while(l<f.length){let y=f[l];if(y.trim()===
|
|
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 re}from"node:child_process";import on from"node:fs";import fe from"node:os";import K$ from"node:path";import*as Gt from"node:process";import{promisify as ce}from"node:util";var vn=ce(re);function J$(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var Pi=Gt.platform==="win32"?K$.join(Gt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",F$="# rpx",le="# Added by rpx",pn=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 vn(i);return r}let t=Hl(),n=i.replace(/'/g,"'\\''");try{if(t){let{stdout:r}=await vn(`echo '${t}' | sudo -S sh -c '${n}' 2>/dev/null`);return Gl=!0,r}if(Gl)try{let{stdout:r}=await vn(`sudo -n sh -c '${n}'`);return r}catch(r){Y("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:r}=await vn(`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 ir(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=ir(i);return n!==null&&pn.has(n.address)&&n.names.includes(t)}function ye(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()===le){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=ir(A),C=T!==null&&pn.has(T.address)&&T.names.some((E)=>n.has(E));if(C){for(let E of T.names)if(n.has(E))r.add(E)}return!C});if($.length>0||u.length===0)c.push(y,...$);l=h;continue}let w=ir(y);if(w?.rpxManaged&&pn.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
|
|
235
|
+
`,removed:[...r]}}function we(i,t){let n=[],r=new Set,f=[];for(let c of i.split(`
|
|
236
236
|
`)){let l=ir(c);if(l?.rpxManaged&&l.rpxPid!==null&&pn.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 ql(i){try{return await on.promises.readFile(Pi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),_$(`cat "${Pi}"`)}}async function gl(i,t){let n=K$.join(
|
|
238
|
+
`,removed:n,stalePids:[...r]}}async function ql(i){try{return await on.promises.readFile(Pi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),_$(`cat "${Pi}"`)}}async function gl(i,t){let n=K$.join(fe.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await on.promises.writeFile(n,i,"utf8"),await _$(`cat "${n}" | tee "${Pi}" > /dev/null`)}finally{await on.promises.unlink(n).catch((r)=>{Y("hosts",`Failed to remove temporary file: ${r}`,t)})}}async function qX(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: ${Pi}`,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
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
240
|
127.0.0.1 ${u} ${F$}:pid=${y}
|
|
241
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 ${Pi}`)}}catch(f){Y("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function gX(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}=
|
|
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 ${Pi}`)}}catch(f){Y("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function gX(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}=ye(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 LX(i,t){Y("hosts",`Checking hosts: ${i}`,t);let n;try{n=await on.promises.readFile(Pi,"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 "${Pi}" 2>/dev/null`;else l=`sudo -n cat "${Pi}" 2>/dev/null || cat "${Pi}" 2>/dev/null || echo ""`;let{stdout:y}=await vn(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
243
|
`);return i.map((f)=>r.some((c)=>z$(c,f)))}async function sX(i=Ui){let t;try{t=await on.promises.readFile(Pi,"utf-8")}catch{return[]}let n=[];for(let r of t.split(`
|
|
244
|
-
`)){let f=ir(r);if(f?.rpxManaged&&f.rpxPid!==null&&pn.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function tr(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}=
|
|
245
|
-
`)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await Nn(i);if(n!==null&&Ui(n))throw Error(`rpx daemon already running (pid=${n})`);await Ti.unlink(t).catch(()=>{})}}async function jn(i=ji()){await Ti.unlink(vf(i)).catch(()=>{})}var Pf=new Map;function Zf(i){for(let[t,n]of Pf)if(!i.has(t))Bl(n),Pf.delete(t)}function $
|
|
246
|
-
`),u.stdin.end();u.unref();let A=vf(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let
|
|
247
|
-
`):A.ca}:null,
|
|
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
|
|
244
|
+
`)){let f=ir(r);if(f?.rpxManaged&&f.rpxPid!==null&&pn.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function tr(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}=we(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 ue=5000;function ji(){return Zi.join(q$(),".stacks","rpx")}function vf(i=ji()){return Zi.join(i,"daemon.pid")}async function Nn(i=ji()){try{let t=await Ti.readFile(vf(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 he(i=ji()){let t=await Nn(i);return t!==null&&Ui(t)}async function g$(i=ji()){await Ti.mkdir(i,{recursive:!0});let t=vf(i);while(!0){try{let r=await Ti.open(t,"wx");try{await r.write(`${U.pid}
|
|
245
|
+
`)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await Nn(i);if(n!==null&&Ui(n))throw Error(`rpx daemon already running (pid=${n})`);await Ti.unlink(t).catch(()=>{})}}async function jn(i=ji()){await Ti.unlink(vf(i)).catch(()=>{})}var Pf=new Map;function Zf(i){for(let[t,n]of Pf)if(!i.has(t))Bl(n),Pf.delete(t)}function $e(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=Pf.get(i.id);if(y&&!$e(y,f))Bl(y),y=void 0;if(!y)y=Hh(f,i.loadBalancer),gh(y),Pf.set(i.id,y);return{sourceHost:l.host,upstreamPool:y,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:n,auth:r}}function Ae(i){return i.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??i[0]??"rpx.localhost"}async function bf(i,t,n=[],r=!1){let f=await Et(t,i.verbose),c=[...new Set([...f.map((h)=>h.to).filter(Boolean),...n])],l=Ae(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 El(w);if(u&&(r||!fl($l,y)))Y("daemon",`regenerating shared cert for host(s): ${y.join(", ")}`,i.verbose),Tl(),u=null;if(!u)Y("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Qh({...w,forceRegenerate:!0}),u=await El(w);if(!u)throw Error("failed to bootstrap TLS for rpx daemon");return u}async function Te(i,t,n,r){let f=U.env.SUDO_PASSWORD,c=U.env.HOME??q$(),l=[U.execPath,...U.argv.slice(1)],y=[`HOME=${c}`,`PATH=${U.env.PATH??""}`];if(r)y.push("RPX_VERBOSE=1");for(let[C,E]of Object.entries(U.env))if(E!==void 0&&C!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(C))y.push(`${C}=${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",(C)=>{h=C}),u.once("exit",(C)=>{$=C??0}),f&&u.stdin)u.stdin.write(`${f}
|
|
246
|
+
`),u.stdin.end();u.unref();let A=vf(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let C=await Nn(i);if(C!==null&&Ui(C)){if(r)S.success(`rpx daemon elevated to root (pid=${C}, https on :${t})`);return{httpsPort:t,httpPort:n,pidPath:A,done:Promise.resolve(),stop:async()=>{try{U.kill(C,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if($!==null&&$!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${$}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((E)=>setTimeout(E,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var Q$=!1;function Ll(){if(Q$)return;Q$=!0,U.on("uncaughtException",(i)=>{S.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),U.on("unhandledRejection",(i)=>{S.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 hW(i={}){Ll();let t=i.verbose??!1,n=i.rpxDir??ji(),r=i.registryDir??Zi.join(n,"registry.d"),f=i.httpsPort??443,c=i.httpPort??80,l=i.hostname??"0.0.0.0",y=i.gcIntervalMs??ue;if(U.env.RPX_DAEMON_WORKER==="1")return Be({rpxDir:U.env.RPX_WORKER_RPXDIR??n,registryDir:U.env.RPX_WORKER_REGISTRYDIR??r,httpsPort:Number.parseInt(U.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:U.env.RPX_WORKER_HOSTNAME??l,verbose:U.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||c>0&&c<1024,u=typeof U.getuid==="function"&&U.getuid()===0;if(U.platform!=="win32"&&w&&!u)return Te(n,f,c,t);let h=Math.max(1,i.workers??(Number.parseInt(U.env.RPX_WORKERS??"",10)||1));if(h>1){if(i.onDemandSites?.enabled)S.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return Ce(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,I)=>Xl(A,m,I);function C(m){A=Nl(m.map((Di)=>({host:Di.to,path:Di.path,route:L$(Di)}))),Zf(new Set(m.map((Di)=>Di.id)));let I=Array.from(A.keys());Y("daemon",`routing table now covers ${I.length} host(s): ${I.join(", ")||"<empty>"}`,t)}await Pn(r,t).catch((m)=>{Y("daemon",`initial gc failed: ${m}`,t)}),await tr({verbose:t}).catch((m)=>{Y("daemon",`stale hosts GC on start failed: ${m}`,t)});let E=await Et(r,t);C(E),await Xn({rpxDir:n,verbose:t}).catch((m)=>{Y("daemon",`DNS reconcile on start failed: ${m}`,t)}),await nr(E,{rpxDir:n,verbose:t,ownerPid:U.pid}).catch((m)=>{Y("daemon",`DNS setup on start failed: ${m}`,t)});let B=[];if(i.productionCerts){if(B=await Sl(i.productionCerts,t),t&&B.length>0)S.info(`SNI: serving ${B.length} real cert(s): ${B.map((m)=>m.serverName).join(", ")}`)}let e=new Set,j=null,X;if(i.onDemandSites?.enabled){if(j=new Ol({resolver:Fl(i.onDemandSites),registryDir:r,rpxDir:n,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(m)=>Rl(A,m)!==void 0,onSiteActivating:(m)=>{It(m)}}),X=async(m)=>{let I=await j.onRequest(m);switch(I.kind){case"ready":return{retry:!0};case"starting":return S$({host:I.host,sinceMs:I.sinceMs,logTail:I.logTail});case"failed":return a$({host:I.host,error:I.error,logTail:I.logTail});case"unknown":default:return}},t)S.info("rpx: on-demand sites enabled")}let W=ml(T,t,X),F=Ul(t),a=null;if(B.length===0)a=await bf(i,r);let J=i.onDemandTls,v=J?.enabled?new xf({config:J,certsDir:J.certsDir??i.productionCerts?.certsDir??Zi.join(n,"on-demand-certs"),initial:B,verbose:t,onCertAdded:(m)=>{gt(m)}}):null;function Mi(m){if(m.length>0)return bn(m.map((I)=>({serverName:I.serverName,cert:I.cert,key:I.key})));return bn({key:a.key,cert:a.cert,ca:a.ca,requestCert:!1,rejectUnauthorized:!1})}function Ht(m){return Bun.serve({port:f,hostname:l,reusePort:G$(),tls:Mi(m),fetch(I,Di){return W(I,Di)},websocket:F,error(I){return Y("daemon",`https server error: ${I}`,t),new Response(`Server Error: ${I.message}`,{status:500})}})}let at=(m)=>[...new Set(m.map((I)=>I.to).filter(Boolean))],qt=(m)=>{if(!a)return B;return Kh([...at(m),...e,"rpx.localhost"],a)},Bt=Ht(v?v.sniEntries():B.length>0?B:qt(E)),Jt=null,Ft=!1;async function gt(m){if(di)return;if(Jt=m,Ft)return;Ft=!0;try{while(!di&&Jt){let I=Jt;Jt=null,Y("daemon",`rebuilding :443 with ${I.length} SNI cert(s)`,t),Bt.stop(!1);let Di,f0=!1,vl=60,r1=500;for(let c0=0;!di&&!f0;c0++)try{Bt=Ht(I),f0=!0;break}catch(f1){if(Di=f1,c0>=vl)break;await new Promise((c1)=>setTimeout(c1,Math.min(25*2**Math.min(c0,4),r1)))}if(!f0)S.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 vi=null;if(c>0)vi=Bun.serve({port:c,hostname:l,fetch(m){return s$(m,v,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)S.success(`rpx daemon listening on https://${l}:${f}${vi?` (http→https on :${c})`:""}`),S.info(`pid file: ${$}`),S.info(`registry: ${r}`);async function K(m){if(di||B.length>0||v||!a)return;try{a=await bf(i,r,[...e]),await gt(qt(m))}catch(I){Y("daemon",`TLS sync on registry change failed: ${I}`,t)}}async function It(m){if(di||B.length>0||v||!a||!m)return;if(e.has(m))return;e.add(m);try{a=await bf(i,r,[...e],!0);let I=await Et(r,t);await gt(qt(I))}catch(I){Y("daemon",`dev cert refresh for ${m} failed: ${I}`,t)}}let n0=Df((m)=>{C(m),K(m),nr(m,{rpxDir:n,verbose:t,ownerPid:U.pid}).catch((I)=>{Y("daemon",`DNS sync on registry change failed: ${I}`,t)})},{dir:r,verbose:t}),Lt=setInterval(()=>{Pn(r,t).then((m)=>{if(m>0)Y("daemon",`gc reaped ${m} stale entries`,t)}).catch((m)=>{Y("daemon",`periodic gc failed: ${m}`,t)}),tr({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 Lt.unref==="function")Lt.unref();let di=!1,Wn,st=new Promise((m)=>{Wn=m});async function r0(){if(di)return st;if(di=!0,clearInterval(Lt),n0.close(),await j?.stopAll().catch((m)=>{Y("daemon",`site supervisor stopAll failed: ${m}`,t)}),Bt.stop(!1),vi?.stop(!1),await Rn({rpxDir:n,verbose:t}).catch((m)=>{Y("daemon",`DNS teardown failed: ${m}`,t)}),Zf(new Set),await jn(n),t)S.info("rpx daemon stopped");return Wn(),st}let Zl=(m)=>{Y("daemon",`received ${m}, shutting down`,t),r0().catch(()=>{})};return U.once("SIGINT",Zl),U.once("SIGTERM",Zl),{stop:r0,done:st,httpsPort:typeof Bt.port==="number"?Bt.port:f,httpPort:vi&&typeof vi.port==="number"?vi.port:c,pidPath:$,ensureCert:(m)=>v?v.ensureCert(m):Promise.resolve(!1),listSites:()=>j?.list()??[]}}function sl(i){return Zi.join(i,"cluster-sni.json")}async function M$(i,t,n){let r=sl(i),f=`${r}.${U.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 Ee(i){if(i.sni.length>0)return bn(i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(i.dev)return bn({key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function Ye(){let i=U.execPath,t=U.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let n=Zi.basename(i).toLowerCase();if((n==="bun"||n==="node"||n.startsWith("bun-"))&&U.argv[1])return[i,U.argv[1],"daemon:start"];return[i,"daemon:start"]}async function Be(i){Ll();let{rpxDir:t,registryDir:n,httpsPort:r,hostname:f,verbose:c}=i,l=new Map,y=(a,J)=>Xl(l,a,J),w=(a)=>{l=Nl(a.map((J)=>({host:J.to,path:J.path,route:L$(J)}))),Zf(new Set(a.map((J)=>J.id)))};w(await Et(n,c));let u=ml(y,c),h=Ul(c),$=!1,A=(a)=>Bun.serve({port:r,hostname:f,reusePort:!0,tls:Ee(a),fetch(J,v){return u(J,v)},websocket:h,error(J){return Y("daemon",`worker https error: ${J}`,c),new Response(`Server Error: ${J.message}`,{status:500})}}),T=A(await O$(t));async function C(){if($)return;let a=await O$(t),J=null;for(let Mi=0;Mi<20&&!$;Mi++)try{J=A(a);break}catch{await new Promise((Ht)=>setTimeout(Ht,25))}if(!J){Y("daemon","worker reloadTls: could not bind new listener; keeping current",c);return}let v=T;T=J,v.stop(!1)}let E=Df((a)=>w(a),{dir:n,verbose:c}),B=()=>{C().catch(()=>{})};U.on("SIGHUP",B);let e=()=>{let a=U.removeListener??U.off;if(typeof a==="function")a.call(U,"SIGHUP",B)},j,X=new Promise((a)=>{j=a});async function W(){if($)return X;return $=!0,e(),E.close(),T.stop(!1),Zf(new Set),j(),X}let F=()=>{W().then(()=>U.exit(0)).catch(()=>U.exit(0))};if(U.once("SIGTERM",F),U.once("SIGINT",F),c)S.success(`rpx worker (pid ${U.pid}) serving :${r}`);return{stop:W,done:X,httpsPort:typeof T.port==="number"?T.port:r,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function Ce(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 Sl(i.productionCerts,y);let A=null;if($.length===0)A=await bf(i,r);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
|
|
247
|
+
`):A.ca}:null,C=!1,E=[];function B(K){for(let It of E)try{It.kill(K)}catch{}}async function e(K){await M$(n,K,T),B("SIGHUP")}let j=i.onDemandTls,X=j?.enabled?new xf({config:j,certsDir:j.certsDir??i.productionCerts?.certsDir??Zi.join(n,"on-demand-certs"),initial:$,verbose:y,onCertAdded:(K)=>{e(K)}}):null;await M$(n,X?X.sniEntries():$,T);let W=await Et(r,y);await Xn({rpxDir:n,verbose:y}).catch((K)=>{Y("daemon",`DNS reconcile on start failed: ${K}`,y)}),await nr(W,{rpxDir:n,verbose:y,ownerPid:U.pid}).catch((K)=>{Y("daemon",`DNS setup on start failed: ${K}`,y)}),await Pn(r,y).catch(()=>{}),await tr({verbose:y}).catch(()=>{});let F=Df((K)=>{nr(K,{rpxDir:n,verbose:y,ownerPid:U.pid}).catch((It)=>{Y("daemon",`DNS sync on registry change failed: ${It}`,y)})},{dir:r,verbose:y}),a=setInterval(()=>{Pn(r,y).catch(()=>{}),tr({verbose:y}).catch(()=>{})},w);a.unref?.();let J=null;if(c>0)J=Bun.serve({port:c,hostname:l,fetch(K){return s$(K,X,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let v=10,Mi=60000,Ht=30000,at=0,qt=Date.now();function Bt(){if(C)return;let K={...U.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(Ye(),{env:K,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n0,Lt){if(C)return;let di=E.indexOf(n0);if(di!==-1)E.splice(di,1);let Wn=Date.now();if(Wn-qt>Mi)qt=Wn,at=0;if(at++,at>v){S.error(`rpx: worker keeps exiting (code ${Lt}); giving up after ${v} restarts in ${Math.round(Mi/1000)}s`);return}let st=Math.min(Ht,100*2**Math.min(at,8));Y("daemon",`worker exited (code ${Lt}); respawning in ${st}ms (restart ${at}/${v})`,y),setTimeout(Bt,st).unref?.()}});E.push(It)}for(let K=0;K<u;K++)Bt();if(y)S.success(`rpx coordinator listening on https://${l}:${f} via ${u} worker(s)${J?` (http→https on :${c})`:""}`),S.info(`pid file: ${h}`);let Jt,Ft=new Promise((K)=>{Jt=K});async function gt(){if(C)return Ft;if(C=!0,clearInterval(a),F.close(),J?.stop(!1),B("SIGTERM"),await Promise.race([Promise.all(E.map((K)=>K.exited)),new Promise((K)=>setTimeout(K,3000))]),B("SIGKILL"),await Rn({rpxDir:n,verbose:y}).catch((K)=>{Y("daemon",`DNS teardown failed: ${K}`,y)}),await jn(n),await Ti.unlink(sl(n)).catch(()=>{}),y)S.info("rpx coordinator stopped");return Jt(),Ft}let vi=(K)=>{Y("daemon",`coordinator received ${K}, shutting down`,y),gt().catch(()=>{})};return U.once("SIGINT",vi),U.once("SIGTERM",vi),{stop:gt,done:Ft,httpsPort:f,httpPort:c,pidPath:h,ensureCert:(K)=>X?X.ensureCert(K):Promise.resolve(!1),listSites:()=>[]}}function ee(){let i=U.execPath,t=Zi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&U.argv[1])return[i,U.argv[1],"daemon:start"];return[i,"daemon:start"]}async function $W(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1;await Xn({rpxDir:t,verbose:n}).catch((h)=>{Y("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,n)});let r=await Nn(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 jn(t);await Ti.mkdir(t,{recursive:!0});let f=i.spawnCommand??ee();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??U.cwd(),env:i.spawnEnv?{...U.env,...i.spawnEnv}:U.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 Nn(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 AW(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1,r=i.timeoutMs??5000,f=i.pollIntervalMs??50,c=i.forceAfterTimeout??!0,l=await Nn(t);if(l===null||!Ui(l)){if(l!==null)await jn(t);return await Xn({rpxDir:t,verbose:n}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{U.kill(l,"SIGTERM")}catch(w){let u=w.code;if(u==="ESRCH")return await jn(t),{stopped:!1,pid:l,forced:!1};if(u==="EPERM")Rt(`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{U.kill(l,"SIGKILL")}catch(w){let u=w.code;if(u==="EPERM")Rt(`kill -KILL ${l}`);else if(u!=="ESRCH")throw w}return await jn(t),await Rn({rpxDir:t,verbose:n}).catch((w)=>{Y("daemon",`DNS teardown after SIGKILL: ${w}`,n)}),{stopped:!0,pid:l,forced:!0}}async function TW(i={}){let t=i.rpxDir??ji();if(await he(t))return;await Xn({rpxDir:t,verbose:i.verbose})}import*as St from"node:fs/promises";import{homedir as me}from"node:os";import*as xl from"node:path";var of=1,Ue="dns-state.json",x$=["com","test","dev","app","page","local","localhost","example","invalid"];function k$(){return xl.join(me(),".stacks","rpx")}function kl(i=k$()){return xl.join(i,Ue)}async function pf(i=k$()){try{let t=await St.readFile(kl(i),"utf8"),n=JSON.parse(t);if(n.version!==of||!Array.isArray(n.resolvers))return null;return{version:of,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 je(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=je(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 t0=15353,Ne="# managed-by: rpx",Z$="/etc/resolver",Ni=null,i0=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 Re(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 rr(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 Xe(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(rr(t.name));let c=Buffer.alloc(4);c.writeUInt16BE(t.type,0),c.writeUInt16BE(t.class,2),r.push(c),r.push(rr(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,rr(t.name),c]);return Buffer.concat(r)}function We(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(rr(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 Se(i,t){if(Yt.platform!=="darwin")return!1;let n=Dl(i);if(n.length===0)return!1;if(Ni){for(let r of n)i0.add(r);return Y("dns","DNS server already running — merged domains",t),!0}return i0=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}=Re(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 i0)if(w===$||w.endsWith(`.${$}`)){u=!0;break}let h;if(u&&(y.type===1||y.type===28))h=Xe(l.id,y,"127.0.0.1"),Y("dns",`Responding with localhost for ${y.name}`,t);else h=We(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(t0,"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,i0=new Set}function NW(){return Ni!==null}async function ae(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=Je(n,1);f.send(l,t0,"127.0.0.1",(y)=>{if(y)clearTimeout(c),f.close(),r(!1)})})}function Je(i,t){let n=Buffer.alloc(12);n.writeUInt16BE(1,0),n.writeUInt16BE(256,2),n.writeUInt16BE(1,4);let r=Buffer.concat([rr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([n,r])}function Fe(){return`${Ne}
|
|
249
249
|
nameserver 127.0.0.1
|
|
250
250
|
port ${t0}
|
|
251
|
-
`}function fr(i){return P$.join(Z$,i)}function
|
|
252
|
-
export{S as a,Rh as b,jB as c,Qt as d,rl as e,fl as f,NB as g,RB as h,bi as i,Tt as j,cl as k,Ln as l,ll as m,Xh as n,Of as o,sn as p,xn as q,yl as r,$l as s,Kh as t,_h as u,Al as v,zR as w,QR as x,MR as y,Qh as z,Tl as A,El as B,Yl as C,OR as D,Mh as E,Gh as F,Hh as G,qh as H,Hf as I,kn as J,gh as K,Bl as L,sB as M,xh as N,kh as O,VR as P,ph as Q,i$ as R,
|
|
251
|
+
`}function fr(i){return P$.join(Z$,i)}function Ie(i){return i.includes("127.0.0.1")&&i.includes(String(t0))}async function Ke(i){try{return await b$.readFile(fr(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function bl(i){if(Yt.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 _e(i,t){i1(i);let{execSudoSync:n}=await import("./chunk-q0831dgh.js"),r=Fe().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${Z$} && printf "%b" "${r}" > ${fr(i)}'`;n(f),Y("dns",`Created ${fr(i)}`,t)}async function ze(i,t){i1(i);let{execSudoSync:n}=await import("./chunk-q0831dgh.js");n(`rm -f ${fr(i)}`),Y("dns",`Removed ${fr(i)}`,t)}async function RW(i,t){return n1({domains:t??[],verbose:i})}async function Qe(i,t){if(Yt.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 _e(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(Yt.platform!=="darwin")return;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-q0831dgh.js");if(!r()&&!n())return;try{for(let f of i)await ze(f,t);await bl(t)}catch(f){Y("dns",`Failed to remove resolver files: ${f}`,t)}}async function t1(i){if(Yt.platform!=="darwin")return[];let t=[];for(let n of x$){let r=await Ke(n);if(r&&Ie(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 Se(n,i.verbose);if(!f){let y=n[0];if(y&&await ae(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 Qe(r,i.verbose))return!1;let l={version:of,resolvers:r,domains:n,ownerPid:i.ownerPid??Yt.pid,updatedAt:new Date().toISOString()};return await V$(t,l),!0}async function nr(i,t={}){let n=i.map((w)=>w.to).filter(Boolean),r=t.rpxDir??ji(),f=dl(n),y=((await pf(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??Yt.pid})}async function Rn(i={}){let t=i.rpxDir??ji();p$(i.verbose);let r=(await pf(t))?.resolvers??[];await Pl(r,i.verbose),await t1(i.verbose),await Vl(t)}async function XW(i){await Rn({verbose:i})}async function Xn(i={}){let t=i.rpxDir??ji(),n=await pf(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 Rn(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{S as a,Rh as b,jB as c,Qt as d,rl as e,fl as f,NB as g,RB as h,bi as i,Tt as j,cl as k,Ln as l,ll as m,Xh as n,Of as o,sn as p,xn as q,yl as r,$l as s,Kh as t,_h as u,Al as v,zR as w,QR as x,MR as y,Qh as z,Tl as A,El as B,Yl as C,OR as D,Mh as E,Gh as F,Hh as G,qh as H,Hf as I,kn as J,gh as K,Bl as L,sB as M,xh as N,kh as O,VR as P,ph as Q,i$ as R,YC as S,BC as T,CC as U,t$ as V,c$ as W,ml as X,Ul as Y,l$ as Z,u$ as _,Lf as $,jl as aa,h$ as ba,Ot as ca,NC as da,Nl as ea,Rl as fa,Xl as ga,bn as ha,RC as ia,Sl as ja,aC as ka,A$ as la,xf as ma,Jl as na,T$ as oa,MC as pa,OC as qa,HC as ra,Fl as sa,EX as ta,m$ as ua,Il as va,U$ as wa,CX as xa,Wt as ya,_l as za,Ui as Aa,N$ as Ba,Ql as Ca,xC as Da,Et as Ea,Pn as Fa,Df as Ga,Ol as Ha,Un as Ia,S$ as Ja,a$ as Ka,F$ as La,ir as Ma,z$ as Na,ye as Oa,we as Pa,qX as Qa,gX as Ra,LX as Sa,sX as Ta,tr as Ua,of as Va,x$ as Wa,d$ as Xa,je as Ya,dl as Za,Dl as _a,t0 as $a,Ne as ab,Se as bb,p$ as cb,NW as db,ae as eb,fr as fb,Ie as gb,RW as hb,t1 as ib,n1 as jb,nr as kb,Rn as lb,XW as mb,Xn as nb,ji as ob,vf as pb,Nn as qb,he as rb,g$ as sb,jn as tb,hW as ub,ee as vb,$W as wb,AW as xb,TW as yb};
|