@stacksjs/rpx 0.11.39 → 0.11.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import{Ab as g,Bb as ql,Cb as K$,Eb as Nt,Fb as Y,Gb as H$,Kb as Jh,Lb as hl,Nb as Gf,Ob as Fh,Qb as c$,Rb as Ih}from"./chunk-w4t1nar9.js";import b$ from"node:dgram";import*as P$ from"node:fs/promises";import*as Z$ from"node:path";import*as Yt from"node:process";import{spawn as q$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as s$}from"node:os";import*as Zi from"node:path";import*as C 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 er}from"node:os";import*as Kh from"node:path";import{join as D}from"node:path";import*as xi from"node:process";import{createRequire as y1}from"node:module";import{Resolver as l0}from"node:dns/promises";import{createHash as u1,sign as h1}from"node:crypto";import{createHash as $1}from"node:crypto";import{sign as A1}from"node:crypto";import{generateKeyPairSync as fw,X509Certificate as j1}from"node:crypto";import y0 from"node:os";import w0 from"node:path";import{existsSync as iy,statSync as ty}from"fs";import{existsSync as N1,mkdirSync as Dm,readdirSync as bm,readFileSync as W1,writeFileSync as Pm}from"fs";import{homedir as xt}from"os";import{dirname as om,resolve as Ji}from"path";import Vn from"process";import{existsSync as ry,statSync as ny}from"fs";import{existsSync as _0,mkdirSync as X1,readdirSync as S1,writeFileSync as a1}from"fs";import{homedir as kt}from"os";import{dirname as fy,resolve as Yi}from"path";import _t from"process";import{join as J1,relative as F1,resolve as cy}from"path";import Jn from"process";import{existsSync as cw,mkdirSync as wC,readdirSync as uC,writeFileSync as hC}from"fs";import{homedir as u0}from"os";import{dirname as TC,resolve as Ei}from"path";import Fr from"process";import{join as I1,relative as K1,resolve as ly}from"path";import Fn from"process";import{existsSync as lw,mkdirSync as mC,readdirSync as CC,writeFileSync as UC}from"fs";import{dirname as RC,resolve as In}from"path";import z0 from"process";import{Buffer as et}from"buffer";import{createCipheriv as _1,createDecipheriv as z1,randomBytes as h0}from"crypto";import{closeSync as $0,createReadStream as yy,createWriteStream as Q1,existsSync as A0,fsyncSync as wy,openSync as uy,writeFileSync as M1}from"fs";import{access as O1,constants as hy,mkdir as G1,readdir as cn,rename as $y,stat as Vt,unlink as ln,writeFile as T0}from"fs/promises";import{join as dt}from"path";import yi from"process";import{pipeline as H1}from"stream/promises";import{createGzip as Ay}from"zlib";import Dt from"process";import tt from"process";import{Buffer as oi}from"buffer";import{createCipheriv as q1,createDecipheriv as s1,randomBytes as E0}from"crypto";import{closeSync as Y0,createReadStream as Ty,createWriteStream as g1,existsSync as yn,fsyncSync as Ey,openSync as Yy,writeFileSync as L1}from"fs";import{access as x1,constants as By,mkdir as k1,readdir as wn,rename as ey,stat as bt,unlink as un,writeFile as B0}from"fs/promises";import{isAbsolute as V1,join as Pt,resolve as d1}from"path";import H from"process";import{pipeline as D1}from"stream/promises";import{createGzip as my}from"zlib";import Zt from"process";import rt from"process";import hn from"process";import{existsSync as $n}from"fs";import{resolve as e0}from"path";import{existsSync as b1}from"fs";import{existsSync as P1,readdirSync as Z1}from"fs";import{extname as m0,resolve as Cy}from"path";import v1 from"process";import{join as o1,relative as p1,resolve as Uy}from"path";import Kn from"process";import{Buffer as pi}from"buffer";import{createCipheriv as iA,createDecipheriv as tA,randomBytes as C0}from"crypto";import{closeSync as U0,createReadStream as jy,createWriteStream as rA,existsSync as An,fsyncSync as Ry,openSync as Ny,writeFileSync as nA}from"fs";import{access as fA,constants as Wy,mkdir as cA,readdir as Tn,rename as Xy,stat as vt,unlink as En,writeFile as j0}from"fs/promises";import{isAbsolute as lA,join as ot,resolve as yA}from"path";import q from"process";import{pipeline as wA}from"stream/promises";import{createGzip as Sy}from"zlib";import pt from"process";import nt from"process";import Yn from"process";import{existsSync as Bn}from"fs";import{resolve as R0}from"path";import{existsSync as uA}from"fs";import{exec as KT}from"node:child_process";import k0 from"node:fs";import _T from"node:os";import Oi from"node:path";import Lw from"node:process";import{promisify as zT}from"node:util";import nr from"node:crypto";import ft from"node:fs";import D0 from"node:path";import rE from"node:crypto";import nE from"node:fs";import fE from"node:tls";import{execSync as yE}from"node:child_process";import xn from"node:os";var w1=y1(import.meta.url),ky=30000;async function Cn(i,t={},r=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(r)})}catch(n){if(n&&typeof n==="object"&&n.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${r}ms`);throw f.name="AcmeRequestTimeoutError",f}throw n}}async function Vy(i,t,r={}){let n=r.timeoutMs??120000,f=r.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()+n,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 Jr{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(Jr.PATH_PREFIX);if(t===-1)return;let r=i.slice(t+Jr.PATH_PREFIX.length);return this.get(r)}}var kn=new Jr;function Un(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function J0(i){return Buffer.from(i,"base64url")}function dy(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 u1("sha256").update(t).digest("base64url")}function by(i){let{protectedHeader:t,payload:r,privateKey:n}=i,f=Un(JSON.stringify(t)),c=r===""?"":Un(JSON.stringify(r)),l=`${f}.${c}`,y=h1("sha256",Buffer.from(l),{key:n,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Un(y)}}var Py="https://acme-staging-v02.api.letsencrypt.org/directory",Zy="https://acme-v02.api.letsencrypt.org/directory";class Sn extends Error{problem;httpStatus;constructor(i,t,r){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class an{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=dy(i.accountPublicKey),this.thumbprint=Dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??ky}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await Cn(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 Cn(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:r,useJwk:n}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)f.jwk=this.jwk;else f.kid=this.requireKid();let c=by({protectedHeader:f,payload:r,privateKey:this.accountKey}),l=await Cn(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 Sn(`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(),r={termsOfServiceAgreed:!0};if(i.email)r.contact=[`mailto:${i.email}`];let n=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(i){let t=await this.directory(),r={identifiers:i.map((f)=>({type:"dns",value:f}))},n=await this.signedPost({url:t.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return $1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let 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 Sn(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await pl(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let 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 pl(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let r=i.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return r}}function vy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${i.trim()}
|
|
1
|
+
import{Ab as s,Bb as gl,Cb as z$,Eb as Wt,Fb as Y,Gb as g$,Kb as Kh,Lb as $l,Nb as Hf,Ob as Ih,Qb as y$,Rb as _h}from"./chunk-w4t1nar9.js";import Z$ from"node:dgram";import*as v$ from"node:fs/promises";import*as o$ from"node:path";import*as Bt from"node:process";import{spawn as s$}from"node:child_process";import*as Ei from"node:fs/promises";import{homedir as L$}from"node:os";import*as vi from"node:path";import*as U from"node:process";var a={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as ul}from"node:child_process";import Z from"node:fs/promises";import*as hl from"node:os";import{homedir as Tr}from"node:os";import*as zh from"node:path";import{join as D}from"node:path";import*as Vi from"node:process";import{createRequire as u1}from"node:module";import{Resolver as y0}from"node:dns/promises";import{createHash as $1,sign as A1}from"node:crypto";import{createHash as T1}from"node:crypto";import{sign as E1}from"node:crypto";import{generateKeyPairSync as lw,X509Certificate as N1}from"node:crypto";import w0 from"node:os";import u0 from"node:path";import{existsSync as ry,statSync as ny}from"fs";import{existsSync as X1,mkdirSync as Pm,readdirSync as Zm,readFileSync as S1,writeFileSync as vm}from"fs";import{homedir as qt}from"os";import{dirname as iC,resolve as Ii}from"path";import dn from"process";import{existsSync as fy,statSync as cy}from"fs";import{existsSync as z0,mkdirSync as a1,readdirSync as J1,writeFileSync as F1}from"fs";import{homedir as gt}from"os";import{dirname as ly,resolve as Bi}from"path";import Kt from"process";import{join as K1,relative as I1,resolve as yy}from"path";import Fn from"process";import{existsSync as yw,mkdirSync as hC,readdirSync as $C,writeFileSync as AC}from"fs";import{homedir as h0}from"os";import{dirname as YC,resolve as Yi}from"path";import ar from"process";import{join as _1,relative as z1,resolve as wy}from"path";import Kn from"process";import{existsSync as ww,mkdirSync as UC,readdirSync as jC,writeFileSync as RC}from"fs";import{dirname as WC,resolve as In}from"path";import Q0 from"process";import{Buffer as mt}from"buffer";import{createCipheriv as Q1,createDecipheriv as M1,randomBytes as $0}from"crypto";import{closeSync as A0,createReadStream as uy,createWriteStream as O1,existsSync as T0,fsyncSync as hy,openSync as $y,writeFileSync as G1}from"fs";import{access as H1,constants as Ay,mkdir as q1,readdir as ln,rename as Ty,stat as st,unlink as yn,writeFile as E0}from"fs/promises";import{join as Lt}from"path";import wi from"process";import{pipeline as g1}from"stream/promises";import{createGzip as Ey}from"zlib";import xt from"process";import rt from"process";import{Buffer as pi}from"buffer";import{createCipheriv as s1,createDecipheriv as L1,randomBytes as Y0}from"crypto";import{closeSync as B0,createReadStream as Yy,createWriteStream as x1,existsSync as wn,fsyncSync as By,openSync as ey,writeFileSync as k1}from"fs";import{access as V1,constants as my,mkdir as d1,readdir as un,rename as Cy,stat as kt,unlink as hn,writeFile as e0}from"fs/promises";import{isAbsolute as D1,join as Vt,resolve as b1}from"path";import H from"process";import{pipeline as P1}from"stream/promises";import{createGzip as Uy}from"zlib";import dt from"process";import nt from"process";import $n from"process";import{existsSync as An}from"fs";import{resolve as m0}from"path";import{existsSync as Z1}from"fs";import{existsSync as v1,readdirSync as o1}from"fs";import{extname as C0,resolve as jy}from"path";import p1 from"process";import{join as iA,relative as tA,resolve as Ry}from"path";import _n from"process";import{Buffer as it}from"buffer";import{createCipheriv as rA,createDecipheriv as nA,randomBytes as U0}from"crypto";import{closeSync as j0,createReadStream as Ny,createWriteStream as fA,existsSync as Tn,fsyncSync as Wy,openSync as Xy,writeFileSync as cA}from"fs";import{access as lA,constants as Sy,mkdir as yA,readdir as En,rename as ay,stat as Dt,unlink as Yn,writeFile as R0}from"fs/promises";import{isAbsolute as wA,join as bt,resolve as uA}from"path";import q from"process";import{pipeline as hA}from"stream/promises";import{createGzip as Jy}from"zlib";import Pt from"process";import ft from"process";import Bn from"process";import{existsSync as en}from"fs";import{resolve as N0}from"path";import{existsSync as $A}from"fs";import{exec as zT}from"node:child_process";import V0 from"node:fs";import QT from"node:os";import Hi from"node:path";import kw from"node:process";import{promisify as MT}from"node:util";import pt from"node:crypto";import ct from"node:fs";import b0 from"node:path";import fE from"node:crypto";import cE from"node:fs";import lE from"node:tls";import{execSync as uE}from"node:child_process";import kn from"node:os";var h1=u1(import.meta.url),dy=30000;async function Un(i,t={},r=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(r)})}catch(n){if(n&&typeof n==="object"&&n.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${r}ms`);throw f.name="AcmeRequestTimeoutError",f}throw n}}async function Dy(i,t,r={}){let n=r.timeoutMs??120000,f=r.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new y0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new y0,l.setServers($)}catch{}let y=Date.now()+n,w=l??new y0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Sr{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Sr.PATH_PREFIX);if(t===-1)return;let r=i.slice(t+Sr.PATH_PREFIX.length);return this.get(r)}}var Vn=new Sr;function jn(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function F0(i){return Buffer.from(i,"base64url")}function by(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Py(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return $1("sha256").update(t).digest("base64url")}function Zy(i){let{protectedHeader:t,payload:r,privateKey:n}=i,f=jn(JSON.stringify(t)),c=r===""?"":jn(JSON.stringify(r)),l=`${f}.${c}`,y=A1("sha256",Buffer.from(l),{key:n,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:jn(y)}}var vy="https://acme-staging-v02.api.letsencrypt.org/directory",oy="https://acme-v02.api.letsencrypt.org/directory";class an extends Error{problem;httpStatus;constructor(i,t,r){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class Jn{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=by(i.accountPublicKey),this.thumbprint=Py(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??dy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await Un(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 Un(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:r,useJwk:n}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)f.jwk=this.jwk;else f.kid=this.requireKid();let c=Zy({protectedHeader:f,payload:r,privateKey:this.accountKey}),l=await Un(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 an(`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(),r={termsOfServiceAgreed:!0};if(i.email)r.contact=[`mailto:${i.email}`];let n=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(i){let t=await this.directory(),r={identifiers:i.map((f)=>({type:"dns",value:f}))},n=await this.signedPost({url:t.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return T1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let 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 an(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ty(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;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 ty(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let r=i.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return r}}function py(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${i.trim()}
|
|
2
2
|
`,chainPem:""};let n=`${r.trim()}
|
|
3
3
|
`,f=t.slice(1).map((c)=>c.trim()).join(`
|
|
4
4
|
`);return{certPem:n,chainPem:f?`${f}
|
|
5
|
-
`:""}}function oy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function pl(i){return new Promise((t)=>setTimeout(t,i))}function T1(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Ut(i,t){return Buffer.concat([Buffer.from([i]),T1(t.length),t])}function py(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=[],n=i;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ut(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let f=t[n],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);r.push(...c)}return Ut(6,Buffer.from(r))}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 iw(i){return Ut(4,i)}function tw(i){return Ut(12,Buffer.from(i,"utf8"))}function K0(i,t,r){let n=128|(r?32:0)|i;return Ut(n,t)}var E1="1.2.840.10045.2.1",Y1="1.2.840.10045.3.1.7",B1="1.2.840.10045.4.3.2",e1="2.5.4.3",m1="1.2.840.113549.1.9.14",C1="2.5.29.17";function U1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=J0(t.x),n=J0(t.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function rw(i){let{domains:t,publicKey:r,privateKey:n}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(F0(ai(Kt(e1),tw(t[0])))),c=ai(ai(Kt(E1),Kt(Y1)),I0(U1(r))),l=t.map((E)=>K0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(C1),iw(y)),u=ai(w),h=ai(Kt(m1),F0(u)),$=K0(0,h,!0),A=ai(py(0),f,c,$),T=A1("sha256",A,n),e=ai(Kt(B1));return ai(A,e,I0(T))}function nw(i){return rw(i).toString("base64url")}function R1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=w1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:r}=fw("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function b0(i){let{domains:t,method:r}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=i.directoryUrl??(i.staging===!1?Zy:Py),f=R1(i.accountKeyPem),c=new an({directoryUrl:n,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??kn,u=[],h=[];try{for(let F of l.authorizations){let a=await c.getAuthorization(F);if(a.status==="valid")continue;let J=an.selectChallenge(a,r);if(r==="dns-01"){let v=oy(a.identifier.value),Mi=c.dns01TxtValue(J.token);await i.dnsProvider.setTxt(v,Mi),u.push({name:v,value:Mi}),await Vy(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}=fw("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:m}=vy(E),j=m?`${B}${m}`:B,W=$.export({format:"pem",type:"pkcs8"}).toString(),X=new Date(new j1(B).validTo);return{certPem:B,keyPem:W,chainPem:m,fullChainPem:j,accountKeyPem:f.pem,notAfter:X}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class yw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!iy(i))return!0;return ty(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=iy(r)?ty(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ww{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _n=new yw,P0=new ww,hA=Object.defineProperty,$A=(i)=>i;function AA(i,t){this[i]=$A.bind(null,t)}var TA=(i,t)=>{for(var r in t)hA(i,r,{get:t[r],enumerable:!0,configurable:!0,set:AA.bind(t,r)})},EA=(i,t)=>()=>(i&&(t=i(i=0)),t),uw={};TA(uw,{withErrorRecovery:()=>Aw,tryLoadConfig:()=>GA,loadConfigWithResult:()=>MA,loadConfig:()=>ew,isRetryableError:()=>FA,isConfigNotFoundError:()=>JA,isBunfigError:()=>Tw,globalPerformanceMonitor:()=>zr,globalCache:()=>tr,getEnvOrDefault:()=>IA,generateConfigTypes:()=>HA,defaultGeneratedDir:()=>Xw,defaultConfigDir:()=>Ww,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>Ew,createLibraryConfig:()=>qA,config:()=>OA,bunfigPlugin:()=>sA,applyEnvVarsToConfig:()=>Sr,TypeGenerationError:()=>s0,SchemaValidationError:()=>Kr,PluginError:()=>L0,PerformanceMonitor:()=>v0,FileSystemError:()=>q0,ErrorFactory:()=>Ct,EnvVarError:()=>Hn,EnvProcessor:()=>dn,ConfigValidator:()=>tc,ConfigValidationError:()=>G0,ConfigNotFoundError:()=>Gn,ConfigMergeError:()=>H0,ConfigLoader:()=>rc,ConfigLoadError:()=>Ir,ConfigFileLoader:()=>Dn,ConfigCache:()=>Z0,CacheUtils:()=>Cw,BunfigError:()=>Ni,BrowserConfigError:()=>g0,ArrayMergeStrategies:()=>Rw});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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!ry(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=ry(r)?ny(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class v0{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function YA(i,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${i}:${r}`:i}function BA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function eA(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 n=[...t];for(let f of i)if(V(f)&&"name"in f){if(!n.find((c)=>V(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(V(f)&&"path"in f){if(!n.find((c)=>V(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((c)=>zn(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!V(t)||!V(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(V(f)&&V(r[n]))r[n]=o0(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&V(f[0])&&V(r[n][0])){let c=[...f];for(let l of r[n])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)=>zn(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function zn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!zn(i[r],t[r]))return!1;return!0}if(V(i)&&V(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zn(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function mA(i,t){if(!lw(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return o0(t,n)}catch{return null}}catch{return null}}async function CA({name:i="",cwd:t,defaultConfig:r}){let n=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=In(n,`${l}${y}`),u=await mA(w,r);if(u!==null)return u}try{let l=In(n,"package.json");if(lw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(r,y)}catch{}}}catch{}return r}function UA(i,t={}){let r=Fn.cwd();while(r.includes("storage"))r=ly(r,"..");let n=ly(r,i||"");if(t?.relative)return K1(Fn.cwd(),n);return n}async function jA(){try{let i=await CA({name:"clarity",defaultConfig:Rn,cwd:Fn.cwd(),endpoint:"",headers:{}});return{...Rn,...i}}catch{return Rn}}function b(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function RA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class hw{async format(i){let t=await RA(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qn{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 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??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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{...Nn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Nn};return{...Nn,...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},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let t=(async()=>{let n,f=0,c=3,l=1000;while(f<c)try{try{try{await O1(this.config.logDirectory,hy.F_OK|hy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await G1(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(n=uy(this.currentLogFile,"a",420),M1(n,y,{flag:"a"}),wy(n),n!==void 0)$0(n),n=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(n!==void 0)try{$0(n)}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 r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(n.length>c)for(let[l]of n.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(),r=h0(16),n=_1("aes-256-gcm",t,r),f=et.concat([n.update(i,"utf8"),n.final()]),c=n.getAuthTag();return{encrypted:et.concat([r,f,c]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Ay(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(et.from(et.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cn(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=`${r}.${l}`;if(await Vt(r).catch(()=>null))try{if(await $y(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await ln(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.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=r.replace(/\.log$/,`-${f}.log`);if(await Vt(r).catch(()=>null))await $y(r,c)}if(this.currentLogFile=n,t.maxFiles){let f=(await cn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await ln(dt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=yy(i),n=Q1(t),f=Ay();await H1(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),A0(this.currentLogFile))try{let i=uy(this.currentLogFile,"r+");wy(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 cn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await ln(dt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);if(this.fancy&&!b()){let u=Uw[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 iw(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function ty(i){return new Promise((t)=>setTimeout(t,i))}function Y1(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function jt(i,t){return Buffer.concat([Buffer.from([i]),Y1(t.length),t])}function tw(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=[],n=i;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return jt(2,t)}function Ft(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let f=t[n],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);r.push(...c)}return jt(6,Buffer.from(r))}function Ki(...i){return jt(48,Buffer.concat(i))}function K0(...i){return jt(49,Buffer.concat(i))}function I0(i){return jt(3,Buffer.concat([Buffer.from([0]),i]))}function rw(i){return jt(4,i)}function nw(i){return jt(12,Buffer.from(i,"utf8"))}function _0(i,t,r){let n=128|(r?32:0)|i;return jt(n,t)}var B1="1.2.840.10045.2.1",e1="1.2.840.10045.3.1.7",m1="1.2.840.10045.4.3.2",C1="2.5.4.3",U1="1.2.840.113549.1.9.14",j1="2.5.29.17";function R1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=F0(t.x),n=F0(t.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function fw(i){let{domains:t,publicKey:r,privateKey:n}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Ki(K0(Ki(Ft(C1),nw(t[0])))),c=Ki(Ki(Ft(B1),Ft(e1)),I0(R1(r))),l=t.map((E)=>_0(2,Buffer.from(E,"ascii"),!1)),y=Ki(...l),w=Ki(Ft(j1),rw(y)),u=Ki(w),h=Ki(Ft(U1),K0(u)),$=_0(0,h,!0),A=Ki(tw(0),f,c,$),T=E1("sha256",A,n),e=Ki(Ft(m1));return Ki(A,e,I0(T))}function cw(i){return fw(i).toString("base64url")}function W1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=h1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:r}=lw("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function P0(i){let{domains:t,method:r}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=i.directoryUrl??(i.staging===!1?oy:vy),f=W1(i.accountKeyPem),c=new Jn({directoryUrl:n,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??Vn,u=[],h=[];try{for(let F of l.authorizations){let I=await c.getAuthorization(F);if(I.status==="valid")continue;let N=Jn.selectChallenge(I,r);if(r==="dns-01"){let li=iw(I.identifier.value),yi=c.dns01TxtValue(N.token);await i.dnsProvider.setTxt(li,yi),u.push({name:li,value:yi}),await Dy(li,yi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(N.token,c.keyAuthorization(N.token)),h.push(N.token);await c.notifyChallengeReady(N.url),await c.pollAuthorization(F,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=lw("ec",{namedCurve:"P-256"}),T=cw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let e=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(e),{certPem:B,chainPem:m}=py(E),j=m?`${B}${m}`:B,W=$.export({format:"pem",type:"pkcs8"}).toString(),S=new Date(new N1(B).validTo);return{certPem:B,keyPem:W,chainPem:m,fullChainPem:j,accountKeyPem:f.pem,notAfter:S}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class uw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!ry(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=ry(r)?ny(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class hw{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var zn=new uw,Z0=new hw,AA=Object.defineProperty,TA=(i)=>i;function EA(i,t){this[i]=TA.bind(null,t)}var YA=(i,t)=>{for(var r in t)AA(i,r,{get:t[r],enumerable:!0,configurable:!0,set:EA.bind(t,r)})},BA=(i,t)=>()=>(i&&(t=i(i=0)),t),$w={};YA($w,{withErrorRecovery:()=>Ew,tryLoadConfig:()=>qA,loadConfigWithResult:()=>GA,loadConfig:()=>Cw,isRetryableError:()=>IA,isConfigNotFoundError:()=>KA,isBunfigError:()=>Yw,globalPerformanceMonitor:()=>Ir,globalCache:()=>vt,getEnvOrDefault:()=>_A,generateConfigTypes:()=>gA,defaultGeneratedDir:()=>aw,defaultConfigDir:()=>Sw,deepMergeWithArrayStrategy:()=>tc,deepMerge:()=>Bw,createLibraryConfig:()=>sA,config:()=>HA,bunfigPlugin:()=>LA,applyEnvVarsToConfig:()=>Wr,TypeGenerationError:()=>s0,SchemaValidationError:()=>Fr,PluginError:()=>x0,PerformanceMonitor:()=>o0,FileSystemError:()=>g0,ErrorFactory:()=>Ut,EnvVarError:()=>qn,EnvProcessor:()=>Dn,ConfigValidator:()=>rc,ConfigValidationError:()=>H0,ConfigNotFoundError:()=>Hn,ConfigMergeError:()=>q0,ConfigLoader:()=>nc,ConfigLoadError:()=>Jr,ConfigFileLoader:()=>bn,ConfigCache:()=>v0,CacheUtils:()=>jw,BunfigError:()=>Xi,BrowserConfigError:()=>L0,ArrayMergeStrategies:()=>Ww});class v0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!fy(i))return!0;return cy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=fy(r)?cy(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class o0{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function eA(i,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${i}:${r}`:i}function mA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function CA(i){return i.getStats().size*2}function p0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let n=[...t];for(let f of i)if(V(f)&&"name"in f){if(!n.find((c)=>V(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(V(f)&&"path"in f){if(!n.find((c)=>V(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((c)=>Qn(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!V(t)||!V(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(V(f)&&V(r[n]))r[n]=p0(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&V(f[0])&&V(r[n][0])){let c=[...f];for(let l of r[n])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)=>Qn(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function Qn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Qn(i[r],t[r]))return!1;return!0}if(V(i)&&V(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Qn(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function UA(i,t){if(!ww(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return p0(t,n)}catch{return null}}catch{return null}}async function jA({name:i="",cwd:t,defaultConfig:r}){let n=t||Q0.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=In(n,`${l}${y}`),u=await UA(w,r);if(u!==null)return u}try{let l=In(n,"package.json");if(ww(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return p0(r,y)}catch{}}}catch{}return r}function RA(i,t={}){let r=Kn.cwd();while(r.includes("storage"))r=wy(r,"..");let n=wy(r,i||"");if(t?.relative)return z1(Kn.cwd(),n);return n}async function NA(){try{let i=await jA({name:"clarity",defaultConfig:Nn,cwd:Kn.cwd(),endpoint:"",headers:{}});return{...Nn,...i}}catch{return Nn}}function b(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function WA(){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 Aw{async format(i){let t=await WA(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:xt.pid,hostname:t(),environment:xt.env.NODE_ENV||"development",platform:xt.platform,version:xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xt.env.NODE_ENV||xt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mn{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={...O0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Aw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??wi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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{...Wn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Wn};return{...Wn,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:O0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let t=(async()=>{let n,f=0,c=3,l=1000;while(f<c)try{try{try{await H1(this.config.logDirectory,Ay.F_OK|Ay.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await q1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:mt.from(i);try{if(!T0(this.currentLogFile))await E0(this.currentLogFile,"",{mode:420});if(n=$y(this.currentLogFile,"a",420),G1(n,y,{flag:"a"}),hy(n),n!==void 0)A0(n),n=void 0;if((await st(this.currentLogFile)).size===0){if(await E0(this.currentLogFile,y,{flag:"w",mode:420}),(await st(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(n!==void 0)try{A0(n)}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 r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Lt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Lt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Lt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return $0(16).toString("hex")}generateKey(){return $0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=$0(16),n=Q1("aes-256-gcm",t,r),f=mt.concat([n.update(i,"utf8"),n.final()]),c=n.getAuthTag();return{encrypted:mt.concat([r,f,c]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Ey(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(mt.from(mt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await st(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ln(this.config.logDirectory),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=`${r}.${l}`;if(await st(r).catch(()=>null))try{if(await Ty(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await yn(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await E0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=r.replace(/\.log$/,`-${f}.log`);if(await st(r).catch(()=>null))await Ty(r,c)}if(this.currentLogFile=n,t.maxFiles){let f=(await ln(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await yn(Lt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=uy(i),n=O1(t),f=Ey();await g1(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),T0(this.currentLogFile))try{let i=$y(this.currentLogFile,"r+");hy(i),A0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await ln(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await yn(Lt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=wi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);if(this.fancy&&!b()){let u=Rw[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 r=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:x.blue("◐"),tag:r,message:`${x.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(r)w+=` ${JSON.stringify(r)}`;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}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new Mn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!T0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=mt.isBuffer(i)?i:mt.from(i,"base64"),f=n.slice(0,16),c=n.slice(-16),l=n.slice(16,-16),y=M1("aes-256-gcm",r,f);return y.setAuthTag(c),mt.concat([y.update(l),y.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=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:r,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(w),showTimestamp:!1}))}else if(!b())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(b())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,n)),f!==void 0)this.activeProgressBar.message=f;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;
|
|
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 cn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=dt(this.config.logDirectory,n);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}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ln(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jn(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&s(t[0])&&"id"in t[0]&&t[0].id===3&&s(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(s(t)&&s(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(s(i)&&"arr"in i&&Array.isArray(i.arr)&&s(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&s(t[0])&&s(i[0])){let n=[...t];for(let f of i)if(s(f)&&"name"in f){if(!n.find((c)=>s(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(s(f)&&"path"in f){if(!n.find((c)=>s(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((c)=>Mn(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!s(t)||!s(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(s(f)&&s(r[n]))r[n]=jn(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&s(f[0])&&s(r[n][0])){let c=[...f];for(let l of r[n])if(s(l)&&"name"in l){if(!c.find((y)=>s(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(s(l)&&"path"in l){if(!c.find((y)=>s(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Mn(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function p0(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:jn(i,t);if(Array.isArray(i))return r==="replace"?t:jn(i,t);if(!s(t)||!s(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=n[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(r==="replace")n[f]=c;else n[f]=jn(l,c);else if(s(c)&&s(l))n[f]=p0(l,c,r);else n[f]=c}return n}function Mn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Mn(i[r],t[r]))return!1;return!0}if(s(i)&&s(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Mn(i[f],t[f]))return!1}return!0}return!1}function s(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function en(i,t,r="replace"){if(!cw(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return p0(t,f,r)}catch{return null}}catch{return null}}function NA(i,t,r=!1){if(!i)return t;let n=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=`${n}_${$.map(A).join("_")}`,e=`${n}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(r)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=Fr.env[T]||Fr.env[e];if(E!==void 0){if(r)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((m)=>m.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function WA({name:i="",alias:t,cwd:r,configDir:n,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=r||Fr.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"),n?Ei(u,n):void 0].filter(Boolean)));for(let B of E){if(c)ui.info(`Searching for configuration in: ${B}`);let m=[Ei(u,"config"),Ei(u,".config")].concat(n?[Ei(u,n)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let j of m)for(let W of h){let X=Ei(B,`${j}${W}`),F=await en(X,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from: ${X}`);return F}}}if(i){let B=Ei(u0(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${B}`);for(let j of m)for(let W of h){let X=Ei(B,`${j}${W}`),F=await en(X,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory: ${X}`);return F}}}if(i){let B=Ei(u0(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let X=Ei(B,`${j}${W}`),F=await en(X,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${X}`);return F}}}if(i){let B=u0(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(c)ui.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let X=Ei(B,`${j}${W}`),F=await en(X,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user home directory: ${X}`);return F}}}try{let B=Ei(u,"package.json");if(cw(B)){let m=await import(B),j=m[i];if(!j&&t){if(j=m[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===m[i]?i:t}`);return p0(w,j,y)}catch(W){if(c)ui.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)ui.warn("Failed to load package.json:",B)}if(c)ui.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function XA(i,t={}){let r=Jn.cwd();while(r.includes("storage"))r=cy(r,"..");let n=cy(r,i||"");if(t?.relative)return F1(Jn.cwd(),n);return n}async function SA(){try{let i=await WA({name:"clarity",alias:"logging",defaultConfig:Wn,cwd:Jn.cwd()});return{...Wn,...i||{}}}catch{return Wn}}function p(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function aA(){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 $w{async format(i){let t=await aA(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid: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 On{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 $w,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Xn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Xn};return{...Xn,...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},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,c=3,l=1000;while(f<c)try{try{try{await x1(this.config.logDirectory,By.F_OK|By.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await k1(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(!yn(this.currentLogFile))await B0(this.currentLogFile,"",{mode:420});if(n=Yy(this.currentLogFile,"a",420),L1(n,y,{flag:"a"}),Ey(n),n!==void 0)Y0(n),n=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(n!==void 0)try{Y0(n)}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 r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(n.length>c)for(let[l]of n.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(),r=E0(16),n=q1("aes-256-gcm",t,r),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=oi.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=my(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(oi.from(oi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wn(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=`${r}.${l}`;if(await bt(r).catch(()=>null))try{if(await ey(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await un(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.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=r.replace(/\.log$/,`-${f}.log`);if(await bt(r).catch(()=>null))await ey(r,c)}if(this.currentLogFile=n,t.maxFiles){let f=(await wn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await un(Pt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=Ty(i),n=g1(t),f=my();await D1(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),yn(this.currentLogFile))try{let i=Yy(this.currentLogFile,"r+");Ey(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 wn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await un(Pt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?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:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=H.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=Q.underline(Q.blue(n)),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,(r,n)=>Q.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>Q.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>Q.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>Q.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>Q.strikethrough(n)),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 r=H.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(V1(t)||t.startsWith("./")||t.startsWith("../"))t=d1(t);else return null;return yn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":jw[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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:Q.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!
|
|
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 r=(n)=>{let f=n.toString().trim().toLowerCase();wi.stdin.removeListener("data",r);try{if(typeof wi.stdin.setRawMode==="function")wi.stdin.setRawMode(!1)}catch{}wi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof wi.stdin.setRawMode==="function")wi.stdin.setRawMode(!0)}catch{}wi.stdin.resume(),wi.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,c=0;if(r=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)r+=` ${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(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
12
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(i,t=""){if(!this.enabled||!this.fancy||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 r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,n)),f!==void 0)this.activeProgressBar.message=f;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;wi.stdout.write(`${"\r".padEnd(wi.stdout.columns||80)}\r`),this.log(f,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!wi.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,c=x.green("━".repeat(n)),l=x.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${r}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||r===100?x.green("✓"):x.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=wi.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,wi.stdout.write(i.lastRenderedLine),t)wi.stdout.write(`
|
|
13
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!wi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ln(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Lt(this.config.logDirectory,n);if(i.before)try{if((await st(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await yn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Rn(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let n=[...t];for(let f of i)if(g(f)&&"name"in f){if(!n.find((c)=>g(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(g(f)&&"path"in f){if(!n.find((c)=>g(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((c)=>On(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!g(t)||!g(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(g(f)&&g(r[n]))r[n]=Rn(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&g(f[0])&&g(r[n][0])){let c=[...f];for(let l of r[n])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)=>On(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function ic(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:Rn(i,t);if(Array.isArray(i))return r==="replace"?t:Rn(i,t);if(!g(t)||!g(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=n[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(r==="replace")n[f]=c;else n[f]=Rn(l,c);else if(g(c)&&g(l))n[f]=ic(l,c,r);else n[f]=c}return n}function On(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!On(i[r],t[r]))return!1;return!0}if(g(i)&&g(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!On(i[f],t[f]))return!1}return!0}return!1}function g(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function mn(i,t,r="replace"){if(!yw(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return ic(t,f,r)}catch{return null}}catch{return null}}function XA(i,t,r=!1){if(!i)return t;let n=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=`${n}_${$.map(A).join("_")}`,e=`${n}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(r)hi.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let E=ar.env[T]||ar.env[e];if(E!==void 0){if(r)hi.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((m)=>m.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function SA({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?XA(i,f,c):f,u=r||ar.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)hi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],e=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Yi(u,"config"),Yi(u,".config"),n?Yi(u,n):void 0].filter(Boolean)));for(let B of E){if(c)hi.info(`Searching for configuration in: ${B}`);let m=[Yi(u,"config"),Yi(u,".config")].concat(n?[Yi(u,n)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let j of m)for(let W of h){let S=Yi(B,`${j}${W}`),F=await mn(S,w,y);if(F!==null){if(c)hi.success(`Configuration loaded from: ${S}`);return F}}}if(i){let B=Yi(h0(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(c)hi.info(`Checking user config directory: ${B}`);for(let j of m)for(let W of h){let S=Yi(B,`${j}${W}`),F=await mn(S,w,y);if(F!==null){if(c)hi.success(`Configuration loaded from user config directory: ${S}`);return F}}}if(i){let B=Yi(h0(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(c)hi.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let S=Yi(B,`${j}${W}`),F=await mn(S,w,y);if(F!==null){if(c)hi.success(`Configuration loaded from user config directory dotfile: ${S}`);return F}}}if(i){let B=h0(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(c)hi.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let S=Yi(B,`${j}${W}`),F=await mn(S,w,y);if(F!==null){if(c)hi.success(`Configuration loaded from user home directory: ${S}`);return F}}}try{let B=Yi(u,"package.json");if(yw(B)){let m=await import(B),j=m[i];if(!j&&t){if(j=m[t],j&&c)hi.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)hi.success(`Configuration loaded from package.json: ${j===m[i]?i:t}`);return ic(w,j,y)}catch(W){if(c)hi.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)hi.warn("Failed to load package.json:",B)}if(c)hi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function aA(i,t={}){let r=Fn.cwd();while(r.includes("storage"))r=yy(r,"..");let n=yy(r,i||"");if(t?.relative)return I1(Fn.cwd(),n);return n}async function JA(){try{let i=await SA({name:"clarity",alias:"logging",defaultConfig:Xn,cwd:Fn.cwd()});return{...Xn,...i||{}}}catch{return Xn}}function o(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function FA(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nt<"u"){let i=nt.type;if(i==="renderer"||i==="worker")return!1;return!!(nt.versions&&(nt.versions.node||nt.versions.bun))}return!1}class Tw{async format(i){let t=await FA(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:dt.pid,hostname:t(),environment:dt.env.NODE_ENV||"development",platform:dt.platform,version:dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dt.env.NODE_ENV||dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gn{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={...G0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Tw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Sn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Sn};return{...Sn,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:G0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!o()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,c=3,l=1000;while(f<c)try{try{try{await V1(this.config.logDirectory,my.F_OK|my.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await d1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:pi.from(i);try{if(!wn(this.currentLogFile))await e0(this.currentLogFile,"",{mode:420});if(n=ey(this.currentLogFile,"a",420),k1(n,y,{flag:"a"}),By(n),n!==void 0)B0(n),n=void 0;if((await kt(this.currentLogFile)).size===0){if(await e0(this.currentLogFile,y,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{B0(n)}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 r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(o())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Y0(16).toString("hex")}generateKey(){return Y0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Y0(16),n=s1("aes-256-gcm",t,r),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=pi.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Uy(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(pi.from(pi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(o())return;if(!this.shouldWriteToFile())return;let i=await kt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await un(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=`${r}.${l}`;if(await kt(r).catch(()=>null))try{if(await Cy(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await hn(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await e0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=r.replace(/\.log$/,`-${f}.log`);if(await kt(r).catch(()=>null))await Cy(r,c)}if(this.currentLogFile=n,t.maxFiles){let f=(await un(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await hn(Vt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=Yy(i),n=x1(t),f=Uy();await P1(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),wn(this.currentLogFile))try{let i=ey(this.currentLogFile,"r+");By(i),B0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await un(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await hn(Vt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?Q.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||o())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level: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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=H.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=Q.underline(Q.blue(n)),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,(r,n)=>Q.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>Q.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>Q.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>Q.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>Q.strikethrough(n)),t}supportsHyperlinks(){if(o())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=H.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(D1(t)||t.startsWith("./")||t.startsWith("../"))t=b1(t);else return null;return wn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Nw[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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:Q.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!o()){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
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
17
|
-
`);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!
|
|
19
|
-
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:Q.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:Q.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:Q.cyan(h),showTimestamp:!1}))}else if(!
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(
|
|
16
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!o()&&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()&&!o()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,c="info")=>{if(!o()&&H.stdout.isTTY)H.stdout.write(`
|
|
17
|
+
`);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!o()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":Q.blue("◐"),tag:r,message:`${Q.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(r)w+=` ${JSON.stringify(r)}`;if(w+=`
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!o())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}`,r=new Gn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(o())throw Error("createReadStream is not supported in browser environments");if(!wn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Yy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=pi.isBuffer(i)?i:pi.from(i,"base64"),f=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=L1("aes-256-gcm",r,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(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return o()}isServerMode(){return!o()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
19
|
+
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:Q.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:Q.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:Q.cyan(h),showTimestamp:!1}))}else if(!o())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(o())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Q.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();H.stdin.removeListener("data",r);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(r=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)r+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);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(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
21
21
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,c=Q.green("━".repeat(n)),l=Q.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${r}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===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,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
|
|
22
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||
|
|
22
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||o()||!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(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await un(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,n);if(i.before)try{if((await kt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await hn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ew(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=r;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===r||!f(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Yw(i){return i instanceof Xi}function KA(i){return i instanceof Hn}function IA(i){if(Yw(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class Dn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=r,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Ir.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,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${y.join("_")}`,u=n.useBackwardCompatibility?`${r}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,r,n);else{let h=$n.env[w]||(u?$n.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=$n.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof qn)throw $;throw Ut.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Ut.envVar(r,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries($n.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,c=n||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,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${r}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,r,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
23
23
|
|
|
24
24
|
`;for(let n of i)r+=`${n.key}
|
|
25
25
|
`,r+=` Type: ${n.type}
|
|
@@ -31,25 +31,25 @@ import{Ab as g,Bb as ql,Cb as K$,Eb as Nt,Fb as Y,Gb as H$,Kb as Jh,Lb as hl,Nb
|
|
|
31
31
|
`;r+=`| Variable | Type | Description | Example |
|
|
32
32
|
`,r+=`|----------|------|-------------|----------|
|
|
33
33
|
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
34
|
-
`;return r}}function IA(i,t){let r=mw("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function Ew(i,t,r={}){return Yw(i,t,r,new WeakMap)}function Yw(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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 Bw(i,t,f,n);if(!Fi(t)||!Fi(i))return t;return QA(i,t,r,n)}function Bw(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return KA(i,t);case"smart":return _A(i,t,n);default:return t}return t}function KA(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Q0(f,n)))r.push(n);return r}function _A(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Fi(t[0])&&Fi(i[0]))return zA(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function zA(i,t,r){let n=[...t];for(let f of i){if(!Fi(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((w)=>Fi(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function QA(i,t,r,n){let f=t;if(Fi(f)&&n.has(f))return n.get(f);let c={...i};if(Fi(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Fi(y)&&Fi(w))c[l]=Yw(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=Bw(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function ic(i,t,r="replace"){return Ew(i,t,{arrayMergeMode:r==="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 r=0;r<i.length;r++)if(!Q0(i[r],t[r]))return!1;return!0}if(Fi(i)&&Fi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Q0(i[f],t[f]))return!1}return!0}return!1}function Fi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Dn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;if(f){let u=tr.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$n(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 Ir(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Ir(i,Error("Configuration must export a valid object"),"unknown");let e={config:ic(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)tr.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?Ct.configLoad(i,u):Ct.configLoad(i,Error(String(u)))}};if(l)return zr.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(e0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return Aw(async()=>{return $n(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!$n(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=e0(i,`${c}${l}`);if(await this.checkFileAccess(y))n.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))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!$n(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class tc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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 zr.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,r){try{if(!b1(t))throw new Kr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Kr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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 rc{fileLoader=new Dn;envProcessor=new dn;validator=new tc;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)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,r){let{name:n="",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(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Yi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw Ct.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?Sr(i,f,l):f,h=this.getLocalDirectories(r,n);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,r,n,f,c){if(!i)return null;let l=c?Sr(i,r,f):r,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:n,verbose:f});if(h){if(f)Gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?Sr(i,n,c):n;try{let w=Yi(r,"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,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Sr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Ct.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return tr.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);tr.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Yi(i,"config"),Yi(i,".config"),t?Yi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Yi(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Yi(kt(),".config",i),Yi(kt(),".config"),kt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function ay(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||r}async function MA(i){return ct.loadConfig({...i,__strictErrorHandling:!0})}async function ew(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await ct.loadConfig(i);else n=await ct.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",c=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)Gi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let l=r?{...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 OA(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(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ay(r)))return(await ct.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}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"&&ay(t)))return(await ct.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function GA(i,t,r="replace"){let n=new Dn;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Sr(i,t,r=!1){let n=new dn,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 HA(i){let t=Yi(_t.cwd(),i.configDir),r=Yi(_t.cwd(),i.generatedDir),n=Yi(r,"config-types.ts");if(!_0(fy(n)))X1(fy(n),{recursive:!0,mode:511});let f=_0(t)?S1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${TT}
|
|
34
|
+
`;return r}}function _A(i,t){let r=Uw("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function Bw(i,t,r={}){return ew(i,t,r,new WeakMap)}function ew(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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,n);if(!_i(t)||!_i(i))return t;return OA(i,t,r,n)}function mw(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return zA(i,t);case"smart":return QA(i,t,n);default:return t}return t}function zA(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>M0(f,n)))r.push(n);return r}function QA(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return MA(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function MA(i,t,r){let n=[...t];for(let f of i){if(!_i(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((w)=>_i(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function OA(i,t,r,n){let f=t;if(_i(f)&&n.has(f))return n.get(f);let c={...i};if(_i(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(_i(y)&&_i(w))c[l]=ew(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=mw(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function tc(i,t,r="replace"){return Bw(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function M0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!M0(i[r],t[r]))return!1;return!0}if(_i(i)&&_i(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!M0(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class bn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;if(f){let u=vt.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!An(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 Jr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Jr(i,Error("Configuration must export a valid object"),"unknown");let e={config:tc(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)vt.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?Ut.configLoad(i,u):Ut.configLoad(i,Error(String(u)))}};if(l)return Ir.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(m0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return Ew(async()=>{return An(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!An(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=m0(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=m0(i,l);if(await this.checkFileAccess(y))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!An(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class rc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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 Ir.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,r){try{if(!Z1(t))throw new Fr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Fr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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:Xw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class nc{fileLoader=new bn;envProcessor=new Dn;validator=new rc;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)qi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw qi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Kt.cwd(),A=[],T=await this.loadLocalConfiguration(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Bi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw Ut.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?Wr(i,f,l):f,h=this.getLocalDirectories(r,n);for(let $ of h){if(l)qi.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)qi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,r,n,f,c){if(!i)return null;let l=c?Wr(i,r,f):r,y=[Bi(gt(),".config",i),Bi(gt(),".config"),gt()];for(let w of y){if(f)qi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:f});if(h){if(f)qi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?Wr(i,n,c):n;try{let w=Bi(r,"package.json");if(!z0(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)qi.success(`Configuration loaded from package.json: ${$}`);return{config:tc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)qi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Wr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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 Ut.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return vt.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);vt.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Bi(i,"config"),Bi(i,".config"),t?Bi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Bi(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Bi(gt(),".config",i),Bi(gt(),".config"),gt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function Fy(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||r}async function GA(i){return lt.loadConfig({...i,__strictErrorHandling:!0})}async function Cw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await lt.loadConfig(i);else n=await lt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",c=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)qi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let l=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await lt.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function HA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await lt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Fy(r)))return(await lt.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await lt.loadConfig({...i,cwd:i.cwd||Kt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Fy(t)))return(await lt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function qA(i,t,r="replace"){let n=new bn;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Wr(i,t,r=!1){let n=new Dn,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=Kt.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=Bi(Kt.cwd(),i.configDir),r=Bi(Kt.cwd(),i.generatedDir),n=Bi(r,"config-types.ts");if(!z0(ly(n)))a1(ly(n),{recursive:!0,mode:511});let f=z0(t)?J1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${YT}
|
|
35
35
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
36
|
-
`;
|
|
37
|
-
${f.map((w)=>{let u=
|
|
36
|
+
`;F1(n,c,{mode:438})}function sA(i){let t=null,r=null,n=()=>{if(!r)r=Cw(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)qi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return n(),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 LA(i){let t=jy(p1.cwd(),i?.configDir||"./config");function r(){if(!v1(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=o1(t).filter((w)=>f.has(C0(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=C0(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=C0($).toLowerCase();if(c.indexOf(h)<c.indexOf(A))y.set(w,u)}return Array.from(y.entries()).map(([w,u])=>({base:w,file:u})).sort((w,u)=>w.base.localeCompare(u.base))}function n(){let f=r(),c=f.map((w)=>w.base),l=c.length?c.map((w)=>`'${w}'`).join(" | "):"string",y=f.length?`{
|
|
37
|
+
${f.map((w)=>{let u=jy(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:n(),loader:"ts"}})}}}var mw,tr,zr,Cw,gA,LA,Jy,Rn,M0,wi,x,xA,Fy,kA,Iy,VA,dA,N0,DA,Ky,_y,W0,bA,PA,ZA,vA,Nn,Uw,oA,ui,pA,iT,zy,Wn,O0,ii,Q,tT,Qy,rT,My,nT,fT,X0,cT,Oy,Gy,lT,S0,yT,wT,uT,hT,$T,Xn,jw,AT,TT="0.15.6",Ni,Gn,Ir,G0,H0,Hn,q0,s0,Kr,g0,L0,Ct,Rw,Nw,Gi,ct,Ww,Xw,ET=EA(async()=>{mw=import.meta.require,tr=new Z0,zr=new v0,Cw={createKey:YA,isEquivalent:BA,estimateMemoryUsage:eA},gA=In(z0.cwd(),"config"),LA=In(z0.cwd(),"src/generated"),Jy=Fn.env.CLARITY_LOG_DIR||I1(UA(),"logs"),Rn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Jy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},M0=await jA(),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,xA=wi.red,Fy=wi.green,kA=wi.yellow,Iy=wi.blue,VA=wi.magenta,dA=wi.cyan,N0=wi.white,DA=wi.gray,Ky=wi.bgRed,_y=wi.bgYellow,W0=wi.bold,bA=wi.dim,PA=wi.italic,ZA=wi.underline,vA=wi.reset,Nn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Uw={debug:"\uD83D\uDD0D",info:Iy("ℹ"),success:Fy("✓"),warning:_y(N0(W0(" WARN "))),error:Ky(N0(W0(" ERROR ")))},oA=new Qn("stacks"),ui=new Qn("bunfig",{showTags:!0}),pA=Ei(Fr.cwd(),"config"),iT=Ei(Fr.cwd(),"src/generated"),zy=Jn.env.CLARITY_LOG_DIR||J1(XA(),"logs"),Wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zy,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 SA(),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,tT=ii.red,Qy=ii.green,rT=ii.yellow,My=ii.blue,nT=ii.magenta,fT=ii.cyan,X0=ii.white,cT=ii.gray,Oy=ii.bgRed,Gy=ii.bgYellow,lT=ii.bgGray,S0=ii.bold,yT=ii.dim,wT=ii.italic,uT=ii.underline,hT=ii.strikethrough,$T=ii.reset,Xn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jw={debug:"\uD83D\uDD0D",info:My("ℹ"),success:Qy("✓"),warning:Gy(X0(S0(" WARN "))),error:Oy(X0(S0(" ERROR ")))},AT=new On("stacks"),Ni=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Gn=class extends Ni{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${i}"${n} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}},Ir=class extends Ni{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},G0=class extends Ni{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}},H0=class extends Ni{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Hn=class extends Ni{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}},q0=class extends Ni{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},s0=class extends Ni{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Kr=class extends Ni{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}},g0=class extends Ni{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}},L0=class extends Ni{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ct={configNotFound(i,t,r){return new Gn(i,t,r)},configLoad(i,t,r){return new Ir(i,t,r)},configValidation(i,t,r){return new G0(i,t,r)},configMerge(i,t,r,n){return new H0(i,t,r,n)},envVar(i,t,r,n){return new Hn(i,t,r,n)},fileSystem(i,t,r){return new q0(i,t,r)},typeGeneration(i,t,r){return new s0(i,t,r)},schemaValidation(i,t,r){return new Kr(i,t,r)},browserConfig(i,t,r,n){return new g0(i,t,r,n)},plugin(i,t,r){return new L0(i,t,r)}},Rw={replace:"replace",concat:"concat",smart:"smart"},Nw=/^https?:\/\//,Gi=new On("bunfig",{showTags:!0}),ct=new rc,Ww=Yi(_t.cwd(),"config"),Xw=Yi(_t.cwd(),"src/generated")});function YT(i,t={}){let r=Kn.cwd();while(r.includes("storage"))r=Uy(r,"..");let n=Uy(r,i||"");if(t?.relative)return p1(Kn.cwd(),n);return n}var BT=Kn.env.CLARITY_LOG_DIR||o1(YT(),"logs"),Sw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qn={...Sw},TU=(async()=>{try{let{loadConfig:i}=await ET().then(()=>uw),t=await i({name:"clarity",alias:"logging",defaultConfig:Sw,cwd:Kn.cwd()});if(t)Object.assign(qn,t)}catch{}return qn})();function ti(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eT(){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 aw{async format(i){let t=await eT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid: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,EU=ci.red,mT=ci.green,YU=ci.yellow,CT=ci.blue,BU=ci.magenta,eU=ci.cyan,Hy=ci.white,mU=ci.gray,UT=ci.bgRed,jT=ci.bgYellow,CU=ci.bgGray,qy=ci.bold,UU=ci.dim,jU=ci.italic,RU=ci.underline,NU=ci.strikethrough,WU=ci.reset,a0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RT={debug:"\uD83D\uDD0D",info:CT("ℹ"),success:mT("✓"),warning:jT(Hy(qy(" WARN "))),error:UT(Hy(qy(" ERROR ")))};class bn{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={...qn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new aw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}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:qn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,c=3,l=1000;while(f<c)try{try{try{await fA(this.config.logDirectory,Wy.F_OK|Wy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await cA(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(!An(this.currentLogFile))await j0(this.currentLogFile,"",{mode:420});if(n=Ny(this.currentLogFile,"a",420),nA(n,y,{flag:"a"}),Ry(n),n!==void 0)U0(n),n=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(n!==void 0)try{U0(n)}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 r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ot(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ot(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ot(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return C0(16).toString("hex")}generateKey(){return C0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=C0(16),n=iA("aes-256-gcm",t,r),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=pi.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Sy(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(pi.from(pi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await 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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Tn(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=`${r}.${l}`;if(await vt(r).catch(()=>null))try{if(await Xy(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await En(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.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=r.replace(/\.log$/,`-${f}.log`);if(await vt(r).catch(()=>null))await Xy(r,c)}if(this.currentLogFile=n,t.maxFiles){let f=(await Tn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await En(ot(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=jy(i),n=rA(t),f=Sy();await wA(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),An(this.currentLogFile))try{let i=Ny(this.currentLogFile,"r+");Ry(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 Tn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await En(ot(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||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:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=O.underline(O.blue(n)),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,(r,n)=>O.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>O.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>O.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>O.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>O.strikethrough(n)),t}supportsHyperlinks(){if(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 r=q.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(lA(t)||t.startsWith("./")||t.startsWith("../"))t=yA(t);else return null;return An(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":RT[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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!
|
|
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:n(),loader:"ts"}})}}}var Uw,vt,Ir,jw,xA,kA,Ky,Nn,O0,ui,x,VA,Iy,dA,_y,DA,bA,W0,PA,zy,Qy,X0,ZA,vA,oA,pA,Wn,Rw,iT,hi,tT,rT,My,Xn,G0,p,Q,nT,Oy,fT,Gy,cT,lT,S0,yT,Hy,qy,wT,a0,uT,hT,$T,AT,TT,Sn,Nw,ET,YT="0.15.6",Xi,Hn,Jr,H0,q0,qn,g0,s0,Fr,L0,x0,Ut,Ww,Xw,qi,lt,Sw,aw,BT=BA(async()=>{Uw=import.meta.require,vt=new v0,Ir=new o0,jw={createKey:eA,isEquivalent:mA,estimateMemoryUsage:CA},xA=In(Q0.cwd(),"config"),kA=In(Q0.cwd(),"src/generated"),Ky=Kn.env.CLARITY_LOG_DIR||_1(RA(),"logs"),Nn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ky,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},O0=await NA(),ui={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=ui,VA=ui.red,Iy=ui.green,dA=ui.yellow,_y=ui.blue,DA=ui.magenta,bA=ui.cyan,W0=ui.white,PA=ui.gray,zy=ui.bgRed,Qy=ui.bgYellow,X0=ui.bold,ZA=ui.dim,vA=ui.italic,oA=ui.underline,pA=ui.reset,Wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Rw={debug:"\uD83D\uDD0D",info:_y("ℹ"),success:Iy("✓"),warning:Qy(W0(X0(" WARN "))),error:zy(W0(X0(" ERROR ")))},iT=new Mn("stacks"),hi=new Mn("bunfig",{showTags:!0}),tT=Yi(ar.cwd(),"config"),rT=Yi(ar.cwd(),"src/generated"),My=Fn.env.CLARITY_LOG_DIR||K1(aA(),"logs"),Xn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:My,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},G0=await JA(),p={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},Q=p,nT=p.red,Oy=p.green,fT=p.yellow,Gy=p.blue,cT=p.magenta,lT=p.cyan,S0=p.white,yT=p.gray,Hy=p.bgRed,qy=p.bgYellow,wT=p.bgGray,a0=p.bold,uT=p.dim,hT=p.italic,$T=p.underline,AT=p.strikethrough,TT=p.reset,Sn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Nw={debug:"\uD83D\uDD0D",info:Gy("ℹ"),success:Oy("✓"),warning:qy(S0(a0(" WARN "))),error:Hy(S0(a0(" ERROR ")))},ET=new Gn("stacks"),Xi=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Hn=class extends Xi{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${i}"${n} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}},Jr=class extends Xi{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},H0=class extends Xi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}},q0=class extends Xi{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qn=class extends Xi{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}},g0=class extends Xi{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},s0=class extends Xi{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Fr=class extends Xi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}},L0=class extends Xi{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}},x0=class extends Xi{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ut={configNotFound(i,t,r){return new Hn(i,t,r)},configLoad(i,t,r){return new Jr(i,t,r)},configValidation(i,t,r){return new H0(i,t,r)},configMerge(i,t,r,n){return new q0(i,t,r,n)},envVar(i,t,r,n){return new qn(i,t,r,n)},fileSystem(i,t,r){return new g0(i,t,r)},typeGeneration(i,t,r){return new s0(i,t,r)},schemaValidation(i,t,r){return new Fr(i,t,r)},browserConfig(i,t,r,n){return new L0(i,t,r,n)},plugin(i,t,r){return new x0(i,t,r)}},Ww={replace:"replace",concat:"concat",smart:"smart"},Xw=/^https?:\/\//,qi=new Gn("bunfig",{showTags:!0}),lt=new nc,Sw=Bi(Kt.cwd(),"config"),aw=Bi(Kt.cwd(),"src/generated")});function eT(i,t={}){let r=_n.cwd();while(r.includes("storage"))r=Ry(r,"..");let n=Ry(r,i||"");if(t?.relative)return tA(_n.cwd(),n);return n}var mT=_n.env.CLARITY_LOG_DIR||iA(eT(),"logs"),Jw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},gn={...Jw},YU=(async()=>{try{let{loadConfig:i}=await BT().then(()=>$w),t=await i({name:"clarity",alias:"logging",defaultConfig:Jw,cwd:_n.cwd()});if(t)Object.assign(gn,t)}catch{}return gn})();function ii(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CT(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let i=ft.type;if(i==="renderer"||i==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class Fw{async format(i){let t=await CT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid: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 fi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=fi,BU=fi.red,UT=fi.green,eU=fi.yellow,jT=fi.blue,mU=fi.magenta,CU=fi.cyan,gy=fi.white,UU=fi.gray,RT=fi.bgRed,NT=fi.bgYellow,jU=fi.bgGray,sy=fi.bold,RU=fi.dim,NU=fi.italic,WU=fi.underline,XU=fi.strikethrough,SU=fi.reset,J0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WT={debug:"\uD83D\uDD0D",info:jT("ℹ"),success:UT("✓"),warning:NT(gy(sy(" WARN "))),error:RT(gy(sy(" ERROR ")))};class Pn{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={...gn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fw,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 r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...J0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...J0};return{...J0,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:gn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ii()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,c=3,l=1000;while(f<c)try{try{try{await lA(this.config.logDirectory,Sy.F_OK|Sy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await yA(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:it.from(i);try{if(!Tn(this.currentLogFile))await R0(this.currentLogFile,"",{mode:420});if(n=Xy(this.currentLogFile,"a",420),cA(n,y,{flag:"a"}),Wy(n),n!==void 0)j0(n),n=void 0;if((await Dt(this.currentLogFile)).size===0){if(await R0(this.currentLogFile,y,{flag:"w",mode:420}),(await Dt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{j0(n)}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 r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return bt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return bt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return bt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ii())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(n.length>c)for(let[l]of n.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return U0(16).toString("hex")}generateKey(){return U0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=U0(16),n=rA("aes-256-gcm",t,r),f=it.isBuffer(i)?i:it.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=it.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Jy(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(it.from(it.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ii())return;if(!this.shouldWriteToFile())return;let i=await Dt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await En(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=`${r}.${l}`;if(await Dt(r).catch(()=>null))try{if(await ay(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await Yn(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await R0(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=r.replace(/\.log$/,`-${f}.log`);if(await Dt(r).catch(()=>null))await ay(r,c)}if(this.currentLogFile=n,t.maxFiles){let f=(await En(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await Yn(bt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=Ny(i),n=fA(t),f=Jy();await hA(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Tn(this.currentLogFile))try{let i=Xy(this.currentLogFile,"r+");Wy(i),j0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ii()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await En(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Yn(bt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ii())return!1;let i=typeof 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:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=O.underline(O.blue(n)),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,(r,n)=>O.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>O.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>O.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>O.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>O.strikethrough(n)),t}supportsHyperlinks(){if(ii())return!1;let i=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 r=q.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(wA(t)||t.startsWith("./")||t.startsWith("../"))t=uA(t);else return null;return Tn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":WT[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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ii()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
45
45
|
`;if(y)h+=`${y}
|
|
46
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
47
|
-
`);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!
|
|
49
|
-
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:O.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(h),showTimestamp:!1}))}else if(!
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(
|
|
46
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ii()&&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()&&!ii()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,c="info")=>{if(!ii()&&q.stdout.isTTY)q.stdout.write(`
|
|
47
|
+
`);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ii()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:r,message:`${O.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(r)w+=` ${JSON.stringify(r)}`;if(w+=`
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ii())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Pn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ii())throw Error("createReadStream is not supported in browser environments");if(!Tn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ny(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=it.isBuffer(i)?i:it.from(i,"base64"),f=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=nA("aes-256-gcm",r,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=it.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ii()}isServerMode(){return!ii()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
49
|
+
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:O.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(h),showTimestamp:!1}))}else if(!ii())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ii())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();q.stdin.removeListener("data",r);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",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(r=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)r+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${y}${l} ${O.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
51
51
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,c=O.green("━".repeat(n)),l=O.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${r}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===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,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
|
|
52
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||
|
|
52
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ii()||!q.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ii()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await En(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=bt(this.config.logDirectory,n);if(i.before)try{if((await Dt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Yn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var aU=new Pn("stacks");class Li extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Kw extends Li{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class sn extends Li{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Iw extends Li{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class _w extends Li{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class fc extends Li{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class zw extends Li{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Qw extends Li{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ln extends Li{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Mw extends Li{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class Ow extends Li{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var ot={configNotFound(i,t,r){return new Kw(i,t,r)},configLoad(i,t,r){return new sn(i,t,r)},configValidation(i,t,r){return new Iw(i,t,r)},configMerge(i,t,r,n){return new _w(i,t,r,n)},envVar(i,t,r,n){return new fc(i,t,r,n)},fileSystem(i,t,r){return new zw(i,t,r)},typeGeneration(i,t,r){return new Qw(i,t,r)},schemaValidation(i,t,r){return new Ln(i,t,r)},browserConfig(i,t,r,n){return new Mw(i,t,r,n)},plugin(i,t,r){return new Ow(i,t,r)}};async function XT(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=r;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===r||!f(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class cc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=r,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Z0.track("applyEnvironmentVariables",u,{configName:i});return u()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${y.join("_")}`,u=n.useBackwardCompatibility?`${r}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,r,n);else{let h=Bn.env[w]||(u?Bn.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=Bn.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof fc)throw $;throw ot.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw ot.envVar(r,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(Bn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,c=n||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,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${r}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,r,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
53
53
|
|
|
54
54
|
`;for(let n of i)r+=`${n.key}
|
|
55
55
|
`,r+=` Type: ${n.type}
|
|
@@ -61,32 +61,32 @@ export type ConfigOf = Config
|
|
|
61
61
|
`;r+=`| Variable | Type | Description | Example |
|
|
62
62
|
`,r+=`|----------|------|-------------|----------|
|
|
63
63
|
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
64
|
-
`;return r}}function WT(i,t,r={}){return Mw(i,t,r,new WeakMap)}function Mw(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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 Ow(i,t,f,n);if(!Ii(t)||!Ii(i))return t;return JT(i,t,r,n)}function Ow(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return XT(i,t);case"smart":return ST(i,t,n);default:return t}return t}function XT(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>x0(f,n)))r.push(n);return r}function ST(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return aT(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function aT(i,t,r){let n=[...t];for(let f of i){if(!Ii(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((w)=>Ii(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function JT(i,t,r,n){let f=t;if(Ii(f)&&n.has(f))return n.get(f);let c={...i};if(Ii(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Ii(y)&&Ii(w))c[l]=Mw(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=Ow(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function Gw(i,t,r="replace"){return WT(i,t,{arrayMergeMode:r==="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 r=0;r<i.length;r++)if(!x0(i[r],t[r]))return!1;return!0}if(Ii(i)&&Ii(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!x0(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Hw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;if(f){let u=_n.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Bn(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 sn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new sn(i,Error("Configuration must export a valid object"),"unknown");let e={config:Gw(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)_n.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?rr.configLoad(i,u):rr.configLoad(i,Error(String(u)))}};if(l)return P0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(R0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of n){if(!c)continue;if(r.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)r.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return r.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return NT(async()=>{return Bn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!Bn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=R0(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=R0(i,l);if(await this.checkFileAccess(y))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!Bn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var FT=/^https?:\/\//;class qw{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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,r){try{if(!uA(t))throw new gn(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new gn(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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:FT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var it=new bn("bunfig",{showTags:!0});function IT(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class sw{fileLoader=new Hw;envProcessor=new fc;validator=new qw;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)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,r){let{name:n="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Vn.cwd(),A=[],T=await this.loadLocalConfiguration(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Ji($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw rr.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${IT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?mn(i,f,l):f,h=this.getLocalDirectories(r,n);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,r,n,f,c){if(!i)return null;let l=c?mn(i,r,f):r,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:n,verbose:f});if(h){if(f)it.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?mn(i,n,c):n;try{let w=Ji(r,"package.json");if(!N1(w))return null;let u={};try{u=JSON.parse(W1(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:Gw(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,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:mn(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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 rr.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return _n.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);_n.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ji(xt(),".config",i),Ji(xt(),".config"),xt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var SU=new sw;function mn(i,t,r=!1){let n=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=Vn.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 aU=Ji(Vn.cwd(),"config"),JU=Ji(Vn.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 N={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},ir={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 xw(i){return k0.readFileSync(i,"utf8")}function V0(i,t){let r=[];function n(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())n(y);else if(l===t)r.push(f)}catch{continue}}}return n(i),r}function R(i,t,r){if(r||o.verbose)console.debug(`[tlsx:${i}] ${t}`)}var QT=zT(KT);function kw(){return Lw.env.SUDO_PASSWORD}var sy="[redacted]",MT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),OT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function GT(i){let t=i.toLowerCase();return MT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Ln(i){if(Array.isArray(i))return i.map((r)=>Ln(r));if(typeof i==="string")return OT.test(i)?sy:i;if(!i||typeof i!=="object")return i;let t={};for(let[r,n]of Object.entries(i)){if(GT(r)){t[r]=sy;continue}t[r]=Ln(n)}return t}function Pn(i){return JSON.stringify(Ln(i))}function HT(i){let t=kw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let r=t.replace(/'/g,"'\\''"),n=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function mt(i,t={}){let r=HT(i);try{let{stdout:n,stderr:f}=await QT(r,{cwd:t.cwd||Lw.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:f.trim()}}catch(n){let f=Error(`Failed to execute command: ${i}
|
|
65
|
-
Error: ${n.message}`);throw f.stack=n.stack,f}}function
|
|
64
|
+
`;return r}}function ST(i,t,r={}){return Gw(i,t,r,new WeakMap)}function Gw(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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 Hw(i,t,f,n);if(!zi(t)||!zi(i))return t;return KT(i,t,r,n)}function Hw(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return aT(i,t);case"smart":return JT(i,t,n);default:return t}return t}function aT(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>k0(f,n)))r.push(n);return r}function JT(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return FT(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function FT(i,t,r){let n=[...t];for(let f of i){if(!zi(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((w)=>zi(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function KT(i,t,r,n){let f=t;if(zi(f)&&n.has(f))return n.get(f);let c={...i};if(zi(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(zi(y)&&zi(w))c[l]=Gw(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=Hw(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function qw(i,t,r="replace"){return ST(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function k0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!k0(i[r],t[r]))return!1;return!0}if(zi(i)&&zi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!k0(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class gw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;if(f){let u=zn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!en(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 sn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new sn(i,Error("Configuration must export a valid object"),"unknown");let e={config:qw(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)zn.setWithFileCheck("file",e,i,c);return e}catch(u){throw u instanceof Error?ot.configLoad(i,u):ot.configLoad(i,Error(String(u)))}};if(l)return Z0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(N0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of n){if(!c)continue;if(r.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)r.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return r.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return XT(async()=>{return en(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!en(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=N0(i,`${c}${l}`);if(await this.checkFileAccess(y))n.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))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!en(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var IT=/^https?:\/\//;class sw{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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 Z0.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,r){try{if(!$A(t))throw new Ln(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Ln(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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:IT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var tt=new Pn("bunfig",{showTags:!0});function _T(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Lw{fileLoader=new gw;envProcessor=new cc;validator=new sw;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)tt.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw tt.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||dn.cwd(),A=[],T=await this.loadLocalConfiguration(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Ii($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw ot.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${_T(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?Cn(i,f,l):f,h=this.getLocalDirectories(r,n);for(let $ of h){if(l)tt.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)tt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,r,n,f,c){if(!i)return null;let l=c?Cn(i,r,f):r,y=[Ii(qt(),".config",i),Ii(qt(),".config"),qt()];for(let w of y){if(f)tt.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:f});if(h){if(f)tt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?Cn(i,n,c):n;try{let w=Ii(r,"package.json");if(!X1(w))return null;let u={};try{u=JSON.parse(S1(w,"utf8"))}catch(A){if(c)tt.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)tt.success(`Configuration loaded from package.json: ${$}`);return{config:qw(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)tt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cn(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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 ot.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return zn.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);zn.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ii(i,"config"),Ii(i,".config"),t?Ii(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ii(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ii(qt(),".config",i),Ii(qt(),".config"),qt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var JU=new Lw;function Cn(i,t,r=!1){let n=new cc,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=dn.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 FU=Ii(dn.cwd(),"config"),KU=Ii(dn.cwd(),"src/generated"),xw={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:u0.join(w0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:u0.join(w0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:u0.join(w0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var v=xw,gi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var X={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Zt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function Vw(i){return V0.readFileSync(i,"utf8")}function d0(i,t){let r=[];function n(f){let c;try{c=V0.readdirSync(f)}catch{return}for(let l of c){let y=Hi.join(f,l);try{if(V0.statSync(y).isDirectory())n(y);else if(l===t)r.push(f)}catch{continue}}}return n(i),r}function R(i,t,r){if(r||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var OT=MT(zT);function dw(){return kw.env.SUDO_PASSWORD}var Ly="[redacted]",GT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),HT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function qT(i){let t=i.toLowerCase();return GT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function xn(i){if(Array.isArray(i))return i.map((r)=>xn(r));if(typeof i==="string")return HT.test(i)?Ly:i;if(!i||typeof i!=="object")return i;let t={};for(let[r,n]of Object.entries(i)){if(qT(r)){t[r]=Ly;continue}t[r]=xn(n)}return t}function Zn(i){return JSON.stringify(xn(i))}function gT(i){let t=dw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let r=t.replace(/'/g,"'\\''"),n=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function Ct(i,t={}){let r=gT(i);try{let{stdout:n,stderr:f}=await OT(r,{cwd:t.cwd||kw.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:f.trim()}}catch(n){let f=Error(`Failed to execute command: ${i}
|
|
65
|
+
Error: ${n.message}`);throw f.stack=n.stack,f}}function Dw(i){if(i.domain)return i.domain;if(i.domains?.length)return i.domains[0];throw Error("Either domain or domains must be specified")}function lc(i){let t=Hi.join(QT.homedir(),".stacks","ssl"),r=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,n=i.certPath?Hi.isAbsolute(i.certPath)?i.certPath:Hi.join(r,i.certPath):Hi.join(r,v.certPath),f=i.keyPath?Hi.isAbsolute(i.keyPath)?i.keyPath:Hi.join(r,i.keyPath):Hi.join(r,v.keyPath),c=i.caCertPath?Hi.isAbsolute(i.caCertPath)?i.caCertPath:Hi.join(r,i.caCertPath):Hi.join(r,v.caCertPath);return{certPath:n,keyPath:f,caCertPath:c,basePath:r}}function bw(i){let t=[],r=new Set;if(i.domain)r.add(i.domain);if(i.domains?.length)i.domains.forEach((n)=>r.add(n));for(let n of r)t.push({type:2,value:n});if(i.altNameIPs?.length)for(let n of i.altNameIPs)t.push({type:7,ip:n});if(i.altNameURIs?.length)for(let n of i.altNameURIs)t.push({type:6,value:n});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return R(X.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function yc(i){let t=i.notBeforeDays??gi.DEFAULT_NOT_BEFORE_DAYS,r=i.validityDays??(i.validityYears?i.validityYears*365:gi.DEFAULT_VALIDITY_DAYS);R(X.CERT,"Calculating certificate validity dates",i.verbose);let n=new Date(Date.now()-86400*t*1000),f=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),R(X.CERT,`Validity period: ${n.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:n,notAfter:f}}var si={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},ei={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 Xr(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function ai(i,t){let r=Xr(t.length);return Buffer.concat([Buffer.from([i]),r,t])}function Kr(i){let t=i.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let f=t[n],c=[];c.unshift(f&127),f>>=7;while(f>0)c.unshift(f&127|128),f>>=7;r.push(...c)}return ai(si.OID,Buffer.from(r))}function D0(i){let t;if(typeof i==="bigint"){let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return ai(si.INTEGER,t)}function Pw(i,t=0){return ai(si.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Zw(i){return ai(si.OCTET_STRING,i)}function Si(...i){return ai(si.SEQUENCE,Buffer.concat(i))}function sT(...i){return ai(si.SET,Buffer.concat(i))}function LT(i){return ai(si.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function xT(i){return ai(si.UTF8_STRING,Buffer.from(i,"utf8"))}function kT(){return Buffer.from([si.NULL,0])}function xy(i,t,r=!0){let n=160|i|(r?0:0),f=Xr(t.length);return Buffer.concat([Buffer.from([n]),f,t])}function ky(i){let t=i.getUTCFullYear();if(t>=2050){let r=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return ai(si.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),n=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),l=i.getUTCMinutes().toString().padStart(2,"0"),y=i.getUTCSeconds().toString().padStart(2,"0"),w=`${r}${n}${f}${c}${l}${y}Z`;return ai(si.UTC_TIME,Buffer.from(w,"ascii"))}}function VT(i,t){return Si(ky(i),ky(t))}function Vy(i){let t=[];for(let r of i){let n;switch(r.shortName){case"CN":n=ei.COMMON_NAME;break;case"C":n=ei.COUNTRY;break;case"L":n=ei.LOCALITY;break;case"ST":n=ei.STATE;break;case"O":n=ei.ORGANIZATION;break;case"OU":n=ei.ORGANIZATIONAL_UNIT;break;default:continue}let f=r.shortName==="C"?LT(r.value):xT(r.value),c=Si(Kr(n),f);t.push(sT(c))}return Si(...t)}function vw(i){return Si(Kr(i),kT())}function dT(i){return i.export({type:"spki",format:"der"})}function DT(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 r=t.split(":"),n=Buffer.alloc(16);for(let f=0;f<8;f++){let c=Number.parseInt(r[f]||"0",16);n.writeUInt16BE(c,f*2)}return n}else{let t=i.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function bT(i){let t=[];for(let r of i)if(r.type===2&&r.value){let n=Xr(r.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=DT(r.ip),f=Xr(n.length);t.push(Buffer.concat([Buffer.from([135]),f,n]))}else if(r.type===6&&r.value){let n=Xr(r.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return Si(...t)}function PT(i,t){if(i){if(t!==void 0)return Si(ai(1,Buffer.from([255])),D0(t));return Si(ai(1,Buffer.from([255])))}return Si()}function ZT(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let r=0,n=t;while(n>0&&(n&1)===0)r++,n>>=1;if(t===0)r=7;return Pw(Buffer.from([t]),r)}function vT(i){let t=[];if(i.serverAuth)t.push(Kr(ei.SERVER_AUTH));if(i.clientAuth)t.push(Kr(ei.CLIENT_AUTH));return Si(...t)}function Nr(i,t,r){let n=[Kr(i)];if(t)n.push(ai(1,Buffer.from([255])));return n.push(Zw(r)),Si(...n)}function oT(i){let t=[];if(t.push(xy(0,D0(2))),t.push(D0(i.serialNumber)),t.push(vw(ei.SHA256_WITH_RSA)),t.push(Vy(i.issuer)),t.push(VT(i.notBefore,i.notAfter)),t.push(Vy(i.subject)),t.push(dT(i.publicKey)),i.extensions){let r=[];if(i.extensions.basicConstraints)r.push(Nr(ei.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,PT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)r.push(Nr(ei.KEY_USAGE,i.extensions.keyUsage.critical??!0,ZT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)r.push(Nr(ei.EXTENDED_KEY_USAGE,!1,vT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)r.push(Nr(ei.SUBJECT_ALT_NAME,!1,bT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)r.push(Nr(ei.SUBJECT_KEY_IDENTIFIER,!1,Zw(i.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(xy(3,Si(...r)))}return Si(...t)}function pT(i,t){let r=pt.createSign("SHA256");r.update(i);let n=r.sign(t);return Si(i,vw(ei.SHA256_WITH_RSA),Pw(n))}function iE(i,t){let r=i.toString("base64"),n=[];for(let f=0;f<r.length;f+=64)n.push(r.slice(f,f+64));return`-----BEGIN ${t}-----
|
|
66
66
|
${n.join(`
|
|
67
67
|
`)}
|
|
68
68
|
-----END ${t}-----
|
|
69
|
-
`}function
|
|
70
|
-
`);for(let c of f){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)n.push({shortName:l.trim(),value:w.trim()})}return{publicKey:r,subject:n}}async function
|
|
71
|
-
`);for(let n of r){let[f,...c]=n.split("="),l=c.join("=");if(f&&l)t.push({shortName:f.trim(),value:l.trim()})}return t}function
|
|
72
|
-
`).some((n)=>{let f=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===r}))return R(N.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return R(N.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return R(N.TRUST,`Error checking certificate trust: ${r}`,t),!1}}var uE={platform:"darwin",async addCertificate(i,t){if(await wE(i,t?.verbose)){R(N.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),ir.success("Certificate is already trusted in system keychain");return}R(N.TRUST,"Adding certificate to macOS keychain",t?.verbose),await mt(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,r){let n=r||o.commonName;R(N.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await mt(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),R(N.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(f){throw R(N.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},hE={platform:"win32",async addCertificate(i,t){R(N.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await mt(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,r){let n=r||o.commonName;R(N.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await mt(`certutil -delstore -enterprise Root "${n}"`),R(N.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(f){throw R(N.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},$E={platform:"linux",async addCertificate(i,t){R(N.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=xn.homedir(),n=Hi.LINUX_CERT_DB_FILENAME,f=Hi.LINUX_TRUST_ARGS;R(N.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let c=V0(r,n);if(c.length===0){ir.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){R(N.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{R(N.TRUST,`Attempting to delete existing cert for ${o.commonName}`,t?.verbose),await mt(`certutil -d sql:${l} -D -n ${o.commonName}`)}catch(y){R(N.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}R(N.TRUST,`Adding new certificate to ${l}`,t?.verbose),await mt(`certutil -d sql:${l} -A -t ${f} -n ${o.commonName} -i ${i}`),ir.info(`Cert added to ${l}`)}},async removeCertificate(i,t,r){let n=r||o.commonName;R(N.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let f=xn.homedir(),c=Hi.LINUX_CERT_DB_FILENAME;R(N.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=V0(f,c);if(l.length===0){ir.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){R(N.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await mt(`certutil -d sql:${y} -D -n "${n}"`),ir.info(`Cert removed from ${y}`)}catch(w){R(N.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},AE={darwin:uE,win32:hE,linux:$E};async function Tc(i,t,r){R(N.TRUST,`Adding certificate to system trust store with options: ${Pn(r)}`,r?.verbose),R(N.TRUST,"Storing certificate and private key",r?.verbose);let n=pw(i,r);R(N.TRUST,"Storing CA certificate",r?.verbose);let f=iu(t,r),c=xn.platform();R(N.TRUST,`Detected platform: ${c}`,r?.verbose);let l=AE[c];if(!l){let y=`Unsupported platform: ${c}`;throw R(N.TRUST,`Error: ${y}`,r?.verbose),Error(y)}return await l.addCertificate(f,r),R(N.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as tl}from"node:os";import{join as rl,resolve as AN}from"node:path";import{existsSync as ru,statSync as nu}from"fs";import{existsSync as TE,mkdirSync as Sj,readdirSync as aj,readFileSync as EE,writeFileSync as Jj}from"fs";import{homedir as fr}from"os";import{dirname as Kj,resolve as Ki}from"path";import _f from"process";import{existsSync as fu,statSync as cu}from"fs";import{existsSync as zc,mkdirSync as YE,readdirSync as BE,writeFileSync as eE}from"fs";import{homedir as cr}from"os";import{dirname as lu,resolve as mi}from"path";import zt from"process";import{join as mE,relative as CE,resolve as yu}from"path";import Cf from"process";import{existsSync as ku,mkdirSync as gj,readdirSync as Lj,writeFileSync as xj}from"fs";import{homedir as Ec}from"os";import{dirname as dj,resolve as ei}from"path";import Mr from"process";import{join as UE,relative as jE,resolve as wu}from"path";import Uf from"process";import{existsSync as Vu,mkdirSync as vj,readdirSync as oj,writeFileSync as pj}from"fs";import{dirname as tR,resolve as jf}from"path";import Qc from"process";import{Buffer as jt}from"buffer";import{createCipheriv as RE,createDecipheriv as NE,randomBytes as Yc}from"crypto";import{closeSync as Bc,createReadStream as uu,createWriteStream as WE,existsSync as ec,fsyncSync as hu,openSync as $u,writeFileSync as XE}from"fs";import{access as SE,constants as Au,mkdir as aE,readdir as on,rename as Tu,stat as lr,unlink as pn,writeFile as mc}from"fs/promises";import{join as yr}from"path";import hi from"process";import{pipeline as JE}from"stream/promises";import{createGzip as Eu}from"zlib";import wr from"process";import ut from"process";import{Buffer as lt}from"buffer";import{createCipheriv as FE,createDecipheriv as IE,randomBytes as Cc}from"crypto";import{closeSync as Uc,createReadStream as Yu,createWriteStream as KE,existsSync as tf,fsyncSync as Bu,openSync as eu,writeFileSync as _E}from"fs";import{access as zE,constants as mu,mkdir as QE,readdir as rf,rename as Cu,stat as ur,unlink as nf,writeFile as jc}from"fs/promises";import{isAbsolute as ME,join as hr,resolve as OE}from"path";import _ from"process";import{pipeline as GE}from"stream/promises";import{createGzip as Uu}from"zlib";import $r from"process";import ht from"process";import ff from"process";import{existsSync as cf}from"fs";import{resolve as Rc}from"path";import{existsSync as HE}from"fs";import{existsSync as qE,readdirSync as sE}from"fs";import{extname as Nc,resolve as ju}from"path";import gE from"process";import{join as LE,relative as xE,resolve as Ru}from"path";import Rf from"process";import{Buffer as yt}from"buffer";import{createCipheriv as kE,createDecipheriv as VE,randomBytes as Wc}from"crypto";import{closeSync as Xc,createReadStream as Nu,createWriteStream as dE,existsSync as lf,fsyncSync as Wu,openSync as Xu,writeFileSync as DE}from"fs";import{access as bE,constants as Su,mkdir as PE,readdir as yf,rename as au,stat as Ar,unlink as wf,writeFile as Sc}from"fs/promises";import{isAbsolute as ZE,join as Tr,resolve as vE}from"path";import z from"process";import{pipeline as oE}from"stream/promises";import{createGzip as Ju}from"zlib";import Er 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 mB}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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!ru(i))return!0;return nu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=ru(r)?nu(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class xu{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var mf=new Lu,Vc=new xu;var pE=Object.defineProperty,iY=(i)=>i;function tY(i,t){this[i]=iY.bind(null,t)}var rY=(i,t)=>{for(var r in t)pE(i,r,{get:t[r],enumerable:!0,configurable:!0,set:tY.bind(t,r)})},nY=(i,t)=>()=>(i&&(t=i(i=0)),t),du={};rY(du,{withErrorRecovery:()=>Pu,tryLoadConfig:()=>SY,loadConfigWithResult:()=>WY,loadConfig:()=>ih,isRetryableError:()=>mY,isConfigNotFoundError:()=>eY,isBunfigError:()=>Zu,globalPerformanceMonitor:()=>Hr,globalCache:()=>Yr,getEnvOrDefault:()=>CY,generateConfigTypes:()=>aY,defaultGeneratedDir:()=>wh,defaultConfigDir:()=>yh,deepMergeWithArrayStrategy:()=>Zc,deepMerge:()=>vu,createLibraryConfig:()=>JY,config:()=>XY,bunfigPlugin:()=>FY,applyEnvVarsToConfig:()=>Qr,TypeGenerationError:()=>gc,SchemaValidationError:()=>Gr,PluginError:()=>xc,PerformanceMonitor:()=>Dc,FileSystemError:()=>sc,ErrorFactory:()=>Rt,EnvVarError:()=>Jf,EnvProcessor:()=>zf,ConfigValidator:()=>vc,ConfigValidationError:()=>Hc,ConfigNotFoundError:()=>af,ConfigMergeError:()=>qc,ConfigLoader:()=>oc,ConfigLoadError:()=>Or,ConfigFileLoader:()=>Qf,ConfigCache:()=>dc,CacheUtils:()=>rh,BunfigError:()=>Si,BrowserConfigError:()=>Lc,ArrayMergeStrategies:()=>ch});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 r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!fu(i))return!0;return cu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=fu(r)?cu(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Dc{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function fY(i,t={}){let n=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return n?`${i}:${n}`:i}function cY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function lY(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 n=[...t];for(let f of i)if(d(f)&&"name"in f){if(!n.find((l)=>d(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(d(f)&&"path"in f){if(!n.find((l)=>d(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((c)=>Nf(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!d(t)||!d(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(d(f)&&d(r[n]))r[n]=bc(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&d(f[0])&&d(r[n][0])){let c=[...f];for(let l of r[n])if(d(l)&&"name"in l){if(!c.find((w)=>d(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(d(l)&&"path"in l){if(!c.find((w)=>d(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Nf(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function Nf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Nf(i[r],t[r]))return!1;return!0}if(d(i)&&d(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Nf(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function yY(i,t){if(!Vu(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return bc(t,n)}catch{return null}}catch{return null}}async function wY({name:i="",cwd:t,defaultConfig:r}){let n=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(n,`${l}${y}`),u=await yY(w,r);if(u!==null)return u}try{let l=jf(n,"package.json");if(Vu(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return bc(r,w)}catch{}}}catch{}return r}function uY(i,t={}){let r=Uf.cwd();while(r.includes("storage"))r=wu(r,"..");let n=wu(r,i||"");if(t?.relative)return jE(Uf.cwd(),n);return n}async function hY(){try{let i=await wY({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 $Y(){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 $Y(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:wr.pid,hostname:t(),environment:wr.env.NODE_ENV||"development",platform:wr.platform,version:wr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wr.env.NODE_ENV||wr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Wf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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 r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let r=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await SE(this.config.logDirectory,Au.F_OK|Au.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await aE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:jt.from(i);try{if(!ec(this.currentLogFile))await mc(this.currentLogFile,"",{mode:420});if(f=$u(this.currentLogFile,"a",420),XE(f,w,{flag:"a"}),hu(f),f!==void 0)Bc(f),f=void 0;if((await lr(this.currentLogFile)).size===0){if(await mc(this.currentLogFile,w,{flag:"w",mode:420}),(await lr(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(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yr(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 yr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yr(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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,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(),r=Yc(16),n=RE("aes-256-gcm",t,r),f=jt.concat([n.update(i,"utf8"),n.final()]),c=n.getAuthTag();return{encrypted:jt.concat([r,f,c]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Eu(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(jt.from(jt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await lr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await on(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=`${r}.${l}`;if(await lr(r).catch(()=>null))try{if(await Tu(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await pn(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await mc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=r.replace(/\.log$/,`-${f}.log`);if(await lr(r).catch(()=>null))await Tu(r,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await on(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await pn(yr(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=uu(i),n=WE(t),f=Eu();await JE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ec(this.currentLogFile))try{let i=$u(this.currentLogFile,"r+");hu(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 on(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await pn(yr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=hi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);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(`
|
|
69
|
+
`}function wc(){let i=pt.randomBytes(20);return i[0]=i[0]&127||1,i}function ow(i=2048){let{privateKey:t,publicKey:r}=pt.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:r}}function tE(i){let t=i.export({type:"spki",format:"der"});return pt.createHash("sha1").update(t).digest()}function pw(i){let t={serialNumber:i.serialNumber||wc(),notBefore:i.notBefore,notAfter:i.notAfter,subject:i.subject,issuer:i.issuer||i.subject,publicKey:i.publicKey,extensions:{basicConstraints:{isCA:i.isCA??!1,critical:!0,pathLenConstraint:i.pathLenConstraint},subjectKeyIdentifier:tE(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let r=oT(t),n=pT(r,i.signingKey);return{certificate:iE(n,"CERTIFICATE"),certificateDer:n}}function iu(i){return i.export({type:"pkcs8",format:"pem"})}function rE(i){return pt.createPrivateKey(i)}function nE(i){let t=new pt.X509Certificate(i),r=t.publicKey,n=[],f=t.subject.split(`
|
|
70
|
+
`);for(let c of f){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)n.push({shortName:l.trim(),value:w.trim()})}return{publicKey:r,subject:n}}async function uc(i={}){R("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||gi.DEFAULT_KEY_SIZE;R("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:r,publicKey:n}=ow(t),f=[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:c,notAfter:l}=yc({validityYears:i.validityYears||gi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:y}=pw({serialNumber:wc(),notBefore:c,notAfter:l,subject:f,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:y,privateKey:iu(r),notBefore:c,notAfter:l}}async function hc(i){if(R("ca","Generating new certificate",i.verbose),R("ca",`Options: ${Zn(i)}`,i.verbose),!i.domain&&!i.domains?.length)throw Error("Either domain or domains must be specified");if(!i.rootCA?.certificate||!i.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=nE(i.rootCA.certificate),r=rE(i.rootCA.privateKey);R("ca",`Generating ${gi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let n=gi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:c}=ow(n),l=i.commonName||Dw(i),y=i.certificateAttributes||[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organizationName||v.organizationName},{shortName:"CN",value:l}],{notBefore:w,notAfter:u}=yc({validityDays:i.validityDays||gi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=bw(i),$=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=pw({serialNumber:wc(),notBefore:w,notAfter:u,subject:y,issuer:t,publicKey:c,signingKey:r,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:A,subjectAltName:h});return{certificate:T,privateKey:iu(f),notBefore:w,notAfter:u}}function tu(i,t){R(X.STORAGE,`Storing certificate and private key with options: ${Zn(t)}`,t?.verbose);let{certPath:r,keyPath:n}=lc({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});R(X.STORAGE,`Certificate path: ${r}`,t?.verbose),R(X.STORAGE,`Private key path: ${n}`,t?.verbose);let f=b0.dirname(r);if(!ct.existsSync(f))R(X.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),ct.mkdirSync(f,{recursive:!0});R(X.STORAGE,"Writing certificate file",t?.verbose),ct.writeFileSync(r,i.certificate);let c=b0.dirname(n);if(!ct.existsSync(c))R(X.STORAGE,`Creating private key directory: ${c}`,t?.verbose),ct.mkdirSync(c,{recursive:!0});return R(X.STORAGE,"Writing private key file",t?.verbose),ct.writeFileSync(n,i.privateKey),R(X.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function ru(i,t){R(X.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=lc({basePath:t?.basePath,caCertPath:t?.caCertPath});R(X.STORAGE,`CA certificate path: ${r}`,t?.verbose);let n=b0.dirname(r);if(!ct.existsSync(n))R(X.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),ct.mkdirSync(n,{recursive:!0});return R(X.STORAGE,"Writing CA certificate file",t?.verbose),ct.writeFileSync(r,i),R(X.STORAGE,"CA certificate stored successfully",t?.verbose),r}function vn(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=Vw(i);return new fE.X509Certificate(t)}function on(i){return vn(i).fingerprint256.replace(/:/g,"").toUpperCase()}function $c(i){return nu(vn(i).subject)}function Ac(i,t,r=443,n=4000){let f;try{f=t.includes("-----BEGIN")?t:cE.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((c)=>{let l=!1,y=(u)=>{if(l)return;l=!0,c(u)},w=lE.connect({host:i,port:r,servername:i,ca:f,rejectUnauthorized:!0},()=>{y(w.authorized),w.end()});w.setTimeout(n,()=>{w.destroy(),y(!1)}),w.on("error",()=>y(!1))})}function yE(i){let t=[],r=i.split(`
|
|
71
|
+
`);for(let n of r){let[f,...c]=n.split("="),l=c.join("=");if(f&&l)t.push({shortName:f.trim(),value:l.trim()})}return t}function nu(i){return yE(i).find((t)=>t.shortName==="CN")?.value||""}function wE(i){let t=[],r=nu(i.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let n=i.subjectAltName;if(n){let f=n.split(", ");for(let c of f)if(c.startsWith("DNS:"))t.push(c.slice(4))}return[...new Set(t)]}function Tc(i,t){let r=vn(i),n=wE(r);for(let f of n){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 hE(i,t){if(kn.platform()!=="darwin")return!1;try{let r=on(i);if(!r)return R(X.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(uE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
72
|
+
`).some((n)=>{let f=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===r}))return R(X.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return R(X.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return R(X.TRUST,`Error checking certificate trust: ${r}`,t),!1}}var $E={platform:"darwin",async addCertificate(i,t){if(await hE(i,t?.verbose)){R(X.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),Zt.success("Certificate is already trusted in system keychain");return}R(X.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,r){let n=r||v.commonName;R(X.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await Ct(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),R(X.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(f){throw R(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},AE={platform:"win32",async addCertificate(i,t){R(X.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await Ct(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,r){let n=r||v.commonName;R(X.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await Ct(`certutil -delstore -enterprise Root "${n}"`),R(X.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(f){throw R(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},TE={platform:"linux",async addCertificate(i,t){R(X.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=kn.homedir(),n=gi.LINUX_CERT_DB_FILENAME,f=gi.LINUX_TRUST_ARGS;R(X.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let c=d0(r,n);if(c.length===0){Zt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){R(X.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{R(X.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await Ct(`certutil -d sql:${l} -D -n ${v.commonName}`)}catch(y){R(X.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}R(X.TRUST,`Adding new certificate to ${l}`,t?.verbose),await Ct(`certutil -d sql:${l} -A -t ${f} -n ${v.commonName} -i ${i}`),Zt.info(`Cert added to ${l}`)}},async removeCertificate(i,t,r){let n=r||v.commonName;R(X.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let f=kn.homedir(),c=gi.LINUX_CERT_DB_FILENAME;R(X.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=d0(f,c);if(l.length===0){Zt.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){R(X.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await Ct(`certutil -d sql:${y} -D -n "${n}"`),Zt.info(`Cert removed from ${y}`)}catch(w){R(X.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},EE={darwin:$E,win32:AE,linux:TE};async function Ec(i,t,r){R(X.TRUST,`Adding certificate to system trust store with options: ${Zn(r)}`,r?.verbose),R(X.TRUST,"Storing certificate and private key",r?.verbose);let n=tu(i,r);R(X.TRUST,"Storing CA certificate",r?.verbose);let f=ru(t,r),c=kn.platform();R(X.TRUST,`Detected platform: ${c}`,r?.verbose);let l=EE[c];if(!l){let y=`Unsupported platform: ${c}`;throw R(X.TRUST,`Error: ${y}`,r?.verbose),Error(y)}return await l.addCertificate(f,r),R(X.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as rl}from"node:os";import{join as nl,resolve as EN}from"node:path";import{existsSync as fu,statSync as cu}from"fs";import{existsSync as YE,mkdirSync as Jj,readdirSync as Fj,readFileSync as BE,writeFileSync as Kj}from"fs";import{homedir as ir}from"os";import{dirname as zj,resolve as Qi}from"path";import zf from"process";import{existsSync as lu,statSync as yu}from"fs";import{existsSync as Qc,mkdirSync as eE,readdirSync as mE,writeFileSync as CE}from"fs";import{homedir as tr}from"os";import{dirname as wu,resolve as Ci}from"path";import It from"process";import{join as UE,relative as jE,resolve as uu}from"path";import Uf from"process";import{existsSync as du,mkdirSync as xj,readdirSync as kj,writeFileSync as Vj}from"fs";import{homedir as Yc}from"os";import{dirname as bj,resolve as mi}from"path";import zr from"process";import{join as RE,relative as NE,resolve as hu}from"path";import jf from"process";import{existsSync as Du,mkdirSync as pj,readdirSync as iR,writeFileSync as tR}from"fs";import{dirname as nR,resolve as Rf}from"path";import Mc from"process";import{Buffer as Rt}from"buffer";import{createCipheriv as WE,createDecipheriv as XE,randomBytes as Bc}from"crypto";import{closeSync as ec,createReadStream as $u,createWriteStream as SE,existsSync as mc,fsyncSync as Au,openSync as Tu,writeFileSync as aE}from"fs";import{access as JE,constants as Eu,mkdir as FE,readdir as pn,rename as Yu,stat as rr,unlink as tf,writeFile as Cc}from"fs/promises";import{join as nr}from"path";import $i from"process";import{pipeline as KE}from"stream/promises";import{createGzip as Bu}from"zlib";import fr from"process";import ht from"process";import{Buffer as yt}from"buffer";import{createCipheriv as IE,createDecipheriv as _E,randomBytes as Uc}from"crypto";import{closeSync as jc,createReadStream as eu,createWriteStream as zE,existsSync as rf,fsyncSync as mu,openSync as Cu,writeFileSync as QE}from"fs";import{access as ME,constants as Uu,mkdir as OE,readdir as nf,rename as ju,stat as cr,unlink as ff,writeFile as Rc}from"fs/promises";import{isAbsolute as GE,join as lr,resolve as HE}from"path";import _ from"process";import{pipeline as qE}from"stream/promises";import{createGzip as Ru}from"zlib";import yr from"process";import $t from"process";import cf from"process";import{existsSync as lf}from"fs";import{resolve as Nc}from"path";import{existsSync as gE}from"fs";import{existsSync as sE,readdirSync as LE}from"fs";import{extname as Wc,resolve as Nu}from"path";import xE from"process";import{join as kE,relative as VE,resolve as Wu}from"path";import Nf from"process";import{Buffer as wt}from"buffer";import{createCipheriv as dE,createDecipheriv as DE,randomBytes as Xc}from"crypto";import{closeSync as Sc,createReadStream as Xu,createWriteStream as bE,existsSync as yf,fsyncSync as Su,openSync as au,writeFileSync as PE}from"fs";import{access as ZE,constants as Ju,mkdir as vE,readdir as wf,rename as Fu,stat as wr,unlink as uf,writeFile as ac}from"fs/promises";import{isAbsolute as oE,join as ur,resolve as pE}from"path";import z from"process";import{pipeline as iY}from"stream/promises";import{createGzip as Ku}from"zlib";import hr from"process";import At from"process";import $f from"process";import{existsSync as Af}from"fs";import{resolve as zc}from"path";import{existsSync as UB}from"fs";class ku{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!fu(i))return!0;return cu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=fu(r)?cu(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Vu{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var Cf=new ku,dc=new Vu;var tY=Object.defineProperty,rY=(i)=>i;function nY(i,t){this[i]=rY.bind(null,t)}var fY=(i,t)=>{for(var r in t)tY(i,r,{get:t[r],enumerable:!0,configurable:!0,set:nY.bind(t,r)})},cY=(i,t)=>()=>(i&&(t=i(i=0)),t),bu={};fY(bu,{withErrorRecovery:()=>vu,tryLoadConfig:()=>JY,loadConfigWithResult:()=>SY,loadConfig:()=>rh,isRetryableError:()=>UY,isConfigNotFoundError:()=>CY,isBunfigError:()=>ou,globalPerformanceMonitor:()=>Or,globalCache:()=>$r,getEnvOrDefault:()=>jY,generateConfigTypes:()=>FY,defaultGeneratedDir:()=>hh,defaultConfigDir:()=>uh,deepMergeWithArrayStrategy:()=>vc,deepMerge:()=>pu,createLibraryConfig:()=>KY,config:()=>aY,bunfigPlugin:()=>IY,applyEnvVarsToConfig:()=>_r,TypeGenerationError:()=>Lc,SchemaValidationError:()=>Mr,PluginError:()=>kc,PerformanceMonitor:()=>bc,FileSystemError:()=>sc,ErrorFactory:()=>Nt,EnvVarError:()=>Ff,EnvProcessor:()=>Qf,ConfigValidator:()=>oc,ConfigValidationError:()=>qc,ConfigNotFoundError:()=>Jf,ConfigMergeError:()=>gc,ConfigLoader:()=>pc,ConfigLoadError:()=>Qr,ConfigFileLoader:()=>Mf,ConfigCache:()=>Dc,CacheUtils:()=>fh,BunfigError:()=>Ji,BrowserConfigError:()=>xc,ArrayMergeStrategies:()=>yh});class Dc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),c=n??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 r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!lu(i))return!0;return yu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=lu(r)?yu(r):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class bc{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-n;return this.recordMetric({operation:i,duration:l,timestamp:f,...r}),c}catch(c){let l=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...r}),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 r=t.map((f)=>f.duration),n=r.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function lY(i,t={}){let n=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return n?`${i}:${n}`:i}function yY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function wY(i){return i.getStats().size*2}function Pc(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&d(t[0])&&"id"in t[0]&&t[0].id===3&&d(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(d(t)&&d(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(d(i)&&"arr"in i&&Array.isArray(i.arr)&&d(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&d(t[0])&&d(i[0])){let n=[...t];for(let f of i)if(d(f)&&"name"in f){if(!n.find((l)=>d(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(d(f)&&"path"in f){if(!n.find((l)=>d(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((c)=>Wf(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!d(t)||!d(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(d(f)&&d(r[n]))r[n]=Pc(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&d(f[0])&&d(r[n][0])){let c=[...f];for(let l of r[n])if(d(l)&&"name"in l){if(!c.find((w)=>d(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(d(l)&&"path"in l){if(!c.find((w)=>d(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Wf(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}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 r=0;r<i.length;r++)if(!Wf(i[r],t[r]))return!1;return!0}if(d(i)&&d(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Wf(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function uY(i,t){if(!Du(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Pc(t,n)}catch{return null}}catch{return null}}async function hY({name:i="",cwd:t,defaultConfig:r}){let n=t||Mc.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=Rf(n,`${l}${y}`),u=await uY(w,r);if(u!==null)return u}try{let l=Rf(n,"package.json");if(Du(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Pc(r,w)}catch{}}}catch{}return r}function $Y(i,t={}){let r=jf.cwd();while(r.includes("storage"))r=hu(r,"..");let n=hu(r,i||"");if(t?.relative)return NE(jf.cwd(),n);return n}async function AY(){try{let i=await hY({name:"clarity",defaultConfig:Yf,cwd:jf.cwd(),endpoint:"",headers:{}});return{...Yf,...i}}catch{return Yf}}function P(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function TY(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let i=ht.type;if(i==="renderer"||i==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class Pu{async format(i){let t=await TY(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:fr.pid,hostname:t(),environment:fr.env.NODE_ENV||"development",platform:fr.platform,version:fr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fr.env.NODE_ENV||fr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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={...Gc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Pu,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??$i.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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{...Bf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Bf};return{...Bf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Gc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let r=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await JE(this.config.logDirectory,Eu.F_OK|Eu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await FE(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:Rt.from(i);try{if(!mc(this.currentLogFile))await Cc(this.currentLogFile,"",{mode:420});if(f=Tu(this.currentLogFile,"a",420),aE(f,w,{flag:"a"}),Au(f),f!==void 0)ec(f),f=void 0;if((await rr(this.currentLogFile)).size===0){if(await Cc(this.currentLogFile,w,{flag:"w",mode:420}),(await rr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{ec(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return nr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return nr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,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 Bc(16).toString("hex")}generateKey(){return Bc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Bc(16),n=WE("aes-256-gcm",t,r),f=Rt.concat([n.update(i,"utf8"),n.final()]),c=n.getAuthTag();return{encrypted:Rt.concat([r,f,c]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Bu(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(Rt.from(Rt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await rr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await pn(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=`${r}.${l}`;if(await rr(r).catch(()=>null))try{if(await Yu(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await tf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.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=r.replace(/\.log$/,`-${f}.log`);if(await rr(r).catch(()=>null))await Yu(r,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await pn(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await tf(nr(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=$u(i),n=SE(t),f=Bu();await KE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),mc(this.currentLogFile))try{let i=Tu(this.currentLogFile,"r+");Au(i),ec(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await pn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await tf(nr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=$i.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);if(this.fancy&&!P()){let u=ch[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 r=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:k.blue("◐"),tag:r,message:`${k.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(r)u+=` ${JSON.stringify(r)}`;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}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=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(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!mc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $u(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Rt.isBuffer(i)?i:Rt.from(i,"base64"),f=n.slice(0,16),c=n.slice(-16),l=n.slice(16,-16),y=XE("aes-256-gcm",r,f);return y.setAuthTag(c),Rt.concat([y.update(l),y.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=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:r,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:k.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:k.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:k.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
|
|
78
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${k.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase()
|
|
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 r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,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
|
|
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 on(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=yr(this.config.logDirectory,n);if(i.before)try{if((await lr(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}r.push(c)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await pn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Tf(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&L(t[0])&&"id"in t[0]&&t[0].id===3&&L(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(L(t)&&L(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&L(t[0])&&L(i[0])){let n=[...t];for(let f of i)if(L(f)&&"name"in f){if(!n.find((l)=>L(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(L(f)&&"path"in f){if(!n.find((l)=>L(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((c)=>Xf(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!L(t)||!L(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(L(f)&&L(r[n]))r[n]=Tf(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&L(f[0])&&L(r[n][0])){let c=[...f];for(let l of r[n])if(L(l)&&"name"in l){if(!c.find((w)=>L(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(L(l)&&"path"in l){if(!c.find((w)=>L(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Xf(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function Pc(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:Tf(i,t);if(Array.isArray(i))return r==="replace"?t:Tf(i,t);if(!L(t)||!L(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=n[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(r==="replace")n[f]=c;else n[f]=Tf(l,c);else if(L(c)&&L(l))n[f]=Pc(l,c,r);else n[f]=c}return n}function Xf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Xf(i[r],t[r]))return!1;return!0}if(L(i)&&L(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Xf(i[f],t[f]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function uf(i,t,r="replace"){if(!ku(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Pc(t,f,r)}catch{return null}}catch{return null}}function AY(i,t,r=!1){if(!i)return t;let n=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=`${n}_${$.map(A).join("_")}`,e=`${n}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(r)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=Mr.env[T]||Mr.env[e];if(E!==void 0){if(r)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((m)=>m.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function TY({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?AY(i,f,c):f,u=r||Mr.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"),n?ei(u,n):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(n?[ei(u,n)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let W of j)for(let X of h){let F=ei(B,`${W}${X}`),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),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${B}`);for(let j of m)for(let W of h){let X=ei(B,`${j}${W}`),F=await uf(X,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${X}`);return F}}}if(i){let B=ei(Ec(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let X=ei(B,`${j}${W}`),F=await uf(X,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${X}`);return F}}}if(i){let B=Ec(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(c)Ai.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let X=ei(B,`${j}${W}`),F=await uf(X,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${X}`);return F}}}try{let B=ei(u,"package.json");if(ku(B)){let m=await import(B),j=m[i];if(!j&&t){if(j=m[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===m[i]?i:t}`);return Pc(w,j,y)}catch(W){if(c)Ai.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)Ai.warn("Failed to load package.json:",B)}if(c)Ai.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function EY(i,t={}){let r=Cf.cwd();while(r.includes("storage"))r=yu(r,"..");let n=yu(r,i||"");if(t?.relative)return CE(Cf.cwd(),n);return n}async function YY(){try{let i=await TY({name:"clarity",alias:"logging",defaultConfig:Bf,cwd:Cf.cwd()});return{...Bf,...i||{}}}catch{return Bf}}function ri(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BY(){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 bu{async format(i){let t=await BY(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$r.pid,hostname:t(),environment:$r.env.NODE_ENV||"development",platform:$r.platform,version:$r.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$r.env.NODE_ENV||$r.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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 bu,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}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},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ri()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await zE(this.config.logDirectory,mu.F_OK|mu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await QE(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=eu(this.currentLogFile,"a",420),_E(f,w,{flag:"a"}),Bu(f),f!==void 0)Uc(f),f=void 0;if((await ur(this.currentLogFile)).size===0){if(await jc(this.currentLogFile,w,{flag:"w",mode:420}),(await ur(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(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return hr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return hr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return hr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ri())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Cc(16).toString("hex")}generateKey(){return Cc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Cc(16),n=FE("aes-256-gcm",t,r),f=lt.isBuffer(i)?i:lt.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=lt.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Uu(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(lt.from(lt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ri())return;if(!this.shouldWriteToFile())return;let i=await ur(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await rf(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=`${r}.${l}`;if(await ur(r).catch(()=>null))try{if(await Cu(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await nf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.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=r.replace(/\.log$/,`-${f}.log`);if(await ur(r).catch(()=>null))await Cu(r,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await rf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await nf(hr(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=Yu(i),n=KE(t),f=Uu();await GE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),tf(this.currentLogFile))try{let i=eu(this.currentLogFile,"r+");Bu(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(!ri()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await rf(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await nf(hr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ri())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level: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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=_.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=M.underline(M.blue(n)),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,(r,n)=>M.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>M.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>M.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>M.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>M.strikethrough(n)),t}supportsHyperlinks(){if(ri())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ME(t)||t.startsWith("./")||t.startsWith("../"))t=OE(t);else return null;return tf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":fh[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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:M.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!
|
|
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 r=(n)=>{let f=n.toString().trim().toLowerCase();$i.stdin.removeListener("data",r);try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!1)}catch{}$i.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!0)}catch{}$i.stdin.resume(),$i.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(r=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)r+=` ${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(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
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 r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(l,y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,l)),y!==void 0)this.activeProgressBar.message=y;let w=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,w)},finish:(l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=this.activeProgressBar.total,l!==void 0)this.activeProgressBar.message=l;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(l,y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;$i.stdout.write(`${"\r".padEnd($i.stdout.columns||80)}\r`),this.log(y,l),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!$i.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,c=k.green("━".repeat(n)),l=k.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${r}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||r===100?k.green("✓"):k.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=$i.stdout.columns||80,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,$i.stdout.write(i.lastRenderedLine),t)$i.stdout.write(`
|
|
80
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!$i.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await pn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=nr(this.config.logDirectory,n);if(i.before)try{if((await rr(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}r.push(c)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await tf(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Ef(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&L(t[0])&&"id"in t[0]&&t[0].id===3&&L(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(L(t)&&L(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&L(t[0])&&L(i[0])){let n=[...t];for(let f of i)if(L(f)&&"name"in f){if(!n.find((l)=>L(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(L(f)&&"path"in f){if(!n.find((l)=>L(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((c)=>Sf(c,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!L(t)||!L(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(L(f)&&L(r[n]))r[n]=Ef(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&L(f[0])&&L(r[n][0])){let c=[...f];for(let l of r[n])if(L(l)&&"name"in l){if(!c.find((w)=>L(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(L(l)&&"path"in l){if(!c.find((w)=>L(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Sf(y,l)))c.push(l);r[n]=c}else if(f.every((c)=>typeof c==="string")&&r[n].every((c)=>typeof c==="string")){let c=[...f];for(let l of r[n])if(!c.includes(l))c.push(l);r[n]=c}else r[n]=f;else r[n]=f}return r}function Zc(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:Ef(i,t);if(Array.isArray(i))return r==="replace"?t:Ef(i,t);if(!L(t)||!L(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=n[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(r==="replace")n[f]=c;else n[f]=Ef(l,c);else if(L(c)&&L(l))n[f]=Zc(l,c,r);else n[f]=c}return n}function Sf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Sf(i[r],t[r]))return!1;return!0}if(L(i)&&L(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Sf(i[f],t[f]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function hf(i,t,r="replace"){if(!du(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Zc(t,f,r)}catch{return null}}catch{return null}}function EY(i,t,r=!1){if(!i)return t;let n=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=`${n}_${$.map(A).join("_")}`,e=`${n}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(r)Ti.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let E=zr.env[T]||zr.env[e];if(E!==void 0){if(r)Ti.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((m)=>m.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function YY({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?EY(i,f,c):f,u=r||zr.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)Ti.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],e=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,mi(u,"config"),mi(u,".config"),n?mi(u,n):void 0].filter(Boolean)));for(let B of E){if(c)Ti.info(`Searching for configuration in: ${B}`);let j=[mi(u,"config"),mi(u,".config")].concat(n?[mi(u,n)]:[]).includes(B)?[...$,...A,...T,...e]:[...A,...$,...e,...T];for(let W of j)for(let S of h){let F=mi(B,`${W}${S}`),I=await hf(F,w,y);if(I!==null){if(c)Ti.success(`Configuration loaded from: ${F}`);return I}}}if(i){let B=mi(Yc(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(c)Ti.info(`Checking user config directory: ${B}`);for(let j of m)for(let W of h){let S=mi(B,`${j}${W}`),F=await hf(S,w,y);if(F!==null){if(c)Ti.success(`Configuration loaded from user config directory: ${S}`);return F}}}if(i){let B=mi(Yc(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(c)Ti.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let S=mi(B,`${j}${W}`),F=await hf(S,w,y);if(F!==null){if(c)Ti.success(`Configuration loaded from user config directory dotfile: ${S}`);return F}}}if(i){let B=Yc(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(c)Ti.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of m)for(let W of h){let S=mi(B,`${j}${W}`),F=await hf(S,w,y);if(F!==null){if(c)Ti.success(`Configuration loaded from user home directory: ${S}`);return F}}}try{let B=mi(u,"package.json");if(du(B)){let m=await import(B),j=m[i];if(!j&&t){if(j=m[t],j&&c)Ti.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)Ti.success(`Configuration loaded from package.json: ${j===m[i]?i:t}`);return Zc(w,j,y)}catch(W){if(c)Ti.warn("Failed to merge package.json config:",W)}}}catch(B){if(c)Ti.warn("Failed to load package.json:",B)}if(c)Ti.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function BY(i,t={}){let r=Uf.cwd();while(r.includes("storage"))r=uu(r,"..");let n=uu(r,i||"");if(t?.relative)return jE(Uf.cwd(),n);return n}async function eY(){try{let i=await YY({name:"clarity",alias:"logging",defaultConfig:ef,cwd:Uf.cwd()});return{...ef,...i||{}}}catch{return ef}}function ti(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function mY(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class Zu{async format(i){let t=await mY(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:yr.pid,hostname:t(),environment:yr.env.NODE_ENV||"development",platform:yr.platform,version:yr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:yr.env.NODE_ENV||yr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class af{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={...Hc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zu,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...mf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...mf};return{...mf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Hc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await ME(this.config.logDirectory,Uu.F_OK|Uu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await OE(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(!rf(this.currentLogFile))await Rc(this.currentLogFile,"",{mode:420});if(f=Cu(this.currentLogFile,"a",420),QE(f,w,{flag:"a"}),mu(f),f!==void 0)jc(f),f=void 0;if((await cr(this.currentLogFile)).size===0){if(await Rc(this.currentLogFile,w,{flag:"w",mode:420}),(await cr(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{jc(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(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return lr(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 lr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return lr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,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 Uc(16).toString("hex")}generateKey(){return Uc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Uc(16),n=IE("aes-256-gcm",t,r),f=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=yt.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Ru(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(yt.from(yt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await cr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await 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=`${r}.${l}`;if(await cr(r).catch(()=>null))try{if(await ju(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await ff(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await Rc(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=r.replace(/\.log$/,`-${f}.log`);if(await cr(r).catch(()=>null))await ju(r,c)}if(this.currentLogFile=n,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 ff(lr(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=eu(i),n=zE(t),f=Ru();await qE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),rf(this.currentLogFile))try{let i=Cu(this.currentLogFile,"r+");mu(i),jc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await nf(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ff(lr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level: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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=_.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=M.underline(M.blue(n)),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,(r,n)=>M.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>M.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>M.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>M.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>M.strikethrough(n)),t}supportsHyperlinks(){if(ti())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(GE(t)||t.startsWith("./")||t.startsWith("../"))t=HE(t);else return null;return rf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":lh[i],A=this.options.showTags!==!1&&this.name?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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:M.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
82
82
|
`;if(y)h+=`${y}
|
|
83
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
84
|
-
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!
|
|
86
|
-
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:M.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(h),showTimestamp:!1}))}else if(!
|
|
87
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(
|
|
83
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(y,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,y),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ti()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ti()&&_.stdout.isTTY)_.stdout.write(`
|
|
84
|
+
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:r,message:`${M.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(r)u+=` ${JSON.stringify(r)}`;if(u+=`
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ti())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new af(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!rf(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 r=this.keys.get(this.currentKeyId);try{let n=yt.isBuffer(i)?i:yt.from(i,"base64"),f=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=_E("aes-256-gcm",r,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(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ti()}isServerMode(){return!ti()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
86
|
+
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:M.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(h),showTimestamp:!1}))}else if(!ti())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
|
|
87
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${M.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(r=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)r+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);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(n)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
88
88
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,c=M.green("━".repeat(n)),l=M.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${r}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===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,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
|
|
89
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||
|
|
89
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await nf(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=lr(this.config.logDirectory,n);if(i.before)try{if((await cr(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}r.push(c)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ff(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function vu(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=r;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===r||!f(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function ou(i){return i instanceof Ji}function CY(i){return i instanceof Jf}function UY(i){if(ou(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>i.message.toLowerCase().includes(r.toLowerCase()))}class Qf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=r,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Or.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,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${y.join("_")}`,u=n.useBackwardCompatibility?`${r}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,r,n);else{let h=cf.env[w]||(u?cf.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=cf.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof Ff)throw $;throw Nt.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Nt.envVar(r,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(cf.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,c=n||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,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${r}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,r,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
90
90
|
|
|
91
91
|
`;for(let n of i)r+=`${n.key}
|
|
92
92
|
`,r+=` Type: ${n.type}
|
|
@@ -98,25 +98,25 @@ ${n.join(`
|
|
|
98
98
|
`;r+=`| Variable | Type | Description | Example |
|
|
99
99
|
`,r+=`|----------|------|-------------|----------|
|
|
100
100
|
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
101
|
-
`;return r}}function CY(i,t){let r=th("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function vu(i,t,r={}){return ou(i,t,r,new WeakMap)}function ou(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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 pu(i,t,f,n);if(!_i(t)||!_i(i))return t;return NY(i,t,r,n)}function pu(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return UY(i,t);case"smart":return jY(i,t,n);default:return t}return t}function UY(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Mc(f,n)))r.push(n);return r}function jY(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return RY(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function RY(i,t,r){let n=[...t];for(let f of i){if(!_i(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((u)=>_i(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function NY(i,t,r,n){let f=t;if(_i(f)&&n.has(f))return n.get(f);let c={...i};if(_i(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(_i(y)&&_i(w))c[l]=ou(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=pu(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function Zc(i,t,r="replace"){return vu(i,t,{arrayMergeMode:r==="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 r=0;r<i.length;r++)if(!Mc(i[r],t[r]))return!1;return!0}if(_i(i)&&_i(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!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,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;if(f){let u=Yr.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 Or(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Or(i,Error("Configuration must export a valid object"),"unknown");let B={config:Zc(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Yr.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Rt.configLoad(i,u):Rt.configLoad(i,Error(String(u)))}};if(l)return Hr.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(Rc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return Pu(async()=>{return cf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!cf(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=Rc(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Rc(i,l);if(await this.checkFileAccess(y))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!cf(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class vc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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 Hr.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,r){try{if(!HE(t))throw new Gr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Gr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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:lh},{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:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)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,r){let{name:n="",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(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(mi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw Rt.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?Qr(i,f,l):f,h=this.getLocalDirectories(r,n);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,r,n,f,c){if(!i)return null;let l=c?Qr(i,r,f):r,y=[mi(cr(),".config",i),mi(cr(),".config"),cr()];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:n,verbose:f});if(h){if(f)gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?Qr(i,n,c):n;try{let w=mi(r,"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)gi.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)gi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Qr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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 Rt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return Yr.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);Yr.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,mi(i,"config"),mi(i,".config"),t?mi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(mi(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[mi(cr(),".config",i),mi(cr(),".config"),cr()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function Fu(i){let r=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return r||n}async function WY(i){return At.loadConfig({...i,__strictErrorHandling:!0})}async function ih(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await At.loadConfig(i);else n=await At.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",c=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)gi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let y=r?{...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(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Fu(r)))return(await At.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}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"&&Fu(t)))return(await At.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function SY(i,t,r="replace"){let n=new Qf;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Qr(i,t,r=!1){let n=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 aY(i){let t=mi(zt.cwd(),i.configDir),r=mi(zt.cwd(),i.generatedDir),n=mi(r,"config-types.ts");if(!zc(lu(n)))YE(lu(n),{recursive:!0,mode:511});let f=zc(t)?BE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${rB}
|
|
101
|
+
`;return r}}function jY(i,t){let r=nh("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function pu(i,t,r={}){return ih(i,t,r,new WeakMap)}function ih(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return th(i,t,f,n);if(!Mi(t)||!Mi(i))return t;return XY(i,t,r,n)}function th(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return RY(i,t);case"smart":return NY(i,t,n);default:return t}return t}function RY(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Oc(f,n)))r.push(n);return r}function NY(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Mi(t[0])&&Mi(i[0]))return WY(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function WY(i,t,r){let n=[...t];for(let f of i){if(!Mi(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((u)=>Mi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function XY(i,t,r,n){let f=t;if(Mi(f)&&n.has(f))return n.get(f);let c={...i};if(Mi(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Mi(y)&&Mi(w))c[l]=ih(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=th(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function vc(i,t,r="replace"){return pu(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Oc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Oc(i[r],t[r]))return!1;return!0}if(Mi(i)&&Mi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Oc(i[f],t[f]))return!1}return!0}return!1}function Mi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Mf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;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(!lf(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new Qr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Qr(i,Error("Configuration must export a valid object"),"unknown");let B={config:vc(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)$r.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 Or.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(Nc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return vu(async()=>{return lf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!lf(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=Nc(i,`${c}${l}`);if(await this.checkFileAccess(y))n.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))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!lf(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class oc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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 Or.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,r){try{if(!gE(t))throw new Mr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Mr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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:wh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class pc{fileLoader=new Mf;envProcessor=new Qf;validator=new oc;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)xi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw xi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||It.cwd(),A=[],T=await this.loadLocalConfiguration(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Ci($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw Nt.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?_r(i,f,l):f,h=this.getLocalDirectories(r,n);for(let $ of h){if(l)xi.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)xi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,r,n,f,c){if(!i)return null;let l=c?_r(i,r,f):r,y=[Ci(tr(),".config",i),Ci(tr(),".config"),tr()];for(let w of y){if(f)xi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:f});if(h){if(f)xi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?_r(i,n,c):n;try{let w=Ci(r,"package.json");if(!Qc(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)xi.success(`Configuration loaded from package.json: ${$}`);return{config:vc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)xi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:_r(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return $r.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);$r.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ci(i,"config"),Ci(i,".config"),t?Ci(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ci(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ci(tr(),".config",i),Ci(tr(),".config"),tr()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function Iu(i){let r=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return r||n}async function SY(i){return Tt.loadConfig({...i,__strictErrorHandling:!0})}async function rh(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await Tt.loadConfig(i);else n=await Tt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",c=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)xi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let y=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await Tt.applyEnvironmentVariables(y.name||"",t,!0,y.verbose||!1))?.config??t;return t}}async function aY(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await Tt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Iu(r)))return(await Tt.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await Tt.loadConfig({...i,cwd:i.cwd||It.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Iu(t)))return(await Tt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function JY(i,t,r="replace"){let n=new Mf;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function _r(i,t,r=!1){let n=new Qf,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=It.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 FY(i){let t=Ci(It.cwd(),i.configDir),r=Ci(It.cwd(),i.generatedDir),n=Ci(r,"config-types.ts");if(!Qc(wu(n)))eE(wu(n),{recursive:!0,mode:511});let f=Qc(t)?mE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${fB}
|
|
102
102
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
103
|
-
`;
|
|
104
|
-
${f.map((u)=>{let h=
|
|
103
|
+
`;CE(n,c,{mode:438})}function KY(i){let t=null,r=null,n=()=>{if(!r)r=rh(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)xi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return n(),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 IY(i){let t=Nu(xE.cwd(),i?.configDir||"./config");function r(){if(!sE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=LE(t).filter((w)=>f.has(Wc(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=Wc(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=Wc($).toLowerCase();if(c.indexOf(h)<c.indexOf(A))y.set(w,u)}return Array.from(y.entries()).map(([w,u])=>({base:w,file:u})).sort((w,u)=>w.base.localeCompare(u.base))}function n(){let f=r(),c=f.map((u)=>u.base),l=c.length?c.map((u)=>`'${u}'`).join(" | "):"string",y=f.length?`{
|
|
104
|
+
${f.map((u)=>{let h=Nu(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
|
|
105
105
|
`)}
|
|
106
106
|
}`:"Record<string, any>";return`export type ConfigNames = ${l}
|
|
107
107
|
export type ConfigByName = ${y}
|
|
108
108
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
109
109
|
export type ConfigOf = Config
|
|
110
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var th,Yr,Hr,rh,IY,KY,Iu,Ef,Oc,$i,k,_Y,Ku,zY,_u,QY,MY,ac,OY,zu,Qu,Jc,GY,HY,qY,sY,Yf,nh,gY,Ai,LY,xY,Mu,Bf,Gc,ni,M,kY,Ou,VY,Gu,dY,DY,Fc,bY,Hu,qu,PY,Ic,ZY,vY,oY,pY,iB,ef,fh,tB,rB="0.15.6",Si,af,Or,Hc,qc,Jf,sc,gc,Gr,Lc,xc,Rt,ch,lh,gi,At,yh,wh,nB=nY(async()=>{th=import.meta.require,Yr=new dc,Hr=new Dc,rh={createKey:fY,isEquivalent:cY,estimateMemoryUsage:lY},IY=jf(Qc.cwd(),"config"),KY=jf(Qc.cwd(),"src/generated"),Iu=Uf.env.CLARITY_LOG_DIR||UE(uY(),"logs"),Ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Iu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Oc=await hY(),$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,_Y=$i.red,Ku=$i.green,zY=$i.yellow,_u=$i.blue,QY=$i.magenta,MY=$i.cyan,ac=$i.white,OY=$i.gray,zu=$i.bgRed,Qu=$i.bgYellow,Jc=$i.bold,GY=$i.dim,HY=$i.italic,qY=$i.underline,sY=$i.reset,Yf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nh={debug:"\uD83D\uDD0D",info:_u("ℹ"),success:Ku("✓"),warning:Qu(ac(Jc(" WARN "))),error:zu(ac(Jc(" ERROR ")))},gY=new Wf("stacks"),Ai=new Wf("bunfig",{showTags:!0}),LY=ei(Mr.cwd(),"config"),xY=ei(Mr.cwd(),"src/generated"),Mu=Cf.env.CLARITY_LOG_DIR||mE(EY(),"logs"),Bf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mu,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 YY(),ni={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=ni,kY=ni.red,Ou=ni.green,VY=ni.yellow,Gu=ni.blue,dY=ni.magenta,DY=ni.cyan,Fc=ni.white,bY=ni.gray,Hu=ni.bgRed,qu=ni.bgYellow,PY=ni.bgGray,Ic=ni.bold,ZY=ni.dim,vY=ni.italic,oY=ni.underline,pY=ni.strikethrough,iB=ni.reset,ef={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fh={debug:"\uD83D\uDD0D",info:Gu("ℹ"),success:Ou("✓"),warning:qu(Fc(Ic(" WARN "))),error:Hu(Fc(Ic(" ERROR ")))},tB=new Sf("stacks"),Si=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},af=class extends Si{code="CONFIG_NOT_FOUND";constructor(t,r,n){let f=n?` or alias "${n}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Or=class extends Si{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Hc=class extends Si{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},qc=class extends Si{code="CONFIG_MERGE_ERROR";constructor(t,r,n,f){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:f,originalError:n.name,originalMessage:n.message});this.cause=n}},Jf=class extends Si{code="ENV_VAR_ERROR";constructor(t,r,n,f){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:f})}},sc=class extends Si{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},gc=class extends Si{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Gr=class extends Si{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Lc=class extends Si{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,f){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:f})}},xc=class extends Si{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Rt={configNotFound(i,t,r){return new af(i,t,r)},configLoad(i,t,r){return new Or(i,t,r)},configValidation(i,t,r){return new Hc(i,t,r)},configMerge(i,t,r,n){return new qc(i,t,r,n)},envVar(i,t,r,n){return new Jf(i,t,r,n)},fileSystem(i,t,r){return new sc(i,t,r)},typeGeneration(i,t,r){return new gc(i,t,r)},schemaValidation(i,t,r){return new Gr(i,t,r)},browserConfig(i,t,r,n){return new Lc(i,t,r,n)},plugin(i,t,r){return new xc(i,t,r)}},ch={replace:"replace",concat:"concat",smart:"smart"},lh=/^https?:\/\//,gi=new Sf("bunfig",{showTags:!0}),At=new oc,yh=mi(zt.cwd(),"config"),wh=mi(zt.cwd(),"src/generated")});function fB(i,t={}){let r=Rf.cwd();while(r.includes("storage"))r=Ru(r,"..");let n=Ru(r,i||"");if(t?.relative)return xE(Rf.cwd(),n);return n}var cB=Rf.env.CLARITY_LOG_DIR||LE(fB(),"logs"),uh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:cB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ff={...uh},LR=(async()=>{try{let{loadConfig:i}=await nB().then(()=>du),t=await i({name:"clarity",alias:"logging",defaultConfig:uh,cwd:Rf.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 lB(){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 hh{async format(i){let t=await lB(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Er.pid,hostname:t(),environment:Er.env.NODE_ENV||"development",platform:Er.platform,version:Er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Er.env.NODE_ENV||Er.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,xR=li.red,yB=li.green,kR=li.yellow,wB=li.blue,VR=li.magenta,dR=li.cyan,su=li.white,DR=li.gray,uB=li.bgRed,hB=li.bgYellow,bR=li.bgGray,gu=li.bold,PR=li.dim,ZR=li.italic,vR=li.underline,oR=li.strikethrough,pR=li.reset,Kc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$B={debug:"\uD83D\uDD0D",info:wB("ℹ"),success:yB("✓"),warning:hB(su(gu(" WARN "))),error:uB(su(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 hh,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 r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}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},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await bE(this.config.logDirectory,Su.F_OK|Su.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await PE(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"}),Wu(f),f!==void 0)Xc(f),f=void 0;if((await Ar(this.currentLogFile)).size===0){if(await Sc(this.currentLogFile,w,{flag:"w",mode:420}),(await Ar(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Xc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Tr(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 Tr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Tr(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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,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 Wc(16).toString("hex")}generateKey(){return Wc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Wc(16),n=kE("aes-256-gcm",t,r),f=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=yt.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Ju(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(yt.from(yt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await Ar(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await 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=`${r}.${l}`;if(await Ar(r).catch(()=>null))try{if(await au(r,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=`${r}.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=r.replace(/\.log$/,`-${f}.log`);if(await Ar(r).catch(()=>null))await au(r,c)}if(this.currentLogFile=n,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(Tr(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=Nu(i),n=dE(t),f=Ju();await oE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),lf(this.currentLogFile))try{let i=Xu(this.currentLogFile,"r+");Wu(i),Xc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await yf(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await wf(Tr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?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:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=z.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=G.underline(G.blue(n)),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,(r,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>G.strikethrough(n)),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 r=z.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ZE(t)||t.startsWith("./")||t.startsWith("../"))t=vE(t);else return null;return lf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":$B[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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!
|
|
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:n(),loader:"ts"}})}}}var nh,$r,Or,fh,_Y,zY,_u,Yf,Gc,Ai,k,QY,zu,MY,Qu,OY,GY,Jc,HY,Mu,Ou,Fc,qY,gY,sY,LY,Bf,ch,xY,Ti,kY,VY,Gu,ef,Hc,ri,M,dY,Hu,DY,qu,bY,PY,Kc,ZY,gu,su,vY,Ic,oY,pY,iB,tB,rB,mf,lh,nB,fB="0.15.6",Ji,Jf,Qr,qc,gc,Ff,sc,Lc,Mr,xc,kc,Nt,yh,wh,xi,Tt,uh,hh,cB=cY(async()=>{nh=import.meta.require,$r=new Dc,Or=new bc,fh={createKey:lY,isEquivalent:yY,estimateMemoryUsage:wY},_Y=Rf(Mc.cwd(),"config"),zY=Rf(Mc.cwd(),"src/generated"),_u=jf.env.CLARITY_LOG_DIR||RE($Y(),"logs"),Yf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_u,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Gc=await AY(),Ai={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},k=Ai,QY=Ai.red,zu=Ai.green,MY=Ai.yellow,Qu=Ai.blue,OY=Ai.magenta,GY=Ai.cyan,Jc=Ai.white,HY=Ai.gray,Mu=Ai.bgRed,Ou=Ai.bgYellow,Fc=Ai.bold,qY=Ai.dim,gY=Ai.italic,sY=Ai.underline,LY=Ai.reset,Bf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ch={debug:"\uD83D\uDD0D",info:Qu("ℹ"),success:zu("✓"),warning:Ou(Jc(Fc(" WARN "))),error:Mu(Jc(Fc(" ERROR ")))},xY=new Xf("stacks"),Ti=new Xf("bunfig",{showTags:!0}),kY=mi(zr.cwd(),"config"),VY=mi(zr.cwd(),"src/generated"),Gu=Uf.env.CLARITY_LOG_DIR||UE(BY(),"logs"),ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Hc=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,dY=ri.red,Hu=ri.green,DY=ri.yellow,qu=ri.blue,bY=ri.magenta,PY=ri.cyan,Kc=ri.white,ZY=ri.gray,gu=ri.bgRed,su=ri.bgYellow,vY=ri.bgGray,Ic=ri.bold,oY=ri.dim,pY=ri.italic,iB=ri.underline,tB=ri.strikethrough,rB=ri.reset,mf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lh={debug:"\uD83D\uDD0D",info:qu("ℹ"),success:Hu("✓"),warning:su(Kc(Ic(" WARN "))),error:gu(Kc(Ic(" ERROR ")))},nB=new af("stacks"),Ji=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Jf=class extends Ji{code="CONFIG_NOT_FOUND";constructor(t,r,n){let f=n?` or alias "${n}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Qr=class extends Ji{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qc=class extends Ji{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},gc=class extends Ji{code="CONFIG_MERGE_ERROR";constructor(t,r,n,f){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:f,originalError:n.name,originalMessage:n.message});this.cause=n}},Ff=class extends Ji{code="ENV_VAR_ERROR";constructor(t,r,n,f){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:f})}},sc=class extends Ji{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Lc=class extends Ji{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Mr=class extends Ji{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},xc=class extends Ji{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,f){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:f})}},kc=class extends Ji{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Nt={configNotFound(i,t,r){return new Jf(i,t,r)},configLoad(i,t,r){return new Qr(i,t,r)},configValidation(i,t,r){return new qc(i,t,r)},configMerge(i,t,r,n){return new gc(i,t,r,n)},envVar(i,t,r,n){return new Ff(i,t,r,n)},fileSystem(i,t,r){return new sc(i,t,r)},typeGeneration(i,t,r){return new Lc(i,t,r)},schemaValidation(i,t,r){return new Mr(i,t,r)},browserConfig(i,t,r,n){return new xc(i,t,r,n)},plugin(i,t,r){return new kc(i,t,r)}},yh={replace:"replace",concat:"concat",smart:"smart"},wh=/^https?:\/\//,xi=new af("bunfig",{showTags:!0}),Tt=new pc,uh=Ci(It.cwd(),"config"),hh=Ci(It.cwd(),"src/generated")});function lB(i,t={}){let r=Nf.cwd();while(r.includes("storage"))r=Wu(r,"..");let n=Wu(r,i||"");if(t?.relative)return VE(Nf.cwd(),n);return n}var yB=Nf.env.CLARITY_LOG_DIR||kE(lB(),"logs"),$h={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Kf={...$h},kR=(async()=>{try{let{loadConfig:i}=await cB().then(()=>bu),t=await i({name:"clarity",alias:"logging",defaultConfig:$h,cwd:Nf.cwd()});if(t)Object.assign(Kf,t)}catch{}return Kf})();function ni(){if(At.env.NODE_ENV==="test"||At.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wB(){if(At.env.NODE_ENV==="test"||At.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof At<"u"){let i=At.type;if(i==="renderer"||i==="worker")return!1;return!!(At.versions&&(At.versions.node||At.versions.bun))}return!1}class Ah{async format(i){let t=await wB(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:hr.pid,hostname:t(),environment:hr.env.NODE_ENV||"development",platform:hr.platform,version:hr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hr.env.NODE_ENV||hr.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"},G=ci,VR=ci.red,uB=ci.green,dR=ci.yellow,hB=ci.blue,DR=ci.magenta,bR=ci.cyan,Lu=ci.white,PR=ci.gray,$B=ci.bgRed,AB=ci.bgYellow,ZR=ci.bgGray,xu=ci.bold,vR=ci.dim,oR=ci.italic,pR=ci.underline,iN=ci.strikethrough,tN=ci.reset,_c={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},TB={debug:"\uD83D\uDD0D",info:hB("ℹ"),success:uB("✓"),warning:AB(Lu(xu(" WARN "))),error:$B(Lu(xu(" ERROR ")))};class Of{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={...Kf},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ah,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),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},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{..._c,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{..._c};return{..._c,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Kf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await ZE(this.config.logDirectory,Ju.F_OK|Ju.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await vE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:wt.from(i);try{if(!yf(this.currentLogFile))await ac(this.currentLogFile,"",{mode:420});if(f=au(this.currentLogFile,"a",420),PE(f,w,{flag:"a"}),Su(f),f!==void 0)Sc(f),f=void 0;if((await wr(this.currentLogFile)).size===0){if(await ac(this.currentLogFile,w,{flag:"w",mode:420}),(await wr(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{Sc(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(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ur(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 ur(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ur(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,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(),r=Xc(16),n=dE("aes-256-gcm",t,r),f=wt.isBuffer(i)?i:wt.from(i,"utf8"),c=n.update(f),l=n.final(),y=c.length+l.length,w=n.getAuthTag(),u=wt.allocUnsafe(16+y+16);return r.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Ku(),f=[];n.on("data",(c)=>f.push(c)),n.on("end",()=>t(wt.from(wt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await wr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wf(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=`${r}.${l}`;if(await wr(r).catch(()=>null))try{if(await Fu(r,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await uf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await ac(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=r.replace(/\.log$/,`-${f}.log`);if(await wr(r).catch(()=>null))await Fu(r,c)}if(this.currentLogFile=n,t.maxFiles){let c=(await wf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await uf(ur(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=Xu(i),n=bE(t),f=Ku();await iY(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),yf(this.currentLogFile))try{let i=au(this.currentLogFile,"r+");Su(i),Sc(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 wf(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await uf(ur(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())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:r="",tag:n="",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(r)T.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)T.push(n.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=z.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${r} ${f}`;else if(c==="info"||c==="success")u=`${r} ${n} ${f}`;else u=`${r} ${n} ${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 r=/%([sdijfo%])/g,n=0,f=i.replace(r,(c,l)=>{if(l==="%")return"%";if(n>=t.length)return c;let y=t[n++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(n<t.length)f+=` ${t.slice(n).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,(r,n,f)=>{let c=G.underline(G.blue(n)),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,(r,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>G.strikethrough(n)),t}supportsHyperlinks(){if(ni())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 r=z.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(oE(t)||t.startsWith("./")||t.startsWith("../"))t=pE(t);else return null;return yf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),c=this.formatFileTimestamp(n),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,r);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":TB[i],A=this.options.showTags!==!1&&this.name?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 e)if(E.trim()&&!E.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
112
112
|
`;if(y)h+=`${y}
|
|
113
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
114
|
-
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!
|
|
116
|
-
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:G.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(h),showTimestamp:!1}))}else if(!
|
|
117
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(
|
|
113
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&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()&&!ni()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ni()&&z.stdout.isTTY)z.stdout.write(`
|
|
114
|
+
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:r,message:`${G.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(r)u+=` ${JSON.stringify(r)}`;if(u+=`
|
|
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}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new Of(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!yf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=wt.isBuffer(i)?i:wt.from(i,"base64"),f=n.subarray(0,16),c=n.subarray(n.length-16),l=n.subarray(16,n.length-16),y=DE("aes-256-gcm",r,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=wt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ni()}isServerMode(){return!ni()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
116
|
+
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:r,message:G.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(h),showTimestamp:!1}))}else if(!ni())console.error(`${n} ${this.environment}.INFO: [BOX] ${c}`);let l=`${n} ${this.environment}.INFO: [BOX] ${c}
|
|
117
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();z.stdin.removeListener("data",r);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",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(r=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)r+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${u}${w} ${G.cyan(n)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
118
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 r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,c=G.green("━".repeat(n)),l=G.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${r}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===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,e=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${e}`,z.stdout.write(i.lastRenderedLine),t)z.stdout.write(`
|
|
119
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||
|
|
119
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!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(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await wf(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let c=ur(this.config.logDirectory,n);if(i.before)try{if((await wr(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}r.push(c)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await uf(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var rN=new Of("stacks");class ki extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Th extends ki{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class If extends ki{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Eh extends ki{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Yh extends ki{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class il extends ki{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class Bh extends ki{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class eh extends ki{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class _f extends ki{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class mh extends ki{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class Ch extends ki{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Ar={configNotFound(i,t,r){return new Th(i,t,r)},configLoad(i,t,r){return new If(i,t,r)},configValidation(i,t,r){return new Eh(i,t,r)},configMerge(i,t,r,n){return new Yh(i,t,r,n)},envVar(i,t,r,n){return new il(i,t,r,n)},fileSystem(i,t,r){return new Bh(i,t,r)},typeGeneration(i,t,r){return new eh(i,t,r)},schemaValidation(i,t,r){return new _f(i,t,r)},browserConfig(i,t,r,n){return new mh(i,t,r,n)},plugin(i,t,r){return new Ch(i,t,r)}};async function EB(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=r;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===r||!f(l))break;if(n>0)await new Promise((u)=>setTimeout(u,n))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class tl{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=r,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return dc.track("applyEnvironmentVariables",u,{configName:i});return u()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${y.join("_")}`,u=n.useBackwardCompatibility?`${r}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,r,n);else{let h=$f.env[w]||(u?$f.env[u]:void 0);if(h!==void 0){if(n.verbose){let $=$f.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,n.customParsers,n.configName)}catch($){if($ instanceof il)throw $;throw Ar.envVar(w,h,typeof c,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[c,l]of Object.entries(n))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Ar.envVar(r,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries($f.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,c=n||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,r,n){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${r}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,r,n);else n.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
120
120
|
|
|
121
121
|
`;for(let n of i)r+=`${n.key}
|
|
122
122
|
`,r+=` Type: ${n.type}
|
|
@@ -128,63 +128,63 @@ export type ConfigOf = Config
|
|
|
128
128
|
`;r+=`| Variable | Type | Description | Example |
|
|
129
129
|
`,r+=`|----------|------|-------------|----------|
|
|
130
130
|
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
131
|
-
`;return r}}function TB(i,t,r={}){return mh(i,t,r,new WeakMap)}function mh(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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,n);if(!zi(t)||!zi(i))return t;return eB(i,t,r,n)}function Ch(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return EB(i,t);case"smart":return YB(i,t,n);default:return t}return t}function EB(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>kc(f,n)))r.push(n);return r}function YB(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return BB(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function BB(i,t,r){let n=[...t];for(let f of i){if(!zi(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((u)=>zi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function eB(i,t,r,n){let f=t;if(zi(f)&&n.has(f))return n.get(f);let c={...i};if(zi(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(zi(y)&&zi(w))c[l]=mh(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=Ch(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function Uh(i,t,r="replace"){return TB(i,t,{arrayMergeMode:r==="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 r=0;r<i.length;r++)if(!kc(i[r],t[r]))return!1;return!0}if(zi(i)&&zi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!kc(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class jh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;if(f){let u=mf.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:Uh(t,$,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)mf.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Br.configLoad(i,u):Br.configLoad(i,Error(String(u)))}};if(l)return Vc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(_c(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of n){if(!c)continue;if(r.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)r.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return r.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return AB(async()=>{return $f(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!$f(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=_c(i,`${c}${l}`);if(await this.checkFileAccess(y))n.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))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!$f(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var CB=/^https?:\/\//;class Rh{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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,r){try{if(!mB(t))throw new Kf(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Kf(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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 UB(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Nh{fileLoader=new jh;envProcessor=new il;validator=new Rh;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)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,r){let{name:n="",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(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Ki($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw Br.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${UB(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?Af(i,f,l):f,h=this.getLocalDirectories(r,n);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,r,n,f,c){if(!i)return null;let l=c?Af(i,r,f):r,y=[Ki(fr(),".config",i),Ki(fr(),".config"),fr()];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:n,verbose:f});if(h){if(f)wt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?Af(i,n,c):n;try{let w=Ki(r,"package.json");if(!TE(w))return null;let u={};try{u=JSON.parse(EE(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:Uh(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,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Af(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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 Br.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return mf.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);mf.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ki(i,"config"),Ki(i,".config"),t?Ki(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ki(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ki(fr(),".config",i),Ki(fr(),".config"),fr()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var cN=new Nh;function Af(i,t,r=!1){let n=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 lN=Ki(_f.cwd(),"config"),yN=Ki(_f.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",jB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:rl(tl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:rl(tl(),".stacks","ssl","stacks.localhost.crt"),keyPath:rl(tl(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Wh=jB;import{execSync as qr}from"node:child_process";import{homedir as XB}from"node:os";import{join as SB}from"node:path";function RB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Qt(i){try{return vn(i)}catch{return null}}function nl(i){try{return hc(i)||null}catch{return null}}function fl(i,t){try{return t.every((r)=>Ac(i,r))}catch{return!1}}function NB(i,t,r=443){return $c(i,t,r)}function WB(i){let t=[];for(let r of i.split(`
|
|
132
|
-
`)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)t.push(n[1].toUpperCase())}return t}var
|
|
133
|
-
`)){let c=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)n.push(c[1].toUpperCase())}return n}function
|
|
134
|
-
`))if(c.toUpperCase().includes("SHA-256")){if(c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return Y("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}function
|
|
131
|
+
`;return r}}function YB(i,t,r={}){return Uh(i,t,r,new WeakMap)}function Uh(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=r;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 jh(i,t,f,n);if(!Oi(t)||!Oi(i))return t;return CB(i,t,r,n)}function jh(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return BB(i,t);case"smart":return eB(i,t,n);default:return t}return t}function BB(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Vc(f,n)))r.push(n);return r}function eB(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Oi(t[0])&&Oi(i[0]))return mB(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function mB(i,t,r){let n=[...t];for(let f of i){if(!Oi(f)){n.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(n.find((u)=>Oi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)n.push(f)}return n}function CB(i,t,r,n){let f=t;if(Oi(f)&&n.has(f))return n.get(f);let c={...i};if(Oi(f))n.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(r.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Oi(y)&&Oi(w))c[l]=Uh(w,y,r,n);else if(Array.isArray(y)||Array.isArray(w))c[l]=jh(w,y,r.arrayMergeMode||"smart",n);else c[l]=y}return c}function Rh(i,t,r="replace"){return YB(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Vc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Vc(i[r],t[r]))return!1;return!0}if(Oi(i)&&Oi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Vc(i[f],t[f]))return!1}return!0}return!1}function Oi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Nh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=r;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(!Af(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:Rh(t,$,n),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?Ar.configLoad(i,u):Ar.configLoad(i,Error(String(u)))}};if(l)return dc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let c of n)for(let l of this.extensions)f.push(zc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of n){if(!c)continue;if(r.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)r.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return r.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return EB(async()=>{return Af(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!Af(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let c of f)for(let l of this.extensions){let y=zc(i,`${c}${l}`);if(await this.checkFileAccess(y))n.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=zc(i,l);if(await this.checkFileAccess(y))n.push(y)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!Af(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var jB=/^https?:\/\//;class Wh{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=r,u=async()=>{let h=[],$=[],A={stopOnFirstError:n,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 dc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,r){try{if(!UB(t))throw new _f(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new _f(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(n.push({path:r,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,n,f,c),c.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(n.push({path:r?`${r}.${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=r?`${r}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,n,f,c),c.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(n.push(...y),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,c,l]=n;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:jB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ut=new Of("bunfig",{showTags:!0});function RB(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Xh{fileLoader=new Nh;envProcessor=new tl;validator=new Wh;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:c,...l}=i;try{if(r?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,r)}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(r?.enabled&&y)this.cacheResult(l.name||"",y,r,l);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)ut.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw ut.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||zf.cwd(),A=[],T=await this.loadLocalConfiguration(n,f,$,l,y,u,h,w,r);if(T)return A.push(...this.getLocalSearchPaths(n,f,$,l)),this.finalizeResult(T,A,w,n,h);let e=await this.loadHomeConfiguration(n,f,y,u,h,w);if(e)return A.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(e,A,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,$,y,u,h,w);if(E)return A.push(Qi($,"package.json")),this.finalizeResult(E,A,w,n,h);if(A.push(...this.getAllSearchPaths(n,f,$,l)),t)throw Ar.configNotFound(n,A,f);return{...await this.applyEnvironmentVariables(n,y,w,h),warnings:[`No configuration file found for "${n}"${RB(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,c,l,y,w){let u=y?Tf(i,f,l):f,h=this.getLocalDirectories(r,n);for(let $ of h){if(l)ut.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)ut.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,r,n,f,c){if(!i)return null;let l=c?Tf(i,r,f):r,y=[Qi(ir(),".config",i),Qi(ir(),".config"),ir()];for(let w of y){if(f)ut.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:n,verbose:f});if(h){if(f)ut.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,c,l){let y=l?Tf(i,n,c):n;try{let w=Qi(r,"package.json");if(!YE(w))return null;let u={};try{u=JSON.parse(BE(w,"utf8"))}catch(A){if(c)ut.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)ut.success(`Configuration loaded from package.json: ${$}`);return{config:Rh(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)ut.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Tf(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let c=r(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 Ar.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return Cf.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);Cf.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Qi(i,"config"),Qi(i,".config"),t?Qi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Qi(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let r=[Qi(ir(),".config",i),Qi(ir(),".config"),ir()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var yN=new Xh;function Tf(i,t,r=!1){let n=new tl,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=zf.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 wN=Qi(zf.cwd(),"config"),uN=Qi(zf.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",NB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:nl(rl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:nl(rl(),".stacks","ssl","stacks.localhost.crt"),keyPath:nl(rl(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Sh=NB;import{execSync as Gr}from"node:child_process";import{homedir as aB}from"node:os";import{join as JB}from"node:path";function WB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function _t(i){try{return on(i)}catch{return null}}function fl(i){try{return $c(i)||null}catch{return null}}function cl(i,t){try{return t.every((r)=>Tc(i,r))}catch{return!1}}function XB(i,t,r=443){return Ac(i,t,r)}function SB(i){let t=[];for(let r of i.split(`
|
|
132
|
+
`)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)t.push(n[1].toUpperCase())}return t}var Pi="-d -r trustRoot -p ssl -p basic",Et="/Library/Keychains/System.keychain",ll="rpx.localhost";function Hr(){return JB(aB(),"Library/Keychains/login.keychain-db")}function yl(){return[Et,Hr()]}function ah(i,t=ll){let r=Gr(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let f of r.split(`
|
|
133
|
+
`)){let c=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)n.push(c[1].toUpperCase())}return n}function Gf(i){if(process.platform!=="darwin")return;let t=_t(i.caPath);if(!t)return;let r=i.commonName??ll,n=i.keychains??yl();for(let f of n)for(let c of ah(f,r)){if(c===t)continue;try{if(f.startsWith("/Library"))Wt(`security delete-certificate -Z ${c} "${f}"`);else Gr(`security delete-certificate -Z ${c} "${f}"`,{stdio:"ignore"});Y("ssl",`Removed stale Root CA ${c} from ${f}`,i.verbose)}catch{}}}function qr(i,t,r){if(process.platform!=="darwin")return gr(i,r);try{let f=Gr(`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"}`,r?.verbose),f}catch{return!1}}function gr(i,t){let r=_t(i);if(!r)return!1;for(let n of yl())try{let f=Gr(`security find-certificate -a -Z "${n}" 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()===r)return Y("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}function wl(i,t){if(process.platform!=="darwin")return!1;let r=t.serverName;Gf({caPath:i,commonName:t.commonName,verbose:t.verbose});let n=Hr();try{Gr(`security add-trusted-cert ${Pi} -k "${n}" "${i}"`,{stdio:"ignore"})}catch{}try{Wt(`security add-trusted-cert ${Pi} -k ${Et} "${i}"`)}catch{return!1}return qr(i,r,{verbose:t.verbose})||gr(i,{verbose:t.verbose})}var Xt=null,Al=D(Tr(),".stacks","ssl","rpx.localhost.crt");function Qh(i,t){return[...new Set(i.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function Mh(i,t,r){let n=D(Tr(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:Al,keyPath:D(n,"rpx.localhost.key"),caCertPath:D(n,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:f.map((c)=>({from:"localhost:1",to:c,cleanUrls:!1}))}}var FB="rpx-root-ca.crt",KB="rpx-root-ca.key";function Tl(i){return{caCertPath:D(i,FB),caKeyPath:D(i,KB)}}function ON(i){return{certPath:D(i,"rpx.localhost.crt"),keyPath:D(i,"rpx.localhost.key"),caCertPath:D(i,"rpx.localhost.ca.crt"),rootCA:Tl(i)}}async function IB(i,t){try{let[r,n]=await Promise.all([Z.readFile(i.caCertPath,"utf8"),Z.readFile(i.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return Y("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:n}}catch(r){return Y("ssl",`No existing Root CA at ${i.caCertPath} (${r.code||r}), will create one`,t),null}}function Jh(i){let t=new Set;t.add(i);let r=i.split(".");if(r.length>=3){let n=r[r.length-1],f=r[r.length-2],c=new Set(["co","com","org","net","ac","gov","edu"]);if(!(r.length===3&&n.length===2&&c.has(f)))t.add(`*.${r.slice(1).join(".")}`)}return Array.from(t)}function Oh(i){let r=$l(i).replace(/\*/g,"wildcard"),n=D(Tr(),".stacks","ssl"),f=n;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:n,{caCertPath:i.https.caCertPath||D(f,`${r}.ca.crt`),certPath:i.https.certPath||D(f,`${r}.crt`),keyPath:i.https.keyPath||D(f,`${r}.key`)};return{caCertPath:D(f,`${r}.ca.crt`),certPath:D(f,`${r}.crt`),keyPath:D(f,`${r}.key`)}}function Fh(i){let t=new Set;if(Hf(i))i.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";Jh(n).forEach((f)=>t.add(f))});else if(Ih(i)){let r=i.to||"rpx.localhost";Jh(r).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function GN(i){Y("ssl","Loading SSL configuration",i.verbose);let t={...Sh,...i};if(i.https=Bl(t),!i.https?.keyPath&&!i.https?.certPath)return Y("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let r=!i.https?.keyPath?"keyPath":"certPath";throw Y("ssl",`Invalid SSL configuration - missing ${r}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{Y("ssl","Reading SSL certificate files",i.verbose);let r=await Z.readFile(i.https?.keyPath,"utf8"),n=await Z.readFile(i.https?.certPath,"utf8");return Y("ssl","SSL configuration loaded successfully",i.verbose),{key:r,cert:n}}catch(r){return Y("ssl",`Failed to read certificates: ${r}`,i.verbose),null}}catch(r){throw Y("ssl",`SSL configuration error: ${r}`,i.verbose),r}}async function HN(i,t){if(Vi.platform==="darwin")return _B(i,t);if(Vi.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)n(!0);else r(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(c)=>{n(!c)})})})}catch{return!1}return!1}async function _B(i,t){if(Vi.platform!=="darwin")return!1;let r=t?.serverName??"rpx.localhost",n=t?.verbose??!1;try{if(qr(i,r,{verbose:n}))return Y("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return Y("ssl","Trusting Root CA for browsers (login + system keychains)",n),wl(i,{serverName:r,verbose:n})}catch{return!1}}async function Gh(i){if(Xt&&!i.forceRegenerate){Y("ssl","Using cached SSL configuration",i.verbose);return}El();let t=Hf(i)?i.proxies.map((h)=>h.to):[i.to];Y("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let r=Bl(i,i.verbose),n=r.basePath||D(Tr(),".stacks","ssl");await Z.mkdir(n,{recursive:!0});let f=Tl(n),c=await IB(f,i.verbose),l=!1;if(!c){if(i.verbose)a.info("Generating Root CA certificate (one-time)...");c=await uc(r);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)a.info(`Generating host certificate for: ${t.join(", ")}`);let y=await hc({...r,rootCA:{certificate:c.certificate,privateKey:c.privateKey}});try{await Promise.all([Z.writeFile(r.certPath,y.certificate),Z.writeFile(r.keyPath,y.privateKey),Z.writeFile(r.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 Hh(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(Y("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)a.success("Root CA is already trusted in system trust store");if(Xt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)a.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)a.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(Vi.platform==="darwin")try{Gf({caPath:f.caCertPath,verbose:i.verbose});let h=Hr();try{ul(`security add-trusted-cert ${Pi} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Wt(`security add-trusted-cert ${Pi} -k ${Et} "${f.caCertPath}"`),i.verbose)a.success("Successfully added Root CA to system trust store");u=!0;let $=D(n,"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.
|
|
138
138
|
if [ -n "$SUDO_PASSWORD" ]
|
|
139
139
|
then
|
|
140
140
|
printf '%s
|
|
141
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
141
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pi} -k ${Et} "${f.caCertPath}"
|
|
142
142
|
else
|
|
143
|
-
sudo security add-trusted-cert ${
|
|
143
|
+
sudo security add-trusted-cert ${Pi} -k ${Et} "${f.caCertPath}"
|
|
144
144
|
fi
|
|
145
145
|
echo "Root CA trusted! Please restart your browser."
|
|
146
146
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
147
|
-
`;await Z.writeFile($,A,{mode:493})}catch(h){if(i.verbose)
|
|
147
|
+
`;await Z.writeFile($,A,{mode:493})}catch(h){if(i.verbose)a.warn(`Could not add Root CA to trust store automatically: ${h}`);let $=D(n,"trust-rpx-cert.sh"),A=`#!/bin/bash
|
|
148
148
|
echo "Trusting RPX Root CA"
|
|
149
149
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
150
150
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
151
151
|
if [ -n "$SUDO_PASSWORD" ]
|
|
152
152
|
then
|
|
153
153
|
printf '%s
|
|
154
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
154
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pi} -k ${Et} "${f.caCertPath}"
|
|
155
155
|
else
|
|
156
|
-
sudo security add-trusted-cert ${
|
|
156
|
+
sudo security add-trusted-cert ${Pi} -k ${Et} "${f.caCertPath}"
|
|
157
157
|
fi
|
|
158
158
|
echo "Root CA trusted! Please restart your browser."
|
|
159
159
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
160
|
-
`;if(await Z.writeFile($,A,{mode:493}),i.verbose)
|
|
160
|
+
`;if(await Z.writeFile($,A,{mode:493}),i.verbose)a.info(`Created a trust helper script at: ${$}`),a.info(`If you're still having certificate issues, run: sh ${$}`)}else if(Vi.platform==="linux")try{let{exec:h}=await import("node:child_process"),$="/usr/local/share/ca-certificates/rpx",A=`
|
|
161
161
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
162
162
|
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
163
163
|
update-ca-certificates
|
|
164
164
|
echo "RPX Root CA installed. Please restart your browser."
|
|
165
|
-
`,T=D(
|
|
165
|
+
`,T=D(hl.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((e)=>{h(`sudo bash "${T}"`,(E)=>{if(E){if(i.verbose)a.warn(`Could not trust certificates: ${E}`);e(!1)}else{if(i.verbose)a.success("Successfully added certificates to system trust store");e(!0)}})}),await Z.unlink(T).catch(()=>{}),u=!0}catch(h){if(i.verbose)a.warn(`Failed to trust certificates: ${h}`)}else if(Vi.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(
|
|
173
|
-
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let f=n.indexOf(":");if(f<=0)continue;t.set(n.slice(0,f),n.slice(f+1))}return t}function
|
|
172
|
+
`,$=D(hl.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),ul(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)a.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)a.warn(`Could not trust certificate: ${h}`)}else try{await Ec(y,c.certificate,r),u=!0}catch(h){if(i.verbose)a.warn(`Could not add certificate to trust store: ${h}`)}if(Xt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)a.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)a.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),a.warn("This will bypass the warning and you should only need to do it once")}function El(){Xt=null}async function Yl(i){if(!i)return null;if(Xt)return Xt;let t=Bl(i);try{let[r,n,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(!r||!n)return Y("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let c="regenerateUntrustedCerts"in i,l=i.regenerateUntrustedCerts,y=c?l!==!1:!0;Y("ssl",`Trust check: hasFlag=${c}, flagValue=${l}, shouldCheckTrust=${y}`,i.verbose);let w=t.basePath||D(Tr(),".stacks","ssl"),u=Tl(w);if(!(y?await Hh(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(Hf(i))try{let{X509Certificate:e}=await import("node:crypto"),B=new e(A).subjectAltName||"",j=i.proxies.map((W)=>W.to).filter((W)=>!B.includes(`DNS:${W}`));if(j.length>0)return Y("ssl",`Certificate missing SANs for: ${j.join(", ")}, will regenerate`,i.verbose),null}catch(e){Y("ssl",`Could not verify cert SANs: ${e}`,i.verbose)}return Y("ssl","Successfully loaded existing certificates",i.verbose),Xt={key:$,cert:A,ca:T},Xt}catch(r){return Y("ssl",`Error checking existing certificates: ${r}`,i.verbose),null}}function Bl(i,t){let r=$l(i);Y("ssl",`Primary domain: ${r}`,t);let n=Oh(i),f=D(Tr(),".stacks","ssl");if(typeof i.https==="object"){let c=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,l={domain:r,hostCertCN:r,basePath:c,caCertPath:i.https.caCertPath||n.caCertPath,certPath:i.https.certPath||n.certPath,keyPath:i.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||r,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(Fh(i)).map((y)=>({type:2,value:y}))};if(Kh(i.https.rootCA))l.rootCA=i.https.rootCA;return l}return{domain:r,hostCertCN:r,basePath:f,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Fh(i)).map((c)=>({type:2,value:c}))}}async function qN(i,t){let r=Oh({to:i,verbose:t}),n=[r.caCertPath,r.certPath,r.keyPath];Y("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((f)=>_h(f,t)))}async function Hh(i,t){try{if(Y("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),Vi.platform==="darwin"){if(t?.serverName)return qr(i,t.serverName,{verbose:t?.verbose});return gr(i,{verbose:t?.verbose})}else if(Vi.platform==="win32")try{let r=fl(i)||"";if(!r)return Y("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(ul(n).toString().includes(r))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(r){return Y("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(Vi.platform==="linux")try{let r=_t(i);if(!r)return Y("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of n){let c;try{c=await Z.readdir(f)}catch{continue}for(let l of c){let y=_t(zh.join(f,l));if(y&&y===r)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(r){return Y("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return Y("ssl",`Platform ${Vi.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return Y("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}function zB(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 QB(i){return(Array.isArray(i)?i:[i]).map((r)=>{let n=typeof r==="string"?{url:r}:r;return{url:n.url,weight:n.weight&&n.weight>0?n.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function qh(i){return(Array.isArray(i)?i:[i]).map((r)=>typeof r==="string"?r:r.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 sh(i,t){return{upstreams:QB(i),strategy:t?.strategy??"round-robin",healthCheck:zB(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function MB(i){let t=i.upstreams.filter((r)=>r.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function OB(i,t){let r=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[r]}function GB(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((f,c)=>f+c.weight,0),n=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[n])n=f;return i.wrrCurrentWeights[n]-=r,t[n]}function HB(i){let t=i[0];for(let r=1;r<i.length;r++)if(i[r].activeConnections<t.activeConnections)t=i[r];return t}function Lh(i){let t=MB(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return GB(i,t);case"least-connections":return HB(t);case"round-robin":default:return OB(i,t)}}function qf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function sr(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function qB(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let r=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(r)?r:80}}async function gB(i,t){let{hostname:r,port:n}=qB(t.url),f=new AbortController,c=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${r}:${n}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),qf(i,t)}catch{sr(i,t)}finally{clearTimeout(c)}}function xh(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let r of i.upstreams)gB(i,r)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function el(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as Vh,timingSafeEqual as kh}from"node:crypto";import{readFileSync as sB}from"node:fs";var LB="/.well-known/acme-challenge/";function Lr(i,t){let r=Buffer.from(i,"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return kh(r,r),!1;return kh(r,n)}function xB(i,t){let r=(A)=>Vh("md5").update(A).digest(),n=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),c=r(Buffer.concat([n,f,n])),l=[n,Buffer.from("$apr1$","utf8"),f];for(let A=n.length;A>0;A-=16)l.push(c.subarray(0,Math.min(A,16)));for(let A=n.length;A>0;A>>=1)l.push(A&1?Buffer.from([0]):n.subarray(0,1));let y=r(Buffer.concat(l));for(let A=0;A<1000;A++){let T=[];if(T.push(A&1?n:y.subarray(0,16)),A%3)T.push(f);if(A%7)T.push(n);T.push(A&1?y.subarray(0,16):n),y=r(Buffer.concat(T))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",u=(A,T)=>{let e="",E=A;for(let B=0;B<T;B++)e+=w[E&63],E>>=6;return e},h=y,$="";return $+=u(h[0]<<16|h[6]<<8|h[12],4),$+=u(h[1]<<16|h[7]<<8|h[13],4),$+=u(h[2]<<16|h[8]<<8|h[14],4),$+=u(h[3]<<16|h[9]<<8|h[15],4),$+=u(h[4]<<16|h[10]<<8|h[5],4),$+=u(h[11],2),`$apr1$${t}$${$}`}function kB(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let n=t.split("$")[2]??"";return Lr(xB(i,n),t)}if(t.startsWith("{SHA}")){let r=Vh("sha1").update(i,"utf8").digest("base64");return Lr(`{SHA}${r}`,t)}return Lr(i,t)}function VB(i){let t=new Map;for(let r of i.split(`
|
|
173
|
+
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let f=n.indexOf(":");if(f<=0)continue;t.set(n.slice(0,f),n.slice(f+1))}return t}function dh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",r=[];if(i.username)r.push({username:i.username,password:i.password??""});for(let c of i.users??[])if(c?.username)r.push({username:c.username,password:c.password??""});let n;if(i.htpasswdFile)try{n=VB(sB(i.htpasswdFile,"utf8"))}catch{n=void 0}if(r.length===0&&(!n||n.size===0))return;return{realm:t,verify:(c,l)=>{let y=!1;for(let w of r)if(Lr(c,w.username)&&Lr(l,w.password))y=!0;if(n){let w=n.get(c);if(w&&kB(l,w))y=!0}return y}}}function Dh(i,t,r){if(t.startsWith(LB))return;let n=i.headers.get("authorization")??"",f=n.indexOf(" "),c=f===-1?n:n.slice(0,f),l=f===-1?"":n.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&&r.verify(w.slice(0,u),w.slice(u+1)))return}let y=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${y}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:dB}=Bun,xr=Symbol("rpx.pool.fallback"),gf=Symbol("rpx.pool.stale");var DB=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function bB(i){return DB.has(i.toUpperCase())}var Cl=Symbol("rpx.pool.timeout"),zt=Symbol("rpx.pool.busy");function PB(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function ZB(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function vB(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function oB(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Ph=1048576;function pB(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var ml=30000,ie=16384,Zh=262144,te=2097152,re=524288,ne=8192,fe=4096,ce=new TextEncoder,vh=new TextDecoder,le=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class oh{socket=null;buf=new Uint8Array(ie);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,r=t.write(i);while(r<i.length){if(this.closed)throw gf;await new Promise((n)=>{this.drainWaiter=n}),r+=t.write(i.subarray(r))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>te)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=re)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class ph{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=PB();maxWaiters;checkoutIdleMs=vB();inUse=new Set;constructor(i,t,r,n=""){this.host=i;this.port=t;this.maxTotal=r;this.key=n;this.maxWaiters=ZB(r)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new oh;return dB({hostname:this.host,port:this.port,socket:{data:(t,r)=>i.push(r),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let n=oB();if(n>0)r.timeout?.(n);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw zt;let i=await this.waitForSlot();if(i===zt)throw zt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,r=(c)=>{if(t)return;t=!0,clearTimeout(f),i(c)},n=(c)=>r(c),f=setTimeout(()=>{let c=this.waiters.indexOf(n);if(c!==-1)this.waiters.splice(c,1);r(zt)},this.queueWaitMs);f.unref?.(),this.waiters.push(n)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min(ml,this.checkoutIdleMs):ml;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-ml;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=i-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=r)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&sf.get(this.key)===this)sf.delete(this.key)}}}var sf=new Map;function ye(i,t){let r=sf.get(i);if(!r){let n=i.lastIndexOf(":"),f=n===-1?i:i.slice(0,n),c=n===-1?80:Number(i.slice(n+1));r=new ph(f,c,t,i),sf.set(i,r)}return r}function bh(i,t,r){for(let n=r+3;n<t;n++)if(i[n]===10&&i[n-1]===13&&i[n-2]===10&&i[n-3]===13)return n-3;return-1}function we(i,t,r){let n=vh.decode(i.subarray(t,r)),f=n.indexOf(`\r
|
|
174
174
|
`),c=f===-1?n:n.slice(0,f),l=c.indexOf(" "),y=Number.parseInt(c.slice(l+1,l+5),10),w=c.startsWith("HTTP/1.0"),u=[],h=-1,$=!1,A=w,T=!1,e=!1,E=f===-1?n.length:f+2;while(E<n.length){let B=n.indexOf(`\r
|
|
175
|
-
`,E);if(B===-1)B=n.length;let m=n.slice(E,B);if(E=B+2,m==="")continue;let j=m.indexOf(":");if(j===-1)continue;let W=m.slice(0,j),
|
|
175
|
+
`,E);if(B===-1)B=n.length;let m=n.slice(E,B);if(E=B+2,m==="")continue;let j=m.indexOf(":");if(j===-1)continue;let W=m.slice(0,j),S=m.slice(j+1).trim(),F=W.charCodeAt(0)|32;if(F===99||F===116||F===107){let I=W.toLowerCase();if(I==="content-length"){let N=/^\d+$/.test(S)?Number(S):Number.NaN;if(!Number.isSafeInteger(N)||h>=0&&h!==N)e=!0;else h=N;continue}if(I==="transfer-encoding"){if(S.toLowerCase().includes("chunked"))$=!0;continue}if(I==="connection"){let N=S.toLowerCase();if(N.includes("close"))A=!0;if(N.includes("keep-alive"))T=!0;continue}if(I==="keep-alive")continue}u.push([W,S])}if(w&&T)A=!1;if($&&h>=0)h=-1;return{status:y,headerEnd:r,headers:u,contentLength:h,chunked:$,closeConn:A,malformed:e}}function ue(i,t){return t||i===204||i===304}async function i$(i){let{hostPort:t,method:r,path:n,reqHeaders:f,forwardedHost:c,originOverride:l,body:y}=i,w=r==="HEAD";if(f.get("expect")||f.get("upgrade"))throw xr;let u=null;if(y){let T=f.get("content-length"),e=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(e)||e>Ph)throw xr;if(u=await Be(y),u===null)throw xr}let h=Ye(r,n,f,t,c,l,u),$=h;if(u&&u.length)$=new Uint8Array(h.length+u.length),$.set(h),$.set(u,h.length);let A=ye(t,i.maxPerHost??pB());for(let T=0;;T++){if(T>0)await new Promise((E)=>{setTimeout(E,T)});let e;try{e=A.acquireIdleSync()??await A.acquireOrDial()}catch(E){if(E!==zt&&T<4)continue;throw E}try{let E=e.socket.write($);if(E<$.length)await e.writeAll($.subarray(E));return await $e(A,e,w,i.signal)}catch(E){let B=E===gf&&T<4&&(e.fresh||bB(r));if(A.destroy(e),B)continue;if(E===gf)throw Error("upstream closed connection");throw E}}}async function he(i){let t=bh(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw Cl;if(i.len===i.pos)throw gf;throw Error("upstream closed mid-header")}if(i.len-i.pos>Zh)throw Error("upstream header block too large");await i.waitForData(i.len),t=bh(i.buf,i.len,i.pos)}return t}async function $e(i,t,r,n){let f;for(;;){let l=await he(t);if(f=we(t.buf,t.pos,l),t.pos=l+4,f.status>=100&&f.status<200)continue;break}if(f.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let c=f.headers;if(ue(f.status,r))return t$(i,t,f.closeConn),new Response(null,{status:f.status,headers:c});if(f.chunked)return new Response(Ee(i,t,f.closeConn,n),{status:f.status,headers:c});if(f.contentLength>=0){if(t.len-t.pos>=f.contentLength){let y=t.pos+f.contentLength,w=t.len>y,u=null;if(f.contentLength>=ne)u=t.buf.subarray(t.pos,y),t.buf=new Uint8Array(fe);else if(f.contentLength>0)u=t.buf.slice(t.pos,y);if(t.pos=0,t.len=0,f.closeConn||w)i.destroy(t);else i.release(t);return new Response(u,{status:f.status,headers:c})}return new Response(Ae(i,t,f.contentLength,f.closeConn),{status:f.status,headers:c})}return new Response(Te(t),{status:f.status,headers:c})}function t$(i,t,r){if(r||t.pos!==t.len)i.destroy(t);else i.release(t)}function Ae(i,t,r,n){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=r-f,t.queuedBytes=0,t.streamingBody=!0;let l=(y)=>{if(t.bodyQueue=null,n||t.len>0)i.destroy(t);else i.release(t);y.close()};return new ReadableStream({start(y){if(c)y.enqueue(c);if(t.bodyRemaining===0&&t.bodyQueue.length===0)l(y)},async pull(y){for(;;){let w=t.bodyQueue;if(w&&w.length>0){let u=w.shift();if(t.queuedBytes-=u.length,t.resumeIfDrained(),y.enqueue(u),t.bodyRemaining===0&&w.length===0)l(y);return}if(t.bodyRemaining===0){if(t.bodyQueue)l(y);return}if(t.closed){t.bodyQueue=null,i.destroy(t),y.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function Te(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 Ee(i,t,r,n){t.streamingBody=!0;let f=0,c=!1,l=!1,y,w=()=>n?.removeEventListener("abort",u),u=()=>{if(l)return;l=!0,i.destroy(t);try{y?.close()}catch{}};async function h($=!1){for(;;){for(let A=t.pos;A+1<t.len;A++)if(t.buf[A]===13&&t.buf[A+1]===10){let T=vh.decode(t.buf.subarray(t.pos,A));return t.pos=A+2,T}if(t.closed){if($&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>Zh)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start($){if(y=$,n?.aborted)u();else n?.addEventListener("abort",u,{once:!0})},async pull($){try{for(;;){if(f>0){if(t.len===t.pos){if(t.closed){i.destroy(t),$.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let E=Math.min(f,t.len-t.pos);if($.enqueue(t.buf.slice(t.pos,t.pos+E)),t.pos+=E,f-=E,t.resumeIfDrained(),f===0)c=!0;return}if(c)await h(),c=!1;let A=await h(!0);if(A===null){i.destroy(t),w(),$.close();return}let T=A.indexOf(";"),e=Number.parseInt(T===-1?A:A.slice(0,T),16);if(!Number.isInteger(e)||e<0){i.destroy(t),$.error(Error("upstream sent malformed chunk size"));return}if(e===0){for(;;)if(await h()==="")break;t$(i,t,r),w(),$.close();return}f=e}}catch(A){if(i.destroy(t),w(),!l)$.error(A)}},cancel(){l=!0,w(),i.destroy(t)}})}function Ye(i,t,r,n,f,c,l){let y=`${i} ${t} HTTP/1.1\r
|
|
176
176
|
host: ${n}\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 r){let $=u.toLowerCase();if(
|
|
181
|
+
`;let w=!1;for(let[u,h]of r){let $=u.toLowerCase();if(le.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 Ee(i){let t=i.getReader(),r=[],n=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(n+=y.length,n>Dh)return t.cancel().catch(()=>{}),null;r.push(y)}}if(r.length===1)return r[0];let f=new Uint8Array(n),c=0;for(let l of r)f.set(l,c),c+=l.length;return f}function dN(i){let t=typeof i==="string"?{to:i}:i,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function i$(i,t,r){if(!i.preservePath)return i.to||"/";let n=`${t}${r}`;return n==="/"?`${i.to}/`:`${i.to}${n}`}import*as Qi from"node:path";function t$(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 Ye={".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 Be(i){let t=Qi.extname(i).toLowerCase();return Ye[t]??"application/octet-stream"}function ee(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Qi.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function me(i,t){let r=ee(i);if(r===null)return null;let n=Qi.posix.extname(r);if(t.cleanUrls&&n===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Qi.join(t.dir,r),redirectTo:f||"/"}}if(r===""||i.endsWith("/"))return{filePath:Qi.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Qi.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Qi.join(t.dir,`${r}.html`)};return{filePath:Qi.join(t.dir,r,"index.html")}}async function r$(i,t){let r=me(i,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(r.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":Be(r.filePath),"Cache-Control":n}});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 Ue=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function je(i){let t=i.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function l$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let r=i.slice(t.length);return r===""?"/":r}return i}function n$(i){if(i.upstreamPool)return sh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function f$(i,t,r,n){let f=r?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?l$(i,t.basePath):i,y=c$(l,t.pathRewrites);if(y)f=y.targetHost,l=y.targetPath,Y("request",`Path rewrite: ${i} → ${f}${l}`,n);return{targetHost:f,targetPath:l}}function Re(i){let t=i.indexOf("://"),r=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=i.indexOf("?",r);if(n===-1)return{pathname:i.slice(r),search:""};return{pathname:i.slice(r,n),search:i.slice(n)}}function Cl(i,t,r){let n=async(f,c)=>{let{pathname:l,search:y}=Re(f.url),w=je(f),u=i(w,l);if(!u&&r){let B=await r(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=Vh(f,l,u.auth);if(B)return Y("request",`401 challenge for ${w}${l}`,t),B}if(u.redirect){let B=i$(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 m=u.stripBasePathPrefix??!0?l$(l,u.basePath):l;return r$(m,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:m,targetPath:j}=f$(l,u,B,t),W=`ws://${m}${j}${y}`,X={};for(let[J,v]of f.headers)if(!Ue.has(J.toLowerCase())&&J.toLowerCase()!=="host")X[J]=v;X.host=m,X["x-forwarded-for"]="127.0.0.1",X["x-forwarded-proto"]="https",X["x-forwarded-host"]=w;let F={targetUrl:W,forwardHeaders:X};if(c.upgrade(f,{data:F})){Y("ws",`upgraded ${w}${j} → ${W}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=n$(u);if(!h)return new Response(`No upstream configured for ${w}`,{status:502});if(u.cleanUrls&&l.endsWith(".html")){let B=l.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:B}})}let{targetHost:$,targetPath:A}=f$(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 oh({hostPort:$,method:f.method,path:`${A}${y}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body,signal:f.signal});if(E)Hf(E,h);return B}catch(B){if(B===ml){if(Y("request",`Upstream timeout for ${w}`,t),E)xr(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===Vr||!e)try{let m=new Headers(f.headers);if(m.set("host",$),m.set("x-forwarded-for","127.0.0.1"),m.set("x-forwarded-proto","https"),m.set("x-forwarded-host",w),T!==void 0)m.set("origin",T);let j=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:m,body:f.body,redirect:"manual"});if(E)Hf(E,h);return j}catch(m){if(Y("request",`Proxy error for ${w}: ${m}`,t),E)xr(E,h);return new Response(`Proxy Error: ${m}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)xr(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)h.activeConnections--}};return async(f,c)=>{try{return await n(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,r=Ce();return{open(n){let{targetUrl:f,forwardHeaders:c}=n.data,l;try{l=new WebSocket(f,{headers:c})}catch(w){Y("ws",`failed to open upstream ${f}: ${w}`,i),n.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,y),l.addEventListener("open",()=>{y.upstreamOpen=!0;for(let w of y.pending)l.send(w);y.pending=[],y.pendingBytes=0}),l.addEventListener("message",(w)=>{n.send(w.data)}),l.addEventListener("close",(w)=>{try{n.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{Y("ws",`upstream error for ${f}`,i);try{n.close(1011,"upstream error")}catch{}})},message(n,f){let c=t.get(n);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>r){Y("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,i);try{n.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}c.pending.push(l),c.pendingBytes+=y},close(n,f,c){let l=t.get(n);if(!l)return;t.delete(n);try{l.upstream.close(f||1000,c||"")}catch{}}}}import*as w$ from"node:fs";import*as u$ from"node:path";var y$="/.well-known/acme-challenge/";function h$(i,t){if(!i||!t.startsWith(y$))return null;let r=t.slice(y$.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return w$.readFileSync(u$.join(i,r),"utf8")}catch{return null}}function gf(i){return i.startsWith("*.")}function jl(i,t){if(!gf(t))return!1;let r=t.slice(1);return i.length>r.length&&i.endsWith(r)}function $$(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[c,l]of i){if(!gf(c))continue;if(jl(t,c)){let y=c.length-1;if(y>f)f=y,n=l}}return n}function Ot(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function Ne(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Rl(i){let t=new Map;for(let n of i){let f=Ot(n.path),c=t.get(n.host);if(!c)c=new Map,t.set(n.host,c);c.set(f,n.route)}let r=new Map;for(let[n,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),r.set(n,c)}return r}function Nl(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[c,l]of i){if(!gf(c))continue;if(jl(t,c)){let y=c.length-1;if(y>f)f=y,n=l}}return n}function Wl(i,t,r){let n=Nl(i,t);if(!n)return;for(let f of n)if(Ne(r,f.path))return f.route;return}import*as dr from"node:fs/promises";import*as Xl from"node:path";function Dr(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function We(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,r,n){try{let[f,c]=await Promise.all([dr.readFile(t,"utf8"),dr.readFile(r,"utf8")]);return{serverName:i,cert:f,key:c}}catch(f){return Y("sni",`skipping ${i}: ${f.message}`,n),null}}async function Sl(i,t){let r=new Map;if(i.certsDir){let f=[];try{f=await dr.readdir(i.certsDir)}catch(c){Y("sni",`certsDir read failed (${i.certsDir}): ${c.message}`,t)}for(let c of f){let l=We(c);if(!l)continue;let y=c.slice(0,-4);r.set(l,{certPath:Xl.join(i.certsDir,c),keyPath:Xl.join(i.certsDir,`${y}.key`)})}}if(i.domains)for(let[f,c]of Object.entries(i.domains))r.set(f,c);let n=[];for(let[f,c]of r){let l=await Xe(f,c.certPath,c.keyPath,t);if(l)n.push(l)}return n}import*as ki from"node:fs/promises";import*as Lf from"node:path";function al(i=process.env){let t=i.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return i.INVOCATION_ID?"restart":"rebind"}var Se="acme-account.key",ae=60000,A$=4096;function Je(i,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return i===n||i.endsWith(`.${n}`)})}function T$(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??kn,this.issuer=i.issuer??b0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??ae;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(!T$(i))return!1;if(Je(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(!T$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let r=this.negativeCache.get(i);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return Y("on-demand",`${i} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let n=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,n),n}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return 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 r={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,r),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>=A$){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=A$){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:r}=this.pathsFor(i);try{let[n,f]=await Promise.all([ki.readFile(t,"utf8"),ki.readFile(r,"utf8")]),c={serverName:i,cert:n,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:Lf.join(this.certsDir,`${i}.crt`),keyPath:Lf.join(this.certsDir,`${i}.key`)}}async persist(i,t,r){await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:f}=this.pathsFor(i);await Promise.all([ki.writeFile(n,t,"utf8"),ki.writeFile(f,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Lf.join(this.certsDir,Se)}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 Fe,readdirSync as Ie,readFileSync as Ke,statSync as _e}from"node:fs";import{homedir as B$}from"node:os";import{isAbsolute as ze,join as mr}from"node:path";var e$=["~/Code"],m$=["localhost","test"],Qe=1800000,Jl={dirExists:(i)=>{try{return _e(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return Fe(i)}catch{return!1}},readText:(i)=>{try{return Ke(i,"utf8")}catch{return null}}};function Fl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return mr(t,i.slice(2));return i}function Me(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function E$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function Oe(i,t){for(let r of t){let n=`.${r}`;if(i.endsWith(n)){let f=i.slice(0,-n.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function Ge(i,t){let r=t.readText(mr(i,"rpx.site.json"));if(r)try{let f=JSON.parse(r);if(f&&typeof f==="object")return f}catch{}let n=t.readText(mr(i,"package.json"));if(n)try{let f=JSON.parse(n);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function He(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 qe(i,t){let r=Ge(i,t);if(r?.command)return He(r);let n=t.fileExists(mr(i,"buddy")),f=t.readText(mr(i,"package.json")),c=null;if(f)try{c=JSON.parse(f)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(n||Object.keys(l).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(c?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Il(i,t={}){let r={dirExists:t.dirExists??Jl.dirExists,fileExists:t.fileExists??Jl.fileExists,readText:t.readText??Jl.readText},n=t.detect??qe,f=t.homeDir??B$(),c=i.tlds??m$,l=(i.roots??e$).map((A)=>Fl(A,f)),y=i.idleTimeoutMs??Qe,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=$$(w,A);if(!T)return null;let e=ze(T.dir)?T.dir:Fl(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=n(e,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let m=Y$({...T.env??{}},void 0,A);return{host:A,id:E$(A),dir:e,command:T.command,env:m,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=Oe(A,c);if(!T)return null;for(let e of l){let E=mr(e,T);if(!r.dirExists(E))continue;let B=n(E,r);if(!B)continue;let m=B.selfRegisters??!1;return{host:A,id:E$(A),dir:E,command:B.command,env:Y$({...B.env??{}},B.urlEnv,A),routes:m?[]:B.routes??[],selfRegisters:m,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=Me(A);if(!T)return null;return h(T)??$(T)}}}function se(i){try{return Ie(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function YW(i,t={}){let r=t.homeDir??B$(),n=i.tlds??m$,f=(i.roots??e$).map(($)=>Fl($,r)),c=t.readdir??se,l=Il(i,t),y=[],w=new Set,u=($)=>{if($&&!w.has($.host))w.add($.host),y.push($)};for(let $ of i.sites??[])if(!$.to.includes("*"))u(l.resolve($.to));let h=n[0]??"localhost";for(let $ of f)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function Y$(i,t,r){if(!t)return i;let n=`https://${r}`;for(let f of t)if(i[f]===void 0)i[f]=n;return i}import{closeSync as W$,openSync as Ve,readFileSync as de}from"node:fs";import*as X$ from"node:fs/promises";import{spawn as De}from"node:child_process";import{homedir as be}from"node:os";import*as Pr from"node:path";import*as Vi from"node:process";import*as kf from"node:net";function U$(i,t,r){return Y("port",`Checking if port ${i} is in use on ${t}`,r),new Promise((n)=>{let f=kf.createServer(),c=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,r),f.close(),n(!0)},3000);f.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,r),n(!0);else Y("port",`Error checking port ${i}: ${l.message}`,r),n(!0)}),f.once("listening",()=>{clearTimeout(c),Y("port",`Port ${i} is available`,r),f.close(),n(!1)});try{f.listen(i,t)}catch(l){clearTimeout(c),Y("port",`Exception checking port ${i}: ${l}`,r),n(!0)}})}async function Kl(i,t,r,n=50){Y("port",`Finding available port starting from ${i} (max attempts: ${n})`,r);let f=i,c=0;while(c<n){if(c++,!await U$(f,t,r))return Y("port",`Found available port: ${f} after ${c} attempts`,r),f;Y("port",`Port ${f} is in use, trying ${f+1} (attempt ${c}/${n})`,r),f++}throw Error(`Unable to find available port after ${n} attempts starting from ${i}`)}function C$(i,t,r=5000,n){return Y("port",`Testing connection to ${t}:${i}`,n),new Promise((f)=>{let c=kf.connect({host:t,port:i,timeout:r});c.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,n),c.end(),f(!0)}),c.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,n),c.destroy(),f(!1)}),c.once("error",(l)=>{Y("port",`Failed to connect to ${t}:${i}: ${l.message}`,n),c.destroy(),f(!1)})})}class j${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,r=50){this.hostname=i,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await U$(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 r=await Kl(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await C$(r,this.hostname,3000,this.verbose))if(r<i+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var mW=new j$;import*as Vf from"node:fs";import*as Ci from"node:fs/promises";import{homedir as ge}from"node:os";import*as _l from"node:path";import*as df from"node:process";var Le=/^[a-zA-Z0-9._-]+$/;function Xt(){return _l.join(ge(),".stacks","rpx","registry.d")}function zl(i){return typeof i==="string"&&i.length>0&&i.length<=128&&Le.test(i)}function Ql(i,t){if(!zl(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return _l.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 R$(i){if(!i||typeof i!=="object")return!1;let t=i,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0||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"&&zl(t.id)&&(n||f)&&typeof t.to==="string"&&t.to.length>0&&c&&r&&typeof t.createdAt==="string"}async function xe(i){await Ci.mkdir(i,{recursive:!0})}async function N$(i,t=Xt(),r){if(!R$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await xe(t);let n=Ql(t,i.id),f=`${n}.tmp.${df.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await Ci.writeFile(f,c,{encoding:"utf8",mode:420}),await Ci.rename(f,n),Y("registry",`wrote entry ${i.id} → ${n}`,r)}catch(l){throw await Ci.unlink(f).catch(()=>{}),l}}async function Ml(i,t=Xt(),r){let n=Ql(t,i);try{await Ci.unlink(n),Y("registry",`removed entry ${i}`,r)}catch(f){if(f.code!=="ENOENT")throw f}}async function ke(i,t=Xt(),r){let n=Ql(t,i);try{let f=await Ci.readFile(n,"utf8"),c=JSON.parse(f);if(!R$(c))return Y("registry",`entry ${i} failed validation, removing`,r),await Ci.unlink(n).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`,r),await Ci.unlink(n).catch(()=>{}),null;throw f}}async function Et(i=Xt(),t){let r;try{r=await Ci.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let n=[];for(let f of r){if(!f.endsWith(".json"))continue;let c=f.slice(0,-5);if(!zl(c))continue;let l=await ke(c,i,t);if(l)n.push(l)}return n}async function br(i=Xt(),t){let r=await Et(i,t),n=0;for(let f of r){if(f.pid===void 0)continue;if(!Ui(f.pid))Y("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await Ml(f.id,i,t).catch(()=>{}),n++}return n}function Df(i,t={}){let r=t.dir??Xt(),n=t.debounceMs??100,f=t.pollMs??Math.max(n*2,250),c=t.verbose;Vf.mkdirSync(r,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((m)=>({id:m.id,from:m.from,to:m.to,path:m.path,pid:m.pid,pathRewrites:m.pathRewrites,cleanUrls:m.cleanUrls,changeOrigin:m.changeOrigin,static:m.static,loadBalancer:m.loadBalancer})).sort((m,j)=>m.id.localeCompare(j.id)))},$=()=>{if(l=null,y)return;Et(r,c).then((B)=>{return w=h(B),i(B)}).catch((B)=>{Y("registry",`watcher onChange failed: ${B}`,c)})},A=()=>{if(y)return;if(l)clearTimeout(l);l=setTimeout($,n)},e=setInterval(()=>{if(y||u)return;u=!0,Et(r,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=Vf.watch(r,{persistent:!0},(B,m)=>{if(m&&/\.tmp\.\d+\.\d+$/.test(m))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 Pe=120000,Ze=200,ve=30000,oe=3000,pe=4000;class Gl{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??Xt(),this.rpxDir=i.rpxDir??Pr.join(be(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??Pe,this.pollIntervalMs=i.pollIntervalMs??Ze,this.restartDelayMs=i.restartDelayMs??oe,this.killGraceMs=i.killGraceMs??pe,this.launch=i.launcher??tm(this.verbose),this.probePort=i.probePort??im,this.pickPort=i.pickPort??((r)=>Kl(r,"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??Ml;let t=i.reapIntervalMs??ve;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let r=this.resolver.resolve(i);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let y of i.routes){if(t.has(y.portEnv))continue;let w=await this.pickPort(y.defaultPort??3000);t.set(y.portEnv,w)}let r=Pr.join(this.rpxDir,"sites",`${i.id}.log`);await X$.mkdir(Pr.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(i,t),f=null,c;try{f=this.launch({command:i.command,cwd:i.dir,env:n,logPath:r})}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:r,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 r of i.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<r&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await n()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",S.success(`rpx: ${t.host} ready`);return}await Ol(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let r=i.routes.filter((f)=>f.readyGate??Ot(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let f of n)if(!await this.probePort(f))return!1;return n.length>0}}async publishRoutes(i){let{site:t,ports:r}=i;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((w)=>Ot(w.path)==="/")??t.routes[0],f=r.get(n.portEnv);if(f===void 0)return;let c=[];for(let w of t.routes){if(w===n)continue;let u=r.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 Ol(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 r={};for(let[n,f]of Object.entries(Vi.env))if(typeof f==="string")r[n]=f;Object.assign(r,i.env);for(let[n,f]of t)r[n]=String(f);return r.RPX_SITE_HOST=i.host,r.RPX_SITE_URL=`https://${i.host}`,r}readLogTail(i,t=40){try{return de(i.logPath,"utf8").split(`
|
|
185
|
+
`,ce.encode(y)}async function Be(i){let t=i.getReader(),r=[],n=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(n+=y.length,n>Ph)return t.cancel().catch(()=>{}),null;r.push(y)}}if(r.length===1)return r[0];let f=new Uint8Array(n),c=0;for(let l of r)f.set(l,c),c+=l.length;return f}function bN(i){let t=typeof i==="string"?{to:i}:i,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function r$(i,t,r){if(!i.preservePath)return i.to||"/";let n=`${t}${r}`;return n==="/"?`${i.to}/`:`${i.to}${n}`}import*as Gi from"node:path";function n$(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var 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 me(i){let t=Gi.extname(i).toLowerCase();return ee[t]??"application/octet-stream"}function Ce(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Gi.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function Ue(i,t){let r=Ce(i);if(r===null)return null;let n=Gi.posix.extname(r);if(t.cleanUrls&&n===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Gi.join(t.dir,r),redirectTo:f||"/"}}if(r===""||i.endsWith("/"))return{filePath:Gi.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Gi.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Gi.join(t.dir,`${r}.html`)};return{filePath:Gi.join(t.dir,r,"index.html")}}async function f$(i,t){let r=Ue(i,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(r.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":me(r.filePath),"Cache-Control":n}});if(t.spa){let c=Gi.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 je(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var Re=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function Ne(i){let t=i.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function w$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let r=i.slice(t.length);return r===""?"/":r}return i}function c$(i){if(i.upstreamPool)return Lh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function l$(i,t,r,n){let f=r?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?w$(i,t.basePath):i,y=y$(l,t.pathRewrites);if(y)f=y.targetHost,l=y.targetPath,Y("request",`Path rewrite: ${i} → ${f}${l}`,n);return{targetHost:f,targetPath:l}}function We(i){let t=i.indexOf("://"),r=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=i.indexOf("?",r);if(n===-1)return{pathname:i.slice(r),search:""};return{pathname:i.slice(r,n),search:i.slice(n)}}function Ul(i,t,r){let n=async(f,c)=>{let{pathname:l,search:y}=We(f.url),w=Ne(f),u=i(w,l);if(!u&&r){let B=await r(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=Dh(f,l,u.auth);if(B)return Y("request",`401 challenge for ${w}${l}`,t),B}if(u.redirect){let B=r$(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 m=u.stripBasePathPrefix??!0?w$(l,u.basePath):l;return f$(m,u.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let B=c$(u);if(!c||!B)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:m,targetPath:j}=l$(l,u,B,t),W=`ws://${m}${j}${y}`,S={};for(let[N,li]of f.headers)if(!Re.has(N.toLowerCase())&&N.toLowerCase()!=="host")S[N]=li;S.host=m,S["x-forwarded-for"]="127.0.0.1",S["x-forwarded-proto"]="https",S["x-forwarded-host"]=w;let F={targetUrl:W,forwardHeaders:S};if(c.upgrade(f,{data:F})){Y("ws",`upgraded ${w}${j} → ${W}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=c$(u);if(!h)return new Response(`No upstream configured for ${w}`,{status:502});if(u.cleanUrls&&l.endsWith(".html")){let B=l.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:B}})}let{targetHost:$,targetPath:A}=l$(l,u,h,t),T=u.changeOrigin?`http://${$}`:void 0,e=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=u.upstreamPool;if(E)h.activeConnections++;try{let B=await i$({hostPort:$,method:f.method,path:`${A}${y}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body,signal:f.signal});if(E)qf(E,h);return B}catch(B){if(B===Cl){if(Y("request",`Upstream timeout for ${w}`,t),E)sr(E,h);return new Response("Gateway Timeout",{status:504})}if(B===zt)return Y("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(B===xr||!e)try{let m=new Headers(f.headers);if(m.set("host",$),m.set("x-forwarded-for","127.0.0.1"),m.set("x-forwarded-proto","https"),m.set("x-forwarded-host",w),T!==void 0)m.set("origin",T);let j=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:m,body:f.body,redirect:"manual"});if(E)qf(E,h);return j}catch(m){if(Y("request",`Proxy error for ${w}: ${m}`,t),E)sr(E,h);return new Response(`Proxy Error: ${m}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)sr(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)h.activeConnections--}};return async(f,c)=>{try{return await n(f,c)}catch(l){return Y("request",`Unhandled proxy handler error: ${l}`,t),new Response("Bad Gateway",{status:502})}}}function jl(i){let t=new WeakMap,r=je();return{open(n){let{targetUrl:f,forwardHeaders:c}=n.data,l;try{l=new WebSocket(f,{headers:c})}catch(w){Y("ws",`failed to open upstream ${f}: ${w}`,i),n.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,y),l.addEventListener("open",()=>{y.upstreamOpen=!0;for(let w of y.pending)l.send(w);y.pending=[],y.pendingBytes=0}),l.addEventListener("message",(w)=>{n.send(w.data)}),l.addEventListener("close",(w)=>{try{n.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{Y("ws",`upstream error for ${f}`,i);try{n.close(1011,"upstream error")}catch{}})},message(n,f){let c=t.get(n);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>r){Y("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,i);try{n.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}c.pending.push(l),c.pendingBytes+=y},close(n,f,c){let l=t.get(n);if(!l)return;t.delete(n);try{l.upstream.close(f||1000,c||"")}catch{}}}}import*as h$ from"node:fs";import*as $$ from"node:path";var u$="/.well-known/acme-challenge/";function A$(i,t){if(!i||!t.startsWith(u$))return null;let r=t.slice(u$.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return h$.readFileSync($$.join(i,r),"utf8")}catch{return null}}function Lf(i){return i.startsWith("*.")}function Rl(i,t){if(!Lf(t))return!1;let r=t.slice(1);return i.length>r.length&&i.endsWith(r)}function T$(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[c,l]of i){if(!Lf(c))continue;if(Rl(t,c)){let y=c.length-1;if(y>f)f=y,n=l}}return n}function Qt(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function Xe(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Nl(i){let t=new Map;for(let n of i){let f=Qt(n.path),c=t.get(n.host);if(!c)c=new Map,t.set(n.host,c);c.set(f,n.route)}let r=new Map;for(let[n,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),r.set(n,c)}return r}function Wl(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[c,l]of i){if(!Lf(c))continue;if(Rl(t,c)){let y=c.length-1;if(y>f)f=y,n=l}}return n}function Xl(i,t,r){let n=Wl(i,t);if(!n)return;for(let f of n)if(Xe(r,f.path))return f.route;return}import*as kr from"node:fs/promises";import*as Sl from"node:path";function Vr(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function Se(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 ae(i,t,r,n){try{let[f,c]=await Promise.all([kr.readFile(t,"utf8"),kr.readFile(r,"utf8")]);return{serverName:i,cert:f,key:c}}catch(f){return Y("sni",`skipping ${i}: ${f.message}`,n),null}}async function al(i,t){let r=new Map;if(i.certsDir){let f=[];try{f=await kr.readdir(i.certsDir)}catch(c){Y("sni",`certsDir read failed (${i.certsDir}): ${c.message}`,t)}for(let c of f){let l=Se(c);if(!l)continue;let y=c.slice(0,-4);r.set(l,{certPath:Sl.join(i.certsDir,c),keyPath:Sl.join(i.certsDir,`${y}.key`)})}}if(i.domains)for(let[f,c]of Object.entries(i.domains))r.set(f,c);let n=[];for(let[f,c]of r){let l=await ae(f,c.certPath,c.keyPath,t);if(l)n.push(l)}return n}import*as di from"node:fs/promises";import*as xf from"node:path";function Jl(i=process.env){let t=i.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return i.INVOCATION_ID?"restart":"rebind"}var Je="acme-account.key",Fe=60000,E$=4096;function Ke(i,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return i===n||i.endsWith(`.${n}`)})}function Y$(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class kf{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??Vn,this.issuer=i.issuer??P0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??Fe;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!Y$(i))return!1;if(Ke(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return Y("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!Y$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let r=this.negativeCache.get(i);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return Y("on-demand",`${i} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let n=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,n),n}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return 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 r={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,r),this.negativeCache.delete(i),Y("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),Y("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=E$){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=E$){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:r}=this.pathsFor(i);try{let[n,f]=await Promise.all([di.readFile(t,"utf8"),di.readFile(r,"utf8")]),c={serverName:i,cert:n,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:xf.join(this.certsDir,`${i}.crt`),keyPath:xf.join(this.certsDir,`${i}.key`)}}async persist(i,t,r){await di.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:f}=this.pathsFor(i);await Promise.all([di.writeFile(n,t,"utf8"),di.writeFile(f,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return xf.join(this.certsDir,Je)}async loadAccountKey(){try{return await di.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(i){if(!i||this.accountKeyPem===i)return;this.accountKeyPem=i,await di.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await di.writeFile(this.accountKeyPath,i,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as Ie,readdirSync as _e,readFileSync as ze,statSync as Qe}from"node:fs";import{homedir as m$}from"node:os";import{isAbsolute as Me,join as Er}from"node:path";var C$=["~/Code"],U$=["localhost","test"],Oe=1800000,Fl={dirExists:(i)=>{try{return Qe(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return Ie(i)}catch{return!1}},readText:(i)=>{try{return ze(i,"utf8")}catch{return null}}};function Kl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Er(t,i.slice(2));return i}function Ge(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function B$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function He(i,t){for(let r of t){let n=`.${r}`;if(i.endsWith(n)){let f=i.slice(0,-n.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function qe(i,t){let r=t.readText(Er(i,"rpx.site.json"));if(r)try{let f=JSON.parse(r);if(f&&typeof f==="object")return f}catch{}let n=t.readText(Er(i,"package.json"));if(n)try{let f=JSON.parse(n);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function 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 se(i,t){let r=qe(i,t);if(r?.command)return ge(r);let n=t.fileExists(Er(i,"buddy")),f=t.readText(Er(i,"package.json")),c=null;if(f)try{c=JSON.parse(f)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(n||Object.keys(l).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(c?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Il(i,t={}){let r={dirExists:t.dirExists??Fl.dirExists,fileExists:t.fileExists??Fl.fileExists,readText:t.readText??Fl.readText},n=t.detect??se,f=t.homeDir??m$(),c=i.tlds??U$,l=(i.roots??C$).map((A)=>Kl(A,f)),y=i.idleTimeoutMs??Oe,w=new Map;for(let A of i.sites??[])w.set(A.to,A);let u=(A)=>A.idleTimeoutMs??y;function h(A){let T=T$(w,A);if(!T)return null;let e=Me(T.dir)?T.dir:Kl(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=n(e,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let m=e$({...T.env??{}},void 0,A);return{host:A,id:B$(A),dir:e,command:T.command,env:m,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=He(A,c);if(!T)return null;for(let e of l){let E=Er(e,T);if(!r.dirExists(E))continue;let B=n(E,r);if(!B)continue;let m=B.selfRegisters??!1;return{host:A,id:B$(A),dir:E,command:B.command,env:e$({...B.env??{}},B.urlEnv,A),routes:m?[]:B.routes??[],selfRegisters:m,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=Ge(A);if(!T)return null;return h(T)??$(T)}}}function Le(i){try{return _e(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function eW(i,t={}){let r=t.homeDir??m$(),n=i.tlds??U$,f=(i.roots??C$).map(($)=>Kl($,r)),c=t.readdir??Le,l=Il(i,t),y=[],w=new Set,u=($)=>{if($&&!w.has($.host))w.add($.host),y.push($)};for(let $ of i.sites??[])if(!$.to.includes("*"))u(l.resolve($.to));let h=n[0]??"localhost";for(let $ of f)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function e$(i,t,r){if(!t)return i;let n=`https://${r}`;for(let f of t)if(i[f]===void 0)i[f]=n;return i}import{closeSync as S$,openSync as De,readFileSync as be}from"node:fs";import*as a$ from"node:fs/promises";import{spawn as Pe}from"node:child_process";import{homedir as Ze}from"node:os";import*as Dr from"node:path";import*as Di from"node:process";import*as Vf from"node:net";function R$(i,t,r){return Y("port",`Checking if port ${i} is in use on ${t}`,r),new Promise((n)=>{let f=Vf.createServer(),c=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,r),f.close(),n(!0)},3000);f.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,r),n(!0);else Y("port",`Error checking port ${i}: ${l.message}`,r),n(!0)}),f.once("listening",()=>{clearTimeout(c),Y("port",`Port ${i} is available`,r),f.close(),n(!1)});try{f.listen(i,t)}catch(l){clearTimeout(c),Y("port",`Exception checking port ${i}: ${l}`,r),n(!0)}})}async function _l(i,t,r,n=50){Y("port",`Finding available port starting from ${i} (max attempts: ${n})`,r);let f=i,c=0;while(c<n){if(c++,!await R$(f,t,r))return Y("port",`Found available port: ${f} after ${c} attempts`,r),f;Y("port",`Port ${f} is in use, trying ${f+1} (attempt ${c}/${n})`,r),f++}throw Error(`Unable to find available port after ${n} attempts starting from ${i}`)}function j$(i,t,r=5000,n){return Y("port",`Testing connection to ${t}:${i}`,n),new Promise((f)=>{let c=Vf.connect({host:t,port:i,timeout:r});c.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,n),c.end(),f(!0)}),c.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,n),c.destroy(),f(!1)}),c.once("error",(l)=>{Y("port",`Failed to connect to ${t}:${i}: ${l.message}`,n),c.destroy(),f(!1)})})}class N${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,r=50){this.hostname=i,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await R$(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await j$(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 r=await _l(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await j$(r,this.hostname,3000,this.verbose))if(r<i+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var UW=new N$;import*as df from"node:fs";import*as Ui from"node:fs/promises";import{homedir as xe}from"node:os";import*as zl from"node:path";import*as Df from"node:process";var ke=/^[a-zA-Z0-9._-]+$/;function St(){return zl.join(xe(),".stacks","rpx","registry.d")}function Ql(i){return typeof i==="string"&&i.length>0&&i.length<=128&&ke.test(i)}function Ml(i,t){if(!Ql(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return zl.join(i,`${t}.json`)}function ji(i){if(!Number.isInteger(i)||i<=0)return!1;try{return Df.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function W$(i){if(!i||typeof i!=="object")return!1;let t=i,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0||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"&&Ql(t.id)&&(n||f)&&typeof t.to==="string"&&t.to.length>0&&c&&r&&typeof t.createdAt==="string"}async function Ve(i){await Ui.mkdir(i,{recursive:!0})}async function X$(i,t=St(),r){if(!W$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await Ve(t);let n=Ml(t,i.id),f=`${n}.tmp.${Df.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await Ui.writeFile(f,c,{encoding:"utf8",mode:420}),await Ui.rename(f,n),Y("registry",`wrote entry ${i.id} → ${n}`,r)}catch(l){throw await Ui.unlink(f).catch(()=>{}),l}}async function Ol(i,t=St(),r){let n=Ml(t,i);try{await Ui.unlink(n),Y("registry",`removed entry ${i}`,r)}catch(f){if(f.code!=="ENOENT")throw f}}async function de(i,t=St(),r){let n=Ml(t,i);try{let f=await Ui.readFile(n,"utf8"),c=JSON.parse(f);if(!W$(c))return Y("registry",`entry ${i} failed validation, removing`,r),await Ui.unlink(n).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`,r),await Ui.unlink(n).catch(()=>{}),null;throw f}}async function Yt(i=St(),t){let r;try{r=await Ui.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let n=[];for(let f of r){if(!f.endsWith(".json"))continue;let c=f.slice(0,-5);if(!Ql(c))continue;let l=await de(c,i,t);if(l)n.push(l)}return n}async function dr(i=St(),t){let r=await Yt(i,t),n=0;for(let f of r){if(f.pid===void 0)continue;if(!ji(f.pid))Y("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await Ol(f.id,i,t).catch(()=>{}),n++}return n}function bf(i,t={}){let r=t.dir??St(),n=t.debounceMs??100,f=t.pollMs??Math.max(n*2,250),c=t.verbose;df.mkdirSync(r,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((m)=>({id:m.id,from:m.from,to:m.to,path:m.path,pid:m.pid,pathRewrites:m.pathRewrites,cleanUrls:m.cleanUrls,changeOrigin:m.changeOrigin,static:m.static,loadBalancer:m.loadBalancer})).sort((m,j)=>m.id.localeCompare(j.id)))},$=()=>{if(l=null,y)return;Yt(r,c).then((B)=>{return w=h(B),i(B)}).catch((B)=>{Y("registry",`watcher onChange failed: ${B}`,c)})},A=()=>{if(y)return;if(l)clearTimeout(l);l=setTimeout($,n)},e=setInterval(()=>{if(y||u)return;u=!0,Yt(r,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=df.watch(r,{persistent:!0},(B,m)=>{if(m&&/\.tmp\.\d+\.\d+$/.test(m))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 ve=120000,oe=200,pe=30000,im=3000,tm=4000;class Hl{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??St(),this.rpxDir=i.rpxDir??Dr.join(Ze(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??ve,this.pollIntervalMs=i.pollIntervalMs??oe,this.restartDelayMs=i.restartDelayMs??im,this.killGraceMs=i.killGraceMs??tm,this.launch=i.launcher??nm(this.verbose),this.probePort=i.probePort??rm,this.pickPort=i.pickPort??((r)=>_l(r,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??X$,this.removeEntry=i.removeEntry??Ol;let t=i.reapIntervalMs??pe;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let r=this.resolver.resolve(i);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let y of i.routes){if(t.has(y.portEnv))continue;let w=await this.pickPort(y.defaultPort??3000);t.set(y.portEnv,w)}let r=Dr.join(this.rpxDir,"sites",`${i.id}.log`);await a$.mkdir(Dr.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(i,t),f=null,c;try{f=this.launch({command:i.command,cwd:i.dir,env:n,logPath:r})}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:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,l),c)return a.warn(`rpx: site ${i.host} ${c}`),l;return a.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"){a.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let r of i.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<r&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await n()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",a.success(`rpx: ${t.host} ready`);return}await Gl(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let r=i.routes.filter((f)=>f.readyGate??Qt(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let f of n)if(!await this.probePort(f))return!1;return n.length>0}}async publishRoutes(i){let{site:t,ports:r}=i;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((w)=>Qt(w.path)==="/")??t.routes[0],f=r.get(n.portEnv);if(f===void 0)return;let c=[];for(let w of t.routes){if(w===n)continue;let u=r.get(w.portEnv);if(u===void 0)continue;c.push({from:Qt(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 Gl(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),a.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let r={};for(let[n,f]of Object.entries(Di.env))if(typeof f==="string")r[n]=f;Object.assign(r,i.env);for(let[n,f]of t)r[n]=String(f);return r.RPX_SITE_HOST=i.host,r.RPX_SITE_URL=`https://${i.host}`,r}readLogTail(i,t=40){try{return be(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 r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),
|
|
187
|
+
`).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),a.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),Gl(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,r]of this.sites){let n=r.site.idleTimeoutMs;if(n<=0)continue;let f=i-r.lastAccess;if((r.status==="ready"||i-r.startedAt>this.startupTimeoutMs)&&f>n)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 Gl(i){return new Promise((t)=>setTimeout(t,i))}async function rm(i){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function nm(i){let t=fm();return({command:r,cwd:n,env:f,logPath:c})=>{let l=De(c,"a");try{let y=Pe("sh",["-c",r],{cwd:n,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{S$(l)}catch{}});return Y("sites",`spawned pid ${w}: sh -c ${r} (cwd ${n})`,i),{pid:w,exited:u,stop:(h="SIGTERM")=>{try{Di.kill(-w,h)}catch{try{y.kill(h)}catch{}}}}}catch(y){try{S$(l)}catch{}throw y}}}function fm(){if(Di.platform==="win32")return null;if(!(typeof Di.getuid==="function"&&Di.getuid()===0))return null;let t=Number.parseInt(Di.env.SUDO_UID??"",10),r=Number.parseInt(Di.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}function Yr(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var cm=`
|
|
188
188
|
:root { color-scheme: light dark }
|
|
189
189
|
* { box-sizing: border-box }
|
|
190
190
|
body {
|
|
@@ -210,43 +210,43 @@ x-forwarded-host: ${f}\r
|
|
|
210
210
|
}
|
|
211
211
|
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
212
212
|
@keyframes spin { to { transform: rotate(360deg) } }
|
|
213
|
-
`;function
|
|
213
|
+
`;function J$(i,t,r){return`<!doctype html>
|
|
214
214
|
<html lang="en">
|
|
215
215
|
<head>
|
|
216
216
|
<meta charset="utf-8">
|
|
217
217
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
218
218
|
${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
|
|
219
|
-
<title>${
|
|
220
|
-
<style>${
|
|
219
|
+
<title>${Yr(i)}</title>
|
|
220
|
+
<style>${cm}</style>
|
|
221
221
|
</head>
|
|
222
222
|
<body><main class="card">${t}</main></body>
|
|
223
|
-
</html>`}function
|
|
224
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${
|
|
223
|
+
</html>`}function F$(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),r=i.logTail?`<pre>${Yr(i.logTail)}</pre>`:"",n=`
|
|
224
|
+
<div class="row"><div class="spinner"></div><h1>Starting ${Yr(i.host)}…</h1></div>
|
|
225
225
|
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
226
226
|
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
227
227
|
<p>Booting for ${t}s.</p>
|
|
228
|
-
${r}`;return new Response(
|
|
229
|
-
<div class="row"><div class="dot"></div><h1>${
|
|
230
|
-
<p>${
|
|
228
|
+
${r}`;return new Response(J$(`Starting ${i.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function K$(i){let t=i.logTail?`<pre>${Yr(i.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
|
|
229
|
+
<div class="row"><div class="dot"></div><h1>${Yr(i.host)} failed to start</h1></div>
|
|
230
|
+
<p>${Yr(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(
|
|
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(J$(`${i.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as lm}from"node:child_process";import Pr from"node:fs";import ym from"node:os";import Q$ from"node:path";import*as Mt from"node:process";import{promisify as wm}from"node:util";var br=wm(lm);function I$(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var Zi=Mt.platform==="win32"?Q$.join(Mt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",_$="# rpx",um="# Added by rpx",Zr=new Set(["127.0.0.1","::1"]),ql=!1;async function M$(i){if(Mt.platform==="win32")throw Error("Administrator privileges required on Windows");if(z$()){let{stdout:n}=await br(i);return n}let t=gl(),r=i.replace(/'/g,"'\\''");try{if(t){let{stdout:n}=await br(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`);return ql=!0,n}if(ql)try{let{stdout:n}=await br(`sudo -n sh -c '${r}'`);return n}catch(n){Y("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:n}=await br(`sudo -n sh -c '${r}'`);return ql=!0,n}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(n){throw Error(`Failed to execute sudo command: ${n.message}`)}}function vr(i){let t=i.indexOf("#"),r=(t===-1?i:i.slice(0,t)).trim();if(!r)return null;let n=t===-1?"":i.slice(t+1).trim(),[f,...c]=r.split(/\s+/);if(!f||c.length===0)return null;let l=/^rpx(?::pid=(\d+))?$/.exec(n);return{address:f,names:c,comment:n,rpxPid:l?.[1]?Number.parseInt(l[1],10):null,rpxManaged:l!==null}}function O$(i,t){let r=vr(i);return r!==null&&Zr.has(r.address)&&r.names.includes(t)}function hm(i,t){let r=new Set(t),n=new Set,f=i.split(`
|
|
233
|
+
`),c=[],l=0;while(l<f.length){let y=f[l];if(y.trim()===um){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=vr(A),e=T!==null&&Zr.has(T.address)&&T.names.some((E)=>r.has(E));if(e){for(let E of T.names)if(r.has(E))n.add(E)}return!e});if($.length>0||u.length===0)c.push(y,...$);l=h;continue}let w=vr(y);if(w?.rpxManaged&&Zr.has(w.address)&&w.names.some((u)=>r.has(u))){for(let u of w.names)if(r.has(u))n.add(u);l++;continue}c.push(y),l++}while(c.length>0&&c[c.length-1].trim()==="")c.pop();return{content:`${c.join(`
|
|
234
234
|
`)}
|
|
235
|
-
`,removed:[...n]}}function
|
|
236
|
-
`)){let l=
|
|
235
|
+
`,removed:[...n]}}function $m(i,t){let r=[],n=new Set,f=[];for(let c of i.split(`
|
|
236
|
+
`)){let l=vr(c);if(l?.rpxManaged&&l.rpxPid!==null&&Zr.has(l.address)&&!t(l.rpxPid)){r.push(...l.names),n.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:r,stalePids:[...n]}}async function sl(i){try{return await
|
|
239
|
-
`),l=r.filter((u)=>!c.some((h)=>
|
|
240
|
-
127.0.0.1 ${u} ${
|
|
241
|
-
::1 ${u} ${
|
|
242
|
-
`);try{await
|
|
243
|
-
`);return i.map((f)=>n.some((c)=>
|
|
244
|
-
`)){let f=
|
|
245
|
-
`)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await
|
|
246
|
-
`),u.stdin.end();u.unref();let A=
|
|
247
|
-
`):A.ca}:null,e=!1,E=[];function B(K){for(let
|
|
248
|
-
`,"utf8")}async function
|
|
238
|
+
`,removed:r,stalePids:[...n]}}async function sl(i){try{return await Pr.promises.readFile(Zi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),M$(`cat "${Zi}"`)}}async function Ll(i,t){let r=Q$.join(ym.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Pr.promises.writeFile(r,i,"utf8"),await M$(`cat "${r}" | tee "${Zi}" > /dev/null`)}finally{await Pr.promises.unlink(r).catch((n)=>{Y("hosts",`Failed to remove temporary file: ${n}`,t)})}}async function LW(i,t){let r=i.filter((f)=>!I$(f)),n=i.filter((f)=>I$(f));if(n.length>0)Y("hosts",`Skipping /etc/hosts for loopback dev names: ${n.join(", ")}`,t);if(r.length===0)return;Y("hosts",`Adding hosts: ${r.join(", ")}`,t),Y("hosts",`Using hosts file at: ${Zi}`,t);try{let f;try{f=await sl(t)}catch(u){throw console.log(" Could not read hosts file — skipping hosts setup"),Y("hosts",`sudo read also failed: ${u}`,t),Error(`Cannot read hosts file: ${u}`)}let c=f.split(`
|
|
239
|
+
`),l=r.filter((u)=>!c.some((h)=>O$(h,u)));if(l.length===0){Y("hosts","All hosts already exist in hosts file",t);return}let y=Mt.pid,w=l.map((u)=>`
|
|
240
|
+
127.0.0.1 ${u} ${_$}:pid=${y}
|
|
241
|
+
::1 ${u} ${_$}:pid=${y}`).join(`
|
|
242
|
+
`);try{await Ll(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 ${Zi}`)}}catch(f){Y("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function xW(i,t){Y("hosts",`Removing hosts: ${i.join(", ")}`,t);try{let r;try{r=await sl(t)}catch(c){throw Y("hosts",`sudo read also failed: ${c}`,t),Error(`Cannot read hosts file: ${c}`)}let{content:n,removed:f}=hm(r,i);if(f.length===0){Y("hosts","No matching rpx-managed hosts found to remove",t);return}try{await Ll(n,t),Y("hosts",`Hosts removed successfully: ${f.join(", ")}`,t)}catch(c){Y("hosts","Could not clean up hosts file automatically",t)}}catch(r){Y("hosts",`Failed to clean up hosts file: ${r.message}`,t)}}async function kW(i,t){Y("hosts",`Checking hosts: ${i}`,t);let r;try{r=await Pr.promises.readFile(Zi,"utf-8")}catch(f){Y("hosts",`Error reading hosts file: ${f}`,t);try{let c=gl(),l;if(c)l=`echo '${c}' | sudo -S cat "${Zi}" 2>/dev/null`;else l=`sudo -n cat "${Zi}" 2>/dev/null || cat "${Zi}" 2>/dev/null || echo ""`;let{stdout:y}=await br(l);r=y}catch(c){return Y("hosts",`Cannot read hosts file, assuming entries don't exist: ${c}`,t),i.map(()=>!1)}}let n=r.split(`
|
|
243
|
+
`);return i.map((f)=>n.some((c)=>O$(c,f)))}async function VW(i=ji){let t;try{t=await Pr.promises.readFile(Zi,"utf-8")}catch{return[]}let r=[];for(let n of t.split(`
|
|
244
|
+
`)){let f=vr(n);if(f?.rpxManaged&&f.rpxPid!==null&&Zr.has(f.address)&&!i(f.rpxPid))r.push(...f.names)}return[...new Set(r)]}async function or(i={}){let t=i.isAlive??ji,r;try{r=await sl(i.verbose)}catch(l){return Y("hosts",`stale hosts GC: cannot read hosts file: ${l}`,i.verbose),[]}let{content:n,removed:f,stalePids:c}=$m(r,t);if(f.length===0)return[];try{return await Ll(n,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 Am=5000;function Ri(){return vi.join(L$(),".stacks","rpx")}function of(i=Ri()){return vi.join(i,"daemon.pid")}async function er(i=Ri()){try{let t=await Ei.readFile(of(i),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Tm(i=Ri()){let t=await er(i);return t!==null&&ji(t)}async function x$(i=Ri()){await Ei.mkdir(i,{recursive:!0});let t=of(i);while(!0){try{let n=await Ei.open(t,"wx");try{await n.write(`${U.pid}
|
|
245
|
+
`)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await er(i);if(r!==null&&ji(r))throw Error(`rpx daemon already running (pid=${r})`);await Ei.unlink(t).catch(()=>{})}}async function Br(i=Ri()){await Ei.unlink(of(i)).catch(()=>{})}var Zf=new Map;function vf(i){for(let[t,r]of Zf)if(!i.has(t))el(r),Zf.delete(t)}function Em(i,t){let r=qh(t??"localhost:1");if(i.upstreams.length!==r.length)return!1;return i.upstreams.every((n,f)=>n.url===r[f])}function k$(i){let t=i.cleanUrls??!1,r=Qt(i.path),n=dh(i.auth);if(i.static)return{static:n$(i.static,t),cleanUrls:t,basePath:r,auth:n};let f=i.from??"localhost:1",c=gh(f),l=new URL(c.startsWith("http")?c:`http://${c}`),y=Zf.get(i.id);if(y&&!Em(y,f))el(y),y=void 0;if(!y)y=sh(f,i.loadBalancer),xh(y),Zf.set(i.id,y);return{sourceHost:l.host,upstreamPool:y,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:r,auth:n}}function Ym(i){return i.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??i[0]??"rpx.localhost"}async function Pf(i,t,r=[],n=!1){let f=await Yt(t,i.verbose),c=[...new Set([...f.map((h)=>h.to).filter(Boolean),...r])],l=Ym(c),y=[...new Set([l,...c,"rpx.localhost"])],w=Mh(c,l,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let u=await Yl(w);if(u&&(n||!cl(Al,y)))Y("daemon",`regenerating shared cert for host(s): ${y.join(", ")}`,i.verbose),El(),u=null;if(!u)Y("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Gh({...w,forceRegenerate:!0}),u=await Yl(w);if(!u)throw Error("failed to bootstrap TLS for rpx daemon");return u}async function Bm(i,t,r,n){let f=U.env.SUDO_PASSWORD,c=U.env.HOME??L$(),l=[U.execPath,...U.argv.slice(1)],y=[`HOME=${c}`,`PATH=${U.env.PATH??""}`];if(n)y.push("RPX_VERBOSE=1");for(let[e,E]of Object.entries(U.env))if(E!==void 0&&e!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(e))y.push(`${e}=${E}`);let w=f?["-S","-p","","env",...y,...l]:["-n","env",...y,...l];Y("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,n);let u=s$("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,$=null;if(u.once("error",(e)=>{h=e}),u.once("exit",(e)=>{$=e??0}),f&&u.stdin)u.stdin.write(`${f}
|
|
246
|
+
`),u.stdin.end();u.unref();let A=of(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let e=await er(i);if(e!==null&&ji(e)){if(n)a.success(`rpx daemon elevated to root (pid=${e}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:A,done:Promise.resolve(),stop:async()=>{try{U.kill(e,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if($!==null&&$!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${$}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((E)=>setTimeout(E,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var G$=!1;function xl(){if(G$)return;G$=!0,U.on("uncaughtException",(i)=>{a.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),U.on("unhandledRejection",(i)=>{a.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function V$(i,t,r){let n;try{n=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??n.hostname).split(":")[0];if(n.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let c=t.challengeStore.handlePath(n.pathname);if(c!==void 0)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(r){let c=A$(r,n.pathname);if(c!=null)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${n.pathname}${n.search}`}})}async function TX(i={}){xl();let t=i.verbose??!1,r=i.rpxDir??Ri(),n=i.registryDir??vi.join(r,"registry.d"),f=i.httpsPort??443,c=i.httpPort??80,l=i.hostname??"::",y=i.hostname==null,w=i.gcIntervalMs??Am;if(U.env.RPX_DAEMON_WORKER==="1")return Cm({rpxDir:U.env.RPX_WORKER_RPXDIR??r,registryDir:U.env.RPX_WORKER_REGISTRYDIR??n,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 u=f>0&&f<1024||c>0&&c<1024,h=typeof U.getuid==="function"&&U.getuid()===0;if(U.platform!=="win32"&&u&&!h)return Bm(r,f,c,t);let $=Math.max(1,i.workers??(Number.parseInt(U.env.RPX_WORKERS??"",10)||1));if($>1){if(i.onDemandSites?.enabled)a.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return Um(i,{rpxDir:r,registryDir:n,httpsPort:f,httpPort:c,hostname:l,verbose:t,gcIntervalMs:w,workers:$})}let A=await x$(r),T=new Map,e=(C,J)=>Xl(T,C,J);function E(C){T=Nl(C.map((Wi)=>({host:Wi.to,path:Wi.path,route:k$(Wi)}))),vf(new Set(C.map((Wi)=>Wi.id)));let J=Array.from(T.keys());Y("daemon",`routing table now covers ${J.length} host(s): ${J.join(", ")||"<empty>"}`,t)}await dr(n,t).catch((C)=>{Y("daemon",`initial gc failed: ${C}`,t)}),await or({verbose:t}).catch((C)=>{Y("daemon",`stale hosts GC on start failed: ${C}`,t)});let B=await Yt(n,t);E(B),await Cr({rpxDir:r,verbose:t}).catch((C)=>{Y("daemon",`DNS reconcile on start failed: ${C}`,t)}),await pr(B,{rpxDir:r,verbose:t,ownerPid:U.pid}).catch((C)=>{Y("daemon",`DNS setup on start failed: ${C}`,t)});let m=[];if(i.productionCerts){if(m=await al(i.productionCerts,t),t&&m.length>0)a.info(`SNI: serving ${m.length} real cert(s): ${m.map((C)=>C.serverName).join(", ")}`)}let j=new Set,W=null,S;if(i.onDemandSites?.enabled){if(W=new Hl({resolver:Il(i.onDemandSites),registryDir:n,rpxDir:r,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(C)=>Wl(T,C)!==void 0,onSiteActivating:(C)=>{fn(C)}}),S=async(C)=>{let J=await W.onRequest(C);switch(J.kind){case"ready":return{retry:!0};case"starting":return F$({host:J.host,sinceMs:J.sinceMs,logTail:J.logTail});case"failed":return K$({host:J.host,error:J.error,logTail:J.logTail});case"unknown":default:return}},t)a.info("rpx: on-demand sites enabled")}let F=Ul(e,t,S),I=jl(t),N=null;if(m.length===0)N=await Pf(i,n);let li=i.onDemandTls,yi=li?.enabled?new kf({config:li,certsDir:li.certsDir??i.productionCerts?.certsDir??vi.join(r,"on-demand-certs"),initial:m,verbose:t,onCertAdded:(C)=>{if(Jl()==="restart")Y("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>U.kill(U.pid,"SIGTERM"),10).unref();else K(C)}}):null;function Ur(C){if(C.length>0)return Vr(C.map((J)=>({serverName:J.serverName,cert:J.cert,key:J.key})));return Vr({key:N.key,cert:N.cert,ca:N.ca,requestCert:!1,rejectUnauthorized:!1})}function et(C){try{return Bun.serve(C)}catch(J){let Wi=J instanceof Error?J.message:String(J),Rr=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(Wi);if(!y||C.hostname!=="::"||!Rr)throw J;return Y("daemon",`no IPv6 on this host (${Wi}); binding 0.0.0.0`,i.verbose),Bun.serve({...C,hostname:"0.0.0.0"})}}function jr(C){return et({port:f,hostname:l,reusePort:g$(),tls:Ur(C),fetch(J,Wi){return F(J,Wi)},websocket:I,error(J){return Y("daemon",`https server error: ${J}`,t),new Response(`Server Error: ${J.message}`,{status:500})}})}let nn=(C)=>[...new Set(C.map((J)=>J.to).filter(Boolean))],Ot=(C)=>{if(!N)return m;return Qh([...nn(C),...j,"rpx.localhost"],N)},oi=jr(yi?yi.sniEntries():m.length>0?m:Ot(B)),Jt=null,Gt=!1;async function K(C){if(bi)return;if(Jt=C,Gt)return;Gt=!0;try{while(!bi&&Jt){let J=Jt;Jt=null,Y("daemon",`rebuilding :443 with ${J.length} SNI cert(s)`,t),oi.stop(!1);let Wi,Rr=!1,iy=60,l1=500;for(let l0=0;!bi&&!Rr;l0++)try{oi=jr(J),Rr=!0;break}catch(y1){if(Wi=y1,l0>=iy)break;await new Promise((w1)=>setTimeout(w1,Math.min(25*2**Math.min(l0,4),l1)))}if(!Rr)a.error(`rpx: CRITICAL — could not rebind :443 after ${iy} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Wi?.message}`)}}finally{Gt=!1}}let Fi=null;if(c>0)Fi=et({port:c,hostname:l,fetch(C){return V$(C,yi,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)a.success(`rpx daemon listening on https://${l}:${f}${Fi?` (http→https on :${c})`:""}`),a.info(`pid file: ${A}`),a.info(`registry: ${n}`);async function n0(C){if(bi||m.length>0||yi||!N)return;try{N=await Pf(i,n,[...j]),await K(Ot(C))}catch(J){Y("daemon",`TLS sync on registry change failed: ${J}`,t)}}async function fn(C){if(bi||m.length>0||yi||!N||!C)return;if(j.has(C))return;j.add(C);try{N=await Pf(i,n,[...j],!0);let J=await Yt(n,t);await K(Ot(J))}catch(J){Y("daemon",`dev cert refresh for ${C} failed: ${J}`,t)}}let cn=bf((C)=>{E(C),n0(C),pr(C,{rpxDir:r,verbose:t,ownerPid:U.pid}).catch((J)=>{Y("daemon",`DNS sync on registry change failed: ${J}`,t)})},{dir:n,verbose:t}),Ht=setInterval(()=>{dr(n,t).then((C)=>{if(C>0)Y("daemon",`gc reaped ${C} stale entries`,t)}).catch((C)=>{Y("daemon",`periodic gc failed: ${C}`,t)}),or({verbose:t}).then((C)=>{if(C.length>0)Y("daemon",`gc reaped stale hosts entries: ${C.join(", ")}`,t)}).catch((C)=>{Y("daemon",`periodic hosts gc failed: ${C}`,t)})},w);if(typeof Ht.unref==="function")Ht.unref();let bi=!1,f0,c0=new Promise((C)=>{f0=C});async function ol(){if(bi)return c0;if(bi=!0,clearInterval(Ht),cn.close(),await W?.stopAll().catch((C)=>{Y("daemon",`site supervisor stopAll failed: ${C}`,t)}),oi.stop(!1),Fi?.stop(!1),await mr({rpxDir:r,verbose:t}).catch((C)=>{Y("daemon",`DNS teardown failed: ${C}`,t)}),vf(new Set),await Br(r),t)a.info("rpx daemon stopped");return f0(),c0}let pl=(C)=>{Y("daemon",`received ${C}, shutting down`,t),ol().catch(()=>{})};return U.once("SIGINT",pl),U.once("SIGTERM",pl),{stop:ol,done:c0,httpsPort:typeof oi.port==="number"?oi.port:f,httpPort:Fi&&typeof Fi.port==="number"?Fi.port:c,pidPath:A,ensureCert:(C)=>yi?yi.ensureCert(C):Promise.resolve(!1),listSites:()=>W?.list()??[]}}function kl(i){return vi.join(i,"cluster-sni.json")}async function H$(i,t,r){let n=kl(i),f=`${n}.${U.pid}.tmp`;await Ei.writeFile(f,JSON.stringify({sni:t,dev:r}),"utf8"),await Ei.rename(f,n)}async function q$(i){try{return JSON.parse(await Ei.readFile(kl(i),"utf8"))}catch{return{sni:[],dev:null}}}function em(i){if(i.sni.length>0)return Vr(i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(i.dev)return Vr({key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function mm(){let i=U.execPath,t=U.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let r=vi.basename(i).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&U.argv[1])return[i,U.argv[1],"daemon:start"];return[i,"daemon:start"]}async function Cm(i){xl();let{rpxDir:t,registryDir:r,httpsPort:n,hostname:f,verbose:c}=i,l=new Map,y=(I,N)=>Xl(l,I,N),w=(I)=>{l=Nl(I.map((N)=>({host:N.to,path:N.path,route:k$(N)}))),vf(new Set(I.map((N)=>N.id)))};w(await Yt(r,c));let u=Ul(y,c),h=jl(c),$=!1,A=(I)=>Bun.serve({port:n,hostname:f,reusePort:!0,tls:em(I),fetch(N,li){return u(N,li)},websocket:h,error(N){return Y("daemon",`worker https error: ${N}`,c),new Response(`Server Error: ${N.message}`,{status:500})}}),T=A(await q$(t));async function e(){if($)return;let I=await q$(t),N=null;for(let yi=0;yi<20&&!$;yi++)try{N=A(I);break}catch{await new Promise((Ur)=>setTimeout(Ur,25))}if(!N){Y("daemon","worker reloadTls: could not bind new listener; keeping current",c);return}let li=T;T=N,li.stop(!1)}let E=bf((I)=>w(I),{dir:r,verbose:c}),B=()=>{e().catch(()=>{})};U.on("SIGHUP",B);let m=()=>{let I=U.removeListener??U.off;if(typeof I==="function")I.call(U,"SIGHUP",B)},j,W=new Promise((I)=>{j=I});async function S(){if($)return W;return $=!0,m(),E.close(),T.stop(!1),vf(new Set),j(),W}let F=()=>{S().then(()=>U.exit(0)).catch(()=>U.exit(0))};if(U.once("SIGTERM",F),U.once("SIGINT",F),c)a.success(`rpx worker (pid ${U.pid}) serving :${n}`);return{stop:S,done:W,httpsPort:typeof T.port==="number"?T.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function Um(i,t){xl();let{rpxDir:r,registryDir:n,httpsPort:f,httpPort:c,hostname:l,verbose:y,gcIntervalMs:w,workers:u}=t,h=await x$(r),$=[];if(i.productionCerts)$=await al(i.productionCerts,y);let A=null;if($.length===0)A=await Pf(i,n);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
|
|
247
|
+
`):A.ca}:null,e=!1,E=[];function B(K){for(let Fi of E)try{Fi.kill(K)}catch{}}async function m(K){await H$(r,K,T),B("SIGHUP")}let j=i.onDemandTls,W=j?.enabled?new kf({config:j,certsDir:j.certsDir??i.productionCerts?.certsDir??vi.join(r,"on-demand-certs"),initial:$,verbose:y,onCertAdded:(K)=>{if(Jl()==="restart")Y("on-demand","certificate installed; restarting supervised gateway to reload TLS",y),setTimeout(()=>U.kill(U.pid,"SIGTERM"),10).unref();else m(K)}}):null;await H$(r,W?W.sniEntries():$,T);let S=await Yt(n,y);await Cr({rpxDir:r,verbose:y}).catch((K)=>{Y("daemon",`DNS reconcile on start failed: ${K}`,y)}),await pr(S,{rpxDir:r,verbose:y,ownerPid:U.pid}).catch((K)=>{Y("daemon",`DNS setup on start failed: ${K}`,y)}),await dr(n,y).catch(()=>{}),await or({verbose:y}).catch(()=>{});let F=bf((K)=>{pr(K,{rpxDir:r,verbose:y,ownerPid:U.pid}).catch((Fi)=>{Y("daemon",`DNS sync on registry change failed: ${Fi}`,y)})},{dir:n,verbose:y}),I=setInterval(()=>{dr(n,y).catch(()=>{}),or({verbose:y}).catch(()=>{})},w);I.unref?.();let N=null;if(c>0)N=Bun.serve({port:c,hostname:l,fetch(K){return V$(K,W,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let li=10,yi=60000,Ur=30000,et=0,jr=Date.now();function nn(){if(e)return;let K={...U.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:l,RPX_WORKER_VERBOSE:y?"1":"0"},Fi=Bun.spawn(mm(),{env:K,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n0,fn){if(e)return;let cn=E.indexOf(n0);if(cn!==-1)E.splice(cn,1);let Ht=Date.now();if(Ht-jr>yi)jr=Ht,et=0;if(et++,et>li){a.error(`rpx: worker keeps exiting (code ${fn}); giving up after ${li} restarts in ${Math.round(yi/1000)}s`);return}let bi=Math.min(Ur,100*2**Math.min(et,8));Y("daemon",`worker exited (code ${fn}); respawning in ${bi}ms (restart ${et}/${li})`,y),setTimeout(nn,bi).unref?.()}});E.push(Fi)}for(let K=0;K<u;K++)nn();if(y)a.success(`rpx coordinator listening on https://${l}:${f} via ${u} worker(s)${N?` (http→https on :${c})`:""}`),a.info(`pid file: ${h}`);let Ot,oi=new Promise((K)=>{Ot=K});async function Jt(){if(e)return oi;if(e=!0,clearInterval(I),F.close(),N?.stop(!1),B("SIGTERM"),await Promise.race([Promise.all(E.map((K)=>K.exited)),new Promise((K)=>setTimeout(K,3000))]),B("SIGKILL"),await mr({rpxDir:r,verbose:y}).catch((K)=>{Y("daemon",`DNS teardown failed: ${K}`,y)}),await Br(r),await Ei.unlink(kl(r)).catch(()=>{}),y)a.info("rpx coordinator stopped");return Ot(),oi}let Gt=(K)=>{Y("daemon",`coordinator received ${K}, shutting down`,y),Jt().catch(()=>{})};return U.once("SIGINT",Gt),U.once("SIGTERM",Gt),{stop:Jt,done:oi,httpsPort:f,httpPort:c,pidPath:h,ensureCert:(K)=>W?W.ensureCert(K):Promise.resolve(!1),listSites:()=>[]}}function jm(){let i=U.execPath,t=vi.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 EX(i={}){let t=i.rpxDir??Ri(),r=i.verbose??!1;await Cr({rpxDir:t,verbose:r}).catch((h)=>{Y("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,r)});let n=await er(t);if(n!==null&&ji(n))return Y("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)Y("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await Br(t);await Ei.mkdir(t,{recursive:!0});let f=i.spawnCommand??jm();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");Y("daemon",`spawning daemon: ${f.join(" ")}`,r);let c=s$(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 er(t);if(h!==null&&ji(h))return Y("daemon",`daemon registered with pid=${h}`,r),{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 YX(i={}){let t=i.rpxDir??Ri(),r=i.verbose??!1,n=i.timeoutMs??5000,f=i.pollIntervalMs??50,c=i.forceAfterTimeout??!0,l=await er(t);if(l===null||!ji(l)){if(l!==null)await Br(t);return await Cr({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{U.kill(l,"SIGTERM")}catch(w){let u=w.code;if(u==="ESRCH")return await Br(t),{stopped:!1,pid:l,forced:!1};if(u==="EPERM")Wt(`kill -TERM ${l}`);else throw w}let y=Date.now()+n;while(Date.now()<y){if(!ji(l))return Y("daemon",`daemon pid=${l} stopped cleanly`,r),{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 ${n}ms`);Y("daemon",`daemon pid=${l} did not exit, escalating to SIGKILL`,r);try{U.kill(l,"SIGKILL")}catch(w){let u=w.code;if(u==="EPERM")Wt(`kill -KILL ${l}`);else if(u!=="ESRCH")throw w}return await Br(t),await mr({rpxDir:t,verbose:r}).catch((w)=>{Y("daemon",`DNS teardown after SIGKILL: ${w}`,r)}),{stopped:!0,pid:l,forced:!0}}async function BX(i={}){let t=i.rpxDir??Ri();if(await Tm(t))return;await Cr({rpxDir:t,verbose:i.verbose})}import*as at from"node:fs/promises";import{homedir as Rm}from"node:os";import*as Vl from"node:path";var pf=1,Nm="dns-state.json",d$=["com","test","dev","app","page","local","localhost","example","invalid"];function D$(){return Vl.join(Rm(),".stacks","rpx")}function dl(i=D$()){return Vl.join(i,Nm)}async function i0(i=D$()){try{let t=await at.readFile(dl(i),"utf8"),r=JSON.parse(t);if(r.version!==pf||!Array.isArray(r.resolvers))return null;return{version:pf,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function b$(i,t){await at.mkdir(i,{recursive:!0}),await at.writeFile(dl(i),`${JSON.stringify(t,null,2)}
|
|
248
|
+
`,"utf8")}async function Dl(i){await at.rm(dl(i),{force:!0})}function P$(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function Wm(i){let t=P$(i);if(!t)return null;let r=t.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function bl(i){let t=new Set;for(let r of i){let n=Wm(r);if(n)t.add(n)}return Array.from(t).sort()}function Pl(i){let t=new Set;for(let r of i){let n=P$(r);if(n)t.add(n)}return Array.from(t).sort()}var r0=15353,Xm="# managed-by: rpx",p$="/etc/resolver",Ni=null,t0=new Set;function i1(i){return{id:i.readUInt16BE(0),flags:i.readUInt16BE(2),qdcount:i.readUInt16BE(4),ancount:i.readUInt16BE(6),nscount:i.readUInt16BE(8),arcount:i.readUInt16BE(10)}}function t1(i,t,r=0){let n=[],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||r>=10)break;let y=i.readUInt16BE(f)&16383,{name:w}=t1(i,y,r+1);if(w)n.push(w);f+=2;break}if(f++,f+l>i.length)break;n.push(i.subarray(f,f+l).toString("ascii")),f+=l}return{name:n.join("."),newOffset:f}}function Sm(i,t){let{name:r,newOffset:n}=t1(i,t),f=i.readUInt16BE(n),c=i.readUInt16BE(n+2);return{question:{name:r,type:f,class:c},newOffset:n+4}}function tn(i){let t=i.split("."),r=[];for(let n of t)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function am(i,t,r){let n=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),n.push(f),n.push(tn(t.name));let c=Buffer.alloc(4);c.writeUInt16BE(t.type,0),c.writeUInt16BE(t.class,2),n.push(c),n.push(tn(t.name));let l=Buffer.alloc(10);if(l.writeUInt16BE(t.type,0),l.writeUInt16BE(1,2),l.writeUInt32BE(300,4),t.type===1){l.writeUInt16BE(4,8),n.push(l);let y=r.split(".").map((w)=>Number.parseInt(w,10));n.push(Buffer.from(y))}else if(t.type===28)l.writeUInt16BE(16,8),n.push(l),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,tn(t.name),c]);return Buffer.concat(n)}function Jm(i,t){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(i,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(tn(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),r.push(f),Buffer.concat(r)}async function Fm(i,t){if(Bt.platform!=="darwin")return!1;let r=Pl(i);if(r.length===0)return!1;if(Ni){for(let n of r)t0.add(n);return Y("dns","DNS server already running — merged domains",t),!0}return t0=new Set(r),new Promise((n)=>{Ni=Z$.createSocket("udp4"),Ni.on("error",(f)=>{Y("dns",`DNS server error: ${f.message}`,t),Ni?.close(),Ni=null,n(!1)}),Ni.on("message",(f,c)=>{try{let l=i1(f),{question:y}=Sm(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 t0)if(w===$||w.endsWith(`.${$}`)){u=!0;break}let h;if(u&&(y.type===1||y.type===28))h=am(l.id,y,"127.0.0.1"),Y("dns",`Responding with localhost for ${y.name}`,t);else h=Jm(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),n(!0)});try{Ni.bind(r0,"127.0.0.1")}catch(f){Y("dns",`Failed to bind DNS server: ${f}`,t),n(!1)}})}function r1(i){if(Ni)Y("dns","Stopping DNS server",i),Ni.close(),Ni=null,t0=new Set}function XX(){return Ni!==null}async function Km(i,t=500){let r=i.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let f=Z$.createSocket("udp4"),c=setTimeout(()=>{f.close(),n(!1)},t);f.on("message",(y)=>{clearTimeout(c),f.close();try{let w=i1(y);n(w.ancount>0)}catch{n(!1)}}),f.on("error",()=>{clearTimeout(c),f.close(),n(!1)});let l=Im(r,1);f.send(l,r0,"127.0.0.1",(y)=>{if(y)clearTimeout(c),f.close(),n(!1)})})}function Im(i,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([tn(i),Buffer.from([0,t,0,1])]);return Buffer.concat([r,n])}function _m(){return`${Xm}
|
|
249
249
|
nameserver 127.0.0.1
|
|
250
|
-
port ${
|
|
251
|
-
`}function
|
|
252
|
-
export{
|
|
250
|
+
port ${r0}
|
|
251
|
+
`}function rn(i){return o$.join(p$,i)}function zm(i){return i.includes("127.0.0.1")&&i.includes(String(r0))}async function Qm(i){try{return await v$.readFile(rn(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Zl(i){if(Bt.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:n}=await import("./chunk-bvq3wmhm.js");if(!n()&&!r()){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 n1(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function Mm(i,t){n1(i);let{execSudoSync:r}=await import("./chunk-bvq3wmhm.js"),n=_m().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${p$} && printf "%b" "${n}" > ${rn(i)}'`;r(f),Y("dns",`Created ${rn(i)}`,t)}async function Om(i,t){n1(i);let{execSudoSync:r}=await import("./chunk-bvq3wmhm.js");r(`rm -f ${rn(i)}`),Y("dns",`Removed ${rn(i)}`,t)}async function SX(i,t){return c1({domains:t??[],verbose:i})}async function Gm(i,t){if(Bt.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-bvq3wmhm.js");if(!n()&&!r())return Y("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await Mm(f,t);return await Zl(t),!0}catch(f){return Y("dns",`Failed to create resolver file: ${f}`,t),!1}}async function vl(i,t){if(Bt.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-bvq3wmhm.js");if(!n()&&!r())return;try{for(let f of i)await Om(f,t);await Zl(t)}catch(f){Y("dns",`Failed to remove resolver files: ${f}`,t)}}async function f1(i){if(Bt.platform!=="darwin")return[];let t=[];for(let r of d$){let n=await Qm(r);if(n&&zm(n))await vl([r],i),t.push(r)}return t}async function c1(i){let t=i.rpxDir??Ri(),r=Pl(i.domains);if(r.length===0)return!1;let n=bl(r),f=await Fm(r,i.verbose);if(!f){let y=r[0];if(y&&await Km(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 Gm(n,i.verbose))return!1;let l={version:pf,resolvers:n,domains:r,ownerPid:i.ownerPid??Bt.pid,updatedAt:new Date().toISOString()};return await b$(t,l),!0}async function pr(i,t={}){let r=i.map((w)=>w.to).filter(Boolean),n=t.rpxDir??Ri(),f=bl(r),y=((await i0(n))?.resolvers??[]).filter((w)=>!f.includes(w));if(y.length>0)await vl(y,t.verbose);if(f.length===0){r1(t.verbose),await Dl(n);return}await c1({domains:r,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??Bt.pid})}async function mr(i={}){let t=i.rpxDir??Ri();r1(i.verbose);let n=(await i0(t))?.resolvers??[];await vl(n,i.verbose),await f1(i.verbose),await Dl(t)}async function aX(i){await mr({verbose:i})}async function Cr(i={}){let t=i.rpxDir??Ri(),r=await i0(t),n=r?.ownerPid!=null&&ji(r.ownerPid);if(r&&!n){Y("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,i.verbose),await mr(i);return}let f=await f1(i.verbose);if(f.length>0)Y("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await Zl(i.verbose)}
|
|
252
|
+
export{a,Sh as b,WB as c,_t as d,fl as e,cl as f,XB as g,SB as h,Pi as i,Et as j,ll as k,Hr as l,yl as m,ah as n,Gf as o,qr as p,gr as q,wl as r,Al as s,Qh as t,Mh as u,Tl as v,ON as w,GN as x,HN as y,Gh as z,El as A,Yl as B,Bl as C,qN as D,Hh as E,gh as F,sh as G,Lh as H,qf as I,sr as J,xh as K,el as L,VB as M,dh as N,Dh as O,bN as P,r$ as Q,n$ as R,me as S,Ce as T,Ue as U,f$ as V,w$ as W,Ul as X,jl as Y,u$ as Z,A$ as _,Lf as $,Rl as aa,T$ as ba,Qt as ca,Xe as da,Nl as ea,Wl as fa,Xl as ga,Vr as ha,Se as ia,al as ja,Jl as ka,Ke as la,Y$ as ma,kf as na,Kl as oa,B$ as pa,He as qa,qe as ra,se as sa,Il as ta,eW as ua,R$ as va,_l as wa,N$ as xa,UW as ya,St as za,Ql as Aa,ji as Ba,X$ as Ca,Ol as Da,de as Ea,Yt as Fa,dr as Ga,bf as Ha,Hl as Ia,Yr as Ja,F$ as Ka,K$ as La,_$ as Ma,vr as Na,O$ as Oa,hm as Pa,$m as Qa,LW as Ra,xW as Sa,kW as Ta,VW as Ua,or as Va,pf as Wa,d$ as Xa,P$ as Ya,Wm as Za,bl as _a,Pl as $a,r0 as ab,Xm as bb,Fm as cb,r1 as db,XX as eb,Km as fb,rn as gb,zm as hb,SX as ib,f1 as jb,c1 as kb,pr as lb,mr as mb,aX as nb,Cr as ob,Ri as pb,of as qb,er as rb,Tm as sb,x$ as tb,Br as ub,TX as vb,jm as wb,EX as xb,YX as yb,BX as zb};
|