@stacksjs/rpx 0.11.13 → 0.11.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,161 @@
1
+ import{Da as O,Fa as yr,Ga as $,Ka as aa,La as os,Na as re,Oa as oa,Qa as Ea,Ra as ua}from"./chunk-hf6e07v4.js";import O0 from"node:dgram";import*as Xa from"node:fs/promises";import*as _a from"node:path";import*as fi from"node:process";import{spawn as Ua}from"node:child_process";import*as Gt from"node:fs/promises";import{homedir as Ss}from"node:os";import*as Nt from"node:path";import*as N from"node:process";var K={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};import{execSync as pi}from"node:child_process";import D from"node:fs/promises";import*as as from"node:os";import{homedir as ne}from"node:os";import{join as tt}from"node:path";import*as Mt from"node:process";import{createRequire as La}from"node:module";import{Resolver as ye}from"node:dns/promises";import{createHash as xa,sign as qa}from"node:crypto";import{createHash as ka}from"node:crypto";import{sign as ba}from"node:crypto";import{generateKeyPairSync as Ll,X509Certificate as io}from"node:crypto";import we from"node:os";import $e from"node:path";import{existsSync as Os,statSync as Hs}from"fs";import{existsSync as no,mkdirSync as sm,readdirSync as lm,readFileSync as eo,writeFileSync as cm}from"fs";import{homedir as Ti}from"os";import{dirname as om,resolve as gt}from"path";import on from"process";import{existsSync as Ks,statSync as Ms}from"fs";import{existsSync as Me,mkdirSync as fo,readdirSync as so,writeFileSync as lo}from"fs";import{homedir as Ci}from"os";import{dirname as zs,resolve as at}from"path";import di from"process";import{join as co,relative as ho,resolve as Ls}from"path";import Dr from"process";import{existsSync as Gl,mkdirSync as Cm,readdirSync as gm,writeFileSync as Sm}from"fs";import{homedir as me}from"os";import{dirname as Ym,resolve as ht}from"path";import nr from"process";import{join as ao,relative as oo,resolve as Gs}from"path";import pr from"process";import{existsSync as xl,mkdirSync as Wm,readdirSync as Xm,writeFileSync as _m}from"fs";import{dirname as Jm,resolve as Vr}from"path";import ze from"process";import{Buffer as si}from"buffer";import{createCipheriv as uo,createDecipheriv as yo,randomBytes as de}from"crypto";import{closeSync as Ae,createReadStream as xs,createWriteStream as wo,existsSync as Ee,fsyncSync as qs,openSync as ks,writeFileSync as $o}from"fs";import{access as mo,constants as bs,mkdir as Ao,readdir as Rr,rename as Ds,stat as gi,unlink as Yr,writeFile as Te}from"fs/promises";import{join as Si}from"path";import nt from"process";import{pipeline as Eo}from"stream/promises";import{createGzip as ps}from"zlib";import Bi from"process";import Dt from"process";import{Buffer as qt}from"buffer";import{createCipheriv as To,createDecipheriv as Co,randomBytes as Ce}from"crypto";import{closeSync as ge,createReadStream as Vs,createWriteStream as go,existsSync as Ur,fsyncSync as Ps,openSync as vs,writeFileSync as So}from"fs";import{access as Bo,constants as Qs,mkdir as Ro,readdir as Fr,rename as Zs,stat as Ri,unlink as Nr,writeFile as Se}from"fs/promises";import{isAbsolute as Yo,join as Yi,resolve as Uo}from"path";import _ from"process";import{pipeline as Fo}from"stream/promises";import{createGzip as tl}from"zlib";import Ui from"process";import pt from"process";import jr from"process";import{existsSync as Wr}from"fs";import{resolve as Be}from"path";import{existsSync as No}from"fs";import{existsSync as jo,readdirSync as Wo}from"fs";import{extname as Re,resolve as il}from"path";import Xo from"process";import{join as _o,relative as Io,resolve as rl}from"path";import Pr from"process";import{Buffer as kt}from"buffer";import{createCipheriv as Jo,createDecipheriv as Oo,randomBytes as Ye}from"crypto";import{closeSync as Ue,createReadStream as nl,createWriteStream as Ho,existsSync as Xr,fsyncSync as el,openSync as fl,writeFileSync as Ko}from"fs";import{access as Mo,constants as sl,mkdir as zo,readdir as _r,rename as ll,stat as Fi,unlink as Ir,writeFile as Fe}from"fs/promises";import{isAbsolute as Lo,join as Ni,resolve as Go}from"path";import I from"process";import{pipeline as xo}from"stream/promises";import{createGzip as cl}from"zlib";import ji from"process";import Vt from"process";import Jr from"process";import{existsSync as Or}from"fs";import{resolve as Ne}from"path";import{existsSync as qo}from"fs";import{exec as uy}from"node:child_process";import gl from"node:fs";import yy from"node:os";import Xt from"node:path";import Rc from"node:process";import{promisify as wy}from"node:util";import Ii from"node:crypto";import Pt from"node:fs";import Ze from"node:path";import{execSync as Ul}from"node:child_process";import hn from"node:os";var Ga=La(import.meta.url);async function Fl(t,i,r={}){let n=r.timeoutMs??120000,e=r.intervalMs??3000,f=t.split(".").slice(-2).join("."),s;try{let h=new ye,a=await h.resolveNs(f),o=(await Promise.all(a.map((y)=>h.resolve4(y).catch(()=>[])))).flat();if(o.length>0)s=new ye,s.setServers(o)}catch{}let c=Date.now()+n,l=s??new ye;for(;;){try{if((await l.resolveTxt(t)).some((h)=>h.join("")===i))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((h)=>setTimeout(h,e))}}class rr{tokens=new Map;add(t,i){this.tokens.set(t,i)}get(t){return this.tokens.get(t)}remove(t){this.tokens.delete(t)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(t){let i=t.indexOf(rr.PATH_PREFIX);if(i===-1)return;let r=t.slice(i+rr.PATH_PREFIX.length);return this.get(r)}}var an=new rr;function Mr(t){return(typeof t==="string"?Buffer.from(t,"utf8"):Buffer.from(t)).toString("base64url")}function Je(t){return Buffer.from(t,"base64url")}function Nl(t){let i=t.export({format:"jwk"});if(i.kty!=="EC"||i.crv!=="P-256"||!i.x||!i.y)throw Error(`Expected a P-256 EC public key, got kty=${i.kty} crv=${i.crv}`);return{crv:"P-256",kty:"EC",x:i.x,y:i.y}}function jl(t){let i=`{"crv":"${t.crv}","kty":"${t.kty}","x":"${t.x}","y":"${t.y}"}`;return xa("sha256").update(i).digest("base64url")}function Wl(t){let{protectedHeader:i,payload:r,privateKey:n}=t,e=Mr(JSON.stringify(i)),f=r===""?"":Mr(JSON.stringify(r)),s=`${e}.${f}`,c=qa("sha256",Buffer.from(s),{key:n,dsaEncoding:"ieee-p1363"});return{protected:e,payload:f,signature:Mr(c)}}var Xl="https://acme-staging-v02.api.letsencrypt.org/directory",_l="https://acme-v02.api.letsencrypt.org/directory";class kr extends Error{problem;httpStatus;constructor(t,i,r){super(t);this.name="AcmeError",this.problem=i,this.httpStatus=r}}class br{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(t){this.directoryUrl=t.directoryUrl,this.accountKey=t.accountKey,this.jwk=Nl(t.accountPublicKey),this.thumbprint=jl(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let t=await fetch(this.directoryUrl);if(!t.ok)throw Error(`Failed to fetch ACME directory: HTTP ${t.status}`);return this.directoryCache=await t.json(),this.directoryCache}async newNonce(){let t=await this.directory(),i=(await fetch(t.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!i)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=i,i}async ensureNonce(){if(this.nonce){let t=this.nonce;return this.nonce=void 0,t}return this.newNonce()}async signedPost(t){let{url:i,payload:r,useJwk:n}=t,e={alg:"ES256",nonce:await this.ensureNonce(),url:i};if(n)e.jwk=this.jwk;else e.kid=this.requireKid();let f=Wl({protectedHeader:e,payload:r,privateKey:this.accountKey}),s=await fetch(i,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(f)}),c=s.headers.get("replay-nonce");if(c)this.nonce=c;let l=s.headers.get("content-type")??"",h;if(l.includes("application/pem-certificate-chain")||l.startsWith("text/"))h=await s.text();else{let a=await s.text();h=a?JSON.parse(a):{}}if(s.status>=400){let a=h??{};throw new kr(`ACME request to ${i} failed (HTTP ${s.status}): ${a.type??""} ${a.detail??""}`.trim(),a,s.status)}return{status:s.status,headers:s.headers,body:h,location:s.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(t={}){let i=await this.directory(),r={termsOfServiceAgreed:!0};if(t.email)r.contact=[`mailto:${t.email}`];let n=await this.signedPost({url:i.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(t){let i=await this.directory(),r={identifiers:t.map((e)=>({type:"dns",value:e}))},n=await this.signedPost({url:i.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(t){return(await this.signedPost({url:t,payload:""})).body}keyAuthorization(t){return`${t}.${this.thumbprint}`}dns01TxtValue(t){return ka("sha256").update(this.keyAuthorization(t)).digest("base64url")}async notifyChallengeReady(t){await this.signedPost({url:t,payload:{}})}async pollAuthorization(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getAuthorization(t);if(f.status==="valid")return;if(f.status==="invalid"){let s=f.challenges.find((c)=>c.status==="invalid");throw new kr(`Authorization for ${f.identifier.value} became invalid: ${s?.error?.detail??"unknown reason"}`,s?.error??{},0)}await Js(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${t} to become valid`)}async finalizeOrder(t,i){return(await this.signedPost({url:t,payload:{csr:i}})).body}async getOrder(t){return(await this.signedPost({url:t,payload:""})).body}async pollOrder(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getOrder(t);if(f.status==="valid"){if(!f.certificate)throw Error("ACME order is valid but has no certificate URL");return f.certificate}if(f.status==="invalid")throw Error(`ACME order ${t} became invalid`);await Js(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${t} to become valid`)}async downloadCertificate(t){let i=await this.signedPost({url:t,payload:""});return typeof i.body==="string"?i.body:String(i.body)}static selectChallenge(t,i){let r=t.challenges.find((n)=>n.type===i);if(!r)throw Error(`No ${i} challenge available for ${t.identifier.value}`);return r}}function Il(t){let i=t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=i[0];if(!r)return{certPem:`${t.trim()}
2
+ `,chainPem:""};let n=`${r.trim()}
3
+ `,e=i.slice(1).map((f)=>f.trim()).join(`
4
+ `);return{certPem:n,chainPem:e?`${e}
5
+ `:""}}function Jl(t){return`_acme-challenge.${t.startsWith("*.")?t.slice(2):t}`}function Js(t){return new Promise((i)=>setTimeout(i,t))}function Da(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function hi(t,i){return Buffer.concat([Buffer.from([t]),Da(i.length),i])}function Ol(t){let i;if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=[],n=t;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);i=Buffer.from(r)}else if(i=t.length===0?Buffer.from([0]):t,i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return hi(2,i)}function mi(t){let i=t.split(".").map(Number);if(i.length<2)throw Error(`Invalid OID: ${t}`);let r=[40*i[0]+i[1]];for(let n=2;n<i.length;n++){let e=i[n],f=[e&127];e=Math.floor(e/128);while(e>0)f.unshift(e&127|128),e=Math.floor(e/128);r.push(...f)}return hi(6,Buffer.from(r))}function Ct(...t){return hi(48,Buffer.concat(t))}function Oe(...t){return hi(49,Buffer.concat(t))}function He(t){return hi(3,Buffer.concat([Buffer.from([0]),t]))}function Hl(t){return hi(4,t)}function Kl(t){return hi(12,Buffer.from(t,"utf8"))}function Ke(t,i,r){let n=128|(r?32:0)|t;return hi(n,i)}var pa="1.2.840.10045.2.1",Va="1.2.840.10045.3.1.7",Pa="1.2.840.10045.4.3.2",va="2.5.4.3",Qa="1.2.840.113549.1.9.14",Za="2.5.29.17";function to(t){let i=t.export({format:"jwk"});if(!i.x||!i.y)throw Error("Public key JWK is missing x/y coordinates");let r=Je(i.x),n=Je(i.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 Ml(t){let{domains:i,publicKey:r,privateKey:n}=t;if(i.length===0)throw Error("At least one domain is required to build a CSR");let e=Ct(Oe(Ct(mi(va),Kl(i[0])))),f=Ct(Ct(mi(pa),mi(Va)),He(to(r))),s=i.map((w)=>Ke(2,Buffer.from(w,"ascii"),!1)),c=Ct(...s),l=Ct(mi(Za),Hl(c)),h=Ct(l),a=Ct(mi(Qa),Oe(h)),o=Ke(0,a,!0),y=Ct(Ol(0),e,f,o),u=ba("sha256",y,n),m=Ct(mi(Pa));return Ct(y,m,He(u))}function zl(t){return Ml(t).toString("base64url")}function ro(t){if(t){let{createPrivateKey:e,createPublicKey:f}=Ga("node:crypto"),s=e(t),c=f(s);return{privateKey:s,publicKey:c,pem:t}}let{privateKey:i,publicKey:r}=Ll("ec",{namedCurve:"P-256"}),n=i.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:i,publicKey:r,pem:n}}async function tf(t){let{domains:i,method:r}=t;if(i.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!t.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(i.some((o)=>o.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=t.directoryUrl??(t.staging===!1?_l:Xl),e=ro(t.accountKeyPem),f=new br({directoryUrl:n,accountKey:e.privateKey,accountPublicKey:e.publicKey});await f.newAccount({email:t.email});let{order:s,orderUrl:c}=await f.newOrder(i),l=t.http01Store??an,h=[],a=[];try{for(let X of s.authorizations){let xt=await f.getAuthorization(X);if(xt.status==="valid")continue;let jt=br.selectChallenge(xt,r);if(r==="dns-01"){let Qi=Jl(xt.identifier.value),Lt=f.dns01TxtValue(jt.token);await t.dnsProvider.setTxt(Qi,Lt),h.push({name:Qi,value:Lt}),await Fl(Qi,Lt,{timeoutMs:t.dnsPropagationTimeoutMs??120000})}else l.add(jt.token,f.keyAuthorization(jt.token)),a.push(jt.token);await f.notifyChallengeReady(jt.url),await f.pollAuthorization(X,{timeoutMs:t.timeoutMs})}let{privateKey:o,publicKey:y}=Ll("ec",{namedCurve:"P-256"}),u=zl({domains:i,publicKey:y,privateKey:o});await f.finalizeOrder(s.finalize,u);let m=await f.pollOrder(c,{timeoutMs:t.timeoutMs}),w=await f.downloadCertificate(m),{certPem:d,chainPem:A}=Il(w),T=A?`${d}${A}`:d,Y=o.export({format:"pem",type:"pkcs8"}).toString(),S=new Date(new io(d).validTo);return{certPem:d,keyPem:Y,chainPem:A,fullChainPem:T,accountKeyPem:e.pem,notAfter:S}}finally{for(let{name:o,value:y}of h)await t.dnsProvider?.removeTxt(o,y).catch(()=>{});for(let o of a)l.remove(o)}}class ql{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),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(t,i){try{if(!Os(t))return!0;return Hs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Os(r)?Hs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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 t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class kl{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var vr=new ql,rf=new kl,ko=Object.defineProperty,bo=(t)=>t;function Do(t,i){this[t]=bo.bind(null,i)}var po=(t,i)=>{for(var r in i)ko(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Do.bind(i,r)})},Vo=(t,i)=>()=>(t&&(i=t(t=0)),i),bl={};po(bl,{withErrorRecovery:()=>Vl,tryLoadConfig:()=>Au,loadConfigWithResult:()=>mu,loadConfig:()=>tc,isRetryableError:()=>au,isConfigNotFoundError:()=>hu,isBunfigError:()=>Pl,globalPerformanceMonitor:()=>lr,globalCache:()=>Xi,getEnvOrDefault:()=>ou,generateConfigTypes:()=>Eu,defaultGeneratedDir:()=>cc,defaultConfigDir:()=>lc,deepMergeWithArrayStrategy:()=>lf,deepMerge:()=>vl,createLibraryConfig:()=>Tu,config:()=>du,bunfigPlugin:()=>Cu,applyEnvVarsToConfig:()=>tr,TypeGenerationError:()=>De,SchemaValidationError:()=>fr,PluginError:()=>Ve,PerformanceMonitor:()=>ef,FileSystemError:()=>be,ErrorFactory:()=>ci,EnvVarError:()=>en,EnvProcessor:()=>un,ConfigValidator:()=>cf,ConfigValidationError:()=>qe,ConfigNotFoundError:()=>nn,ConfigMergeError:()=>ke,ConfigLoader:()=>hf,ConfigLoadError:()=>er,ConfigFileLoader:()=>yn,ConfigCache:()=>nf,CacheUtils:()=>rc,BunfigError:()=>dt,BrowserConfigError:()=>pe,ArrayMergeStrategies:()=>fc});class nf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),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(t,i){try{if(!Ks(t))return!0;return Ms(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Ks(r)?Ms(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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 t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ef{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Po(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function vo(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Qo(t){return t.getStats().size*2}function ff(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((f)=>G(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((f)=>G(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Qr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=ff(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let s of r[n])if(G(s)&&"name"in s){if(!f.find((c)=>G(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((c)=>G(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Qr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Qr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Qr(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Qr(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Zo(t,i){if(!xl(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return ff(i,n)}catch{return null}}catch{return null}}async function tu({name:t="",cwd:i,defaultConfig:r}){let n=i||ze.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Vr(n,`${s}${c}`),h=await Zo(l,r);if(h!==null)return h}try{let s=Vr(n,"package.json");if(xl(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return ff(r,c)}catch{}}}catch{}return r}function iu(t,i={}){let r=pr.cwd();while(r.includes("storage"))r=Gs(r,"..");let n=Gs(r,t||"");if(i?.relative)return oo(pr.cwd(),n);return n}async function ru(){try{let t=await tu({name:"clarity",defaultConfig:Lr,cwd:pr.cwd(),endpoint:"",headers:{}});return{...Lr,...t}}catch{return Lr}}function q(){if(Dt.env.NODE_ENV==="test"||Dt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nu(){if(Dt.env.NODE_ENV==="test"||Dt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Dt<"u"){let t=Dt.type;if(t==="renderer"||t==="worker")return!1;return!!(Dt.versions&&(Dt.versions.node||Dt.versions.bun))}return!1}class Dl{async format(t){let i=await nu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Bi.pid,hostname:i(),environment:Bi.env.NODE_ENV||"development",platform:Bi.platform,version:Bi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Bi.env.NODE_ENV||Bi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Zr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Ge},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Dl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??nt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Gr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Gr};return{...Gr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ge.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await mo(this.config.logDirectory,bs.F_OK|bs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ao(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:si.from(t);try{if(!Ee(this.currentLogFile))await Te(this.currentLogFile,"",{mode:420});if(n=ks(this.currentLogFile,"a",420),$o(n,c,{flag:"a"}),qs(n),n!==void 0)Ae(n),n=void 0;if((await gi(this.currentLogFile)).size===0){if(await Te(this.currentLogFile,c,{flag:"w",mode:420}),(await gi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let o=s*2**e;await new Promise((y)=>setTimeout(y,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Ae(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}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 Si(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 Si(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Si(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(q())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,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 t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return de(16).toString("hex")}generateKey(){return de(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=de(16),n=uo("aes-256-gcm",i,r),e=si.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:si.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ps(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(si.from(si.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(q())return;let t=await gi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Rr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await gi(r).catch(()=>null))try{if(await Ds(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Yr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Te(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await gi(r).catch(()=>null))await Ds(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Rr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Yr(Si(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=xs(t),n=wo(i),e=ps();await Eo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!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(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ee(this.currentLogFile))try{let t=ks(this.currentLogFile,"r+");qs(t),Ae(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Rr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Yr(Si(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?M.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=nt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${M.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!q()){let h=nc[t],a=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:M.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:M.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o),c){let y=c.split(`
6
+ `);for(let u of y)if(u.trim()&&!u.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:M.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!q()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
7
+ `;if(c)l+=`${c}
8
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!q()){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:M.blue("◐"),tag:r,message:`${M.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
9
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:M.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!q())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!Ee(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xs(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.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=si.isBuffer(t)?t:si.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=yo("aes-256-gcm",r,e);return c.setAuthTag(f),si.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q()}isServerMode(){return!q()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!q()){let f=t.split(`
10
+ `),s=Math.max(...f.map((a)=>a.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((a)=>{let o=" ".repeat(s-a.length-2);return`│ ${a}${o} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(c)})),h.forEach((a)=>console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(a),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(l),showTimestamp:!1}))}else if(!q())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
11
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(q())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${M.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();nt.stdin.removeListener("data",r);try{if(typeof nt.stdin.setRawMode==="function")nt.stdin.setRawMode(!1)}catch{}nt.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof nt.stdin.setRawMode==="function")nt.stdin.setRawMode(!0)}catch{}nt.stdin.resume(),nt.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let e=/%([sdijfo%])/g,f=0;if(r=t.replace(e,(s,c)=>{if(c==="%")return"%";if(f>=i.length)return s;let l=i[f++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return s}}),f<i.length)r+=` ${i.slice(f).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!q()){let e=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",f=M.blue("◐");console.error(`${f} ${e} ${M.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
12
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(t,i=""){if(!this.enabled||!this.fancy||q()||t<=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:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())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,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;nt.stdout.write(`${"\r".padEnd(nt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||q()||!nt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=M.green("━".repeat(n)),s=M.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=i||r===100?M.green("✓"):M.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",y=`\r${a}${o} ${c} ${l}${h}`,u=nt.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,nt.stdout.write(t.lastRenderedLine),i)nt.stdout.write(`
13
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||q()||!nt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Rr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Si(this.config.logDirectory,n);if(t.before)try{if((await gi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}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 Yr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function zr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&J(i[0])&&"id"in i[0]&&i[0].id===3&&J(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(J(i)&&J(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(J(t)&&"arr"in t&&Array.isArray(t.arr)&&J(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&J(i[0])&&J(t[0])){let n=[...i];for(let e of t)if(J(e)&&"name"in e){if(!n.find((f)=>J(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(J(e)&&"path"in e){if(!n.find((f)=>J(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>tn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!J(i)||!J(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(J(e)&&J(r[n]))r[n]=zr(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&J(e[0])&&J(r[n][0])){let f=[...e];for(let s of r[n])if(J(s)&&"name"in s){if(!f.find((c)=>J(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(J(s)&&"path"in s){if(!f.find((c)=>J(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>tn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function sf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:zr(t,i);if(Array.isArray(t))return r==="replace"?i:zr(t,i);if(!J(i)||!J(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=zr(s,f);else if(J(f)&&J(s))n[e]=sf(s,f,r);else n[e]=f}return n}function tn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!tn(t[r],i[r]))return!1;return!0}if(J(t)&&J(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!tn(t[e],i[e]))return!1}return!0}return!1}function J(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Hr(t,i,r="replace"){if(!Gl(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return sf(i,e,r)}catch{return null}}catch{return null}}function eu(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${n}_${o.map(y).join("_")}`,m=`${n}_${o.map((w)=>w.toUpperCase()).join("_")}`;if(r)ft.info(`Checking environment variable ${u} for config ${t}.${o.join(".")}`);if(typeof a==="object"&&a!==null&&!Array.isArray(a))l[h]=f(a,o);else{let w=nr.env[u]||nr.env[m];if(w!==void 0){if(r)ft.info(`Using environment variable ${w?u:m} for config ${t}.${o.join(".")}`);if(typeof a==="number")l[h]=Number(w);else if(typeof a==="boolean")l[h]=w.toLowerCase()==="true";else if(Array.isArray(a))try{let d=JSON.parse(w);if(Array.isArray(d))l[h]=d;else l[h]=w.split(",").map((A)=>A.trim())}catch{l[h]=w.split(",").map((d)=>d.trim())}else l[h]=w}}}return l}return f(e)}async function fu({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?eu(t,e,f):e,h=r||nr.cwd(),a=[".ts",".js",".mjs",".cjs",".json"];if(f)ft.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],w=Array.from(new Set([h,ht(h,"config"),ht(h,".config"),n?ht(h,n):void 0].filter(Boolean)));for(let d of w){if(f)ft.info(`Searching for configuration in: ${d}`);let A=[ht(h,"config"),ht(h,".config")].concat(n?[ht(h,n)]:[]).includes(d)?[...o,...y,...u,...m]:[...y,...o,...m,...u];for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from: ${S}`);return X}}}if(t){let d=ht(me(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)ft.info(`Checking user config directory: ${d}`);for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user config directory: ${S}`);return X}}}if(t){let d=ht(me(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)ft.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user config directory dotfile: ${S}`);return X}}}if(t){let d=me(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)ft.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user home directory: ${S}`);return X}}}try{let d=ht(h,"package.json");if(Gl(d)){let A=await import(d),T=A[t];if(!T&&i){if(T=A[i],T&&f)ft.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)ft.success(`Configuration loaded from package.json: ${T===A[t]?t:i}`);return sf(l,T,c)}catch(Y){if(f)ft.warn("Failed to merge package.json config:",Y)}}}catch(d){if(f)ft.warn("Failed to load package.json:",d)}if(f)ft.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function su(t,i={}){let r=Dr.cwd();while(r.includes("storage"))r=Ls(r,"..");let n=Ls(r,t||"");if(i?.relative)return ho(Dr.cwd(),n);return n}async function lu(){try{let t=await fu({name:"clarity",alias:"logging",defaultConfig:xr,cwd:Dr.cwd()});return{...xr,...t||{}}}catch{return xr}}function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cu(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class pl{async format(t){let i=await cu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ui.pid,hostname:i(),environment:Ui.env.NODE_ENV||"development",platform:Ui.platform,version:Ui.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ui.env.NODE_ENV||Ui.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rn{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(t,i={}){this.name=t,this.config={...xe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new pl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...qr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...qr};return{...qr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:xe.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Bo(this.config.logDirectory,Qs.F_OK|Qs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ro(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:qt.from(t);try{if(!Ur(this.currentLogFile))await Se(this.currentLogFile,"",{mode:420});if(n=vs(this.currentLogFile,"a",420),So(n,c,{flag:"a"}),Ps(n),n!==void 0)ge(n),n=void 0;if((await Ri(this.currentLogFile)).size===0){if(await Se(this.currentLogFile,c,{flag:"w",mode:420}),(await Ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let o=s*2**e;await new Promise((y)=>setTimeout(y,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{ge(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}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 Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,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 t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ce(16).toString("hex")}generateKey(){return Ce(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ce(16),n=To("aes-256-gcm",i,r),e=qt.isBuffer(t)?t:qt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=qt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=tl(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(qt.from(qt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await Ri(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Fr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ri(r).catch(()=>null))try{if(await Zs(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Nr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Se(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ri(r).catch(()=>null))await Zs(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Fr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Nr(Yi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Vs(t),n=go(i),e=tl();await Fo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!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(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ur(this.currentLogFile))try{let t=vs(this.currentLogFile,"r+");Ps(t),ge(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Fr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Nr(Yi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?U.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=_.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${U.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=U.underline(U.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>U.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>U.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>U.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>U.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>U.strikethrough(n)),i}supportsHyperlinks(){if(p())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=_.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Yo(i)||i.startsWith("./")||i.startsWith("../"))i=Uo(i);else return null;return Ur(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":ec[t],y=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:U.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:U.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
14
+ `);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:U.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
15
+ `;if(c)a+=`${c}
16
+ `;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!p()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!p()&&_.stdout.isTTY)_.stdout.write(`
17
+ `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":U.blue("◐"),tag:r,message:`${U.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
18
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":U.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new rn(i,{...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(!Ur(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Vs(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.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=qt.isBuffer(t)?t:qt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Co("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,o=qt.allocUnsafe(a);return l.copy(o,0),h.copy(o,l.length),o.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(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
19
+ `),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,o=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:U.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(h),showTimestamp:!1})),o.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(a),showTimestamp:!1}))}else if(!p())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${U.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let a=i[c++];switch(h){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 l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${U.blue("◐")} `;console.error(`${c}${s} ${U.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
21
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=U.green("━".repeat(n)),s=U.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?U.green("✓"):U.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${U.gray(this.formatTag(this.name))}`:"",y=`\r${a}${o} ${c} ${l}${h}`,u=_.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
22
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Fr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Yi(this.config.logDirectory,n);if(t.before)try{if((await Ri(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}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 Nr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Vl(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Pl(t){return t instanceof dt}function hu(t){return t instanceof nn}function au(t){if(Pl(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class un{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return lr.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=jr.env[l]||(h?jr.env[h]:void 0);if(a!==void 0){if(n.verbose){let o=jr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof en)throw o;throw ci.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ci.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(jr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
23
+
24
+ `;for(let n of t)r+=`${n.key}
25
+ `,r+=` Type: ${n.type}
26
+ `,r+=` Description: ${n.description}
27
+ `,r+=` Example: ${n.example}
28
+
29
+ `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
30
+
31
+ `;r+=`| Variable | Type | Description | Example |
32
+ `,r+=`|----------|------|-------------|----------|
33
+ `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
34
+ `;return r}}function ou(t,i){let r=ic("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function vl(t,i,r={}){return Ql(t,i,r,new WeakMap)}function Ql(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Zl(t,i,e,n);if(!St(i)||!St(t))return i;return $u(t,i,r,n)}function Zl(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return uu(t,i);case"smart":return yu(t,i,n);default:return i}return i}function uu(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Le(e,n)))r.push(n);return r}function yu(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(St(i[0])&&St(t[0]))return wu(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function wu(t,i,r){let n=[...i];for(let e of t){if(!St(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>St(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function $u(t,i,r,n){let e=i;if(St(e)&&n.has(e))return n.get(e);let f={...t};if(St(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(St(c)&&St(l))f[s]=Ql(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Zl(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function lf(t,i,r="replace"){return vl(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Le(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Le(t[r],i[r]))return!1;return!0}if(St(t)&&St(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Le(t[e],i[e]))return!1}return!0}return!1}function St(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class yn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Xi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Wr(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new er(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new er(t,Error("Configuration must export a valid object"),"unknown");let m={config:lf(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Xi.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ci.configLoad(t,h):ci.configLoad(t,Error(String(h)))}};if(s)return lr.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Be(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Vl(async()=>{return Wr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Wr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Be(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Be(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Wr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class cf{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await lr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!No(i))throw new fr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new fr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:sc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class hf{fileLoader=new yn;envProcessor=new un;validator=new cf;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw _t.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||di.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(at(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw ci.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?tr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)_t.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)_t.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?tr(t,r,e):r,c=[at(Ci(),".config",t),at(Ci(),".config"),Ci()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)_t.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?tr(t,n,f):n;try{let l=at(r,"package.json");if(!Me(l))return null;let h=await import(l),a=h[t],o=t;if(!a&&i)a=h[i],o=i;if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)_t.success(`Configuration loaded from package.json: ${o}`);return{config:lf(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:tr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ci.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Xi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Xi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(Ci(),".config",t),at(Ci(),".config"),Ci()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function hl(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function mu(t){return vt.loadConfig({...t,__strictErrorHandling:!0})}async function tc(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await vt.loadConfig(t);else n=await vt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)_t.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await vt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function du(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await vt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&hl(r)))return(await vt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await vt.loadConfig({...t,cwd:t.cwd||di.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&hl(i)))return(await vt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Au(t,i,r="replace"){let n=new yn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function tr(t,i,r=!1){let n=new un,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=di.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}function Eu(t){let i=at(di.cwd(),t.configDir),r=at(di.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!Me(zs(n)))fo(zs(n),{recursive:!0,mode:511});let e=Me(i)?so(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${pu}
35
+ export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
36
+ `;lo(n,f,{mode:438})}function Tu(t){let i=null,r=null,n=()=>{if(!r)r=tc(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)_t.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function Cu(t){let i=il(Xo.cwd(),t?.configDir||"./config");function r(){if(!jo(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Wo(i).filter((l)=>e.has(Re(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let a=Re(h).toLowerCase(),o=c.get(l);if(!o){c.set(l,h);continue}let y=Re(o).toLowerCase();if(f.indexOf(a)<f.indexOf(y))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((l)=>l.base),s=f.length?f.map((l)=>`'${l}'`).join(" | "):"string",c=e.length?`{
37
+ ${e.map((l)=>{let h=il(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${h}').default`}).join(`,
38
+ `)}
39
+ }`:"Record<string, any>";return`export type ConfigNames = ${s}
40
+ export type ConfigByName = ${c}
41
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
42
+ export type ConfigOf = Config
43
+ `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var ic,Xi,lr,rc,gu,Su,al,Lr,Ge,et,M,Bu,ol,Ru,ul,Yu,Uu,je,Fu,yl,wl,We,Nu,ju,Wu,Xu,Gr,nc,_u,ft,Iu,Ju,$l,xr,xe,V,U,Ou,ml,Hu,dl,Ku,Mu,Xe,zu,Al,El,Lu,_e,Gu,xu,qu,ku,bu,qr,ec,Du,pu="0.15.6",dt,nn,er,qe,ke,en,be,De,fr,pe,Ve,ci,fc,sc,_t,vt,lc,cc,Vu=Vo(async()=>{ic=import.meta.require,Xi=new nf,lr=new ef,rc={createKey:Po,isEquivalent:vo,estimateMemoryUsage:Qo},gu=Vr(ze.cwd(),"config"),Su=Vr(ze.cwd(),"src/generated"),al=pr.env.CLARITY_LOG_DIR||ao(iu(),"logs"),Lr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:al,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ge=await ru(),et={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},M=et,Bu=et.red,ol=et.green,Ru=et.yellow,ul=et.blue,Yu=et.magenta,Uu=et.cyan,je=et.white,Fu=et.gray,yl=et.bgRed,wl=et.bgYellow,We=et.bold,Nu=et.dim,ju=et.italic,Wu=et.underline,Xu=et.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nc={debug:"\uD83D\uDD0D",info:ul("ℹ"),success:ol("✓"),warning:wl(je(We(" WARN "))),error:yl(je(We(" ERROR ")))},_u=new Zr("stacks"),ft=new Zr("bunfig",{showTags:!0}),Iu=ht(nr.cwd(),"config"),Ju=ht(nr.cwd(),"src/generated"),$l=Dr.env.CLARITY_LOG_DIR||co(su(),"logs"),xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$l,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xe=await lu(),V={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},U=V,Ou=V.red,ml=V.green,Hu=V.yellow,dl=V.blue,Ku=V.magenta,Mu=V.cyan,Xe=V.white,zu=V.gray,Al=V.bgRed,El=V.bgYellow,Lu=V.bgGray,_e=V.bold,Gu=V.dim,xu=V.italic,qu=V.underline,ku=V.strikethrough,bu=V.reset,qr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ec={debug:"\uD83D\uDD0D",info:dl("ℹ"),success:ml("✓"),warning:El(Xe(_e(" WARN "))),error:Al(Xe(_e(" ERROR ")))},Du=new rn("stacks"),dt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,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(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},nn=class extends dt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},er=class extends dt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},qe=class extends dt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},ke=class extends dt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},en=class extends dt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},be=class extends dt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},De=class extends dt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},fr=class extends dt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},pe=class extends dt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},Ve=class extends dt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ci={configNotFound(t,i,r){return new nn(t,i,r)},configLoad(t,i,r){return new er(t,i,r)},configValidation(t,i,r){return new qe(t,i,r)},configMerge(t,i,r,n){return new ke(t,i,r,n)},envVar(t,i,r,n){return new en(t,i,r,n)},fileSystem(t,i,r){return new be(t,i,r)},typeGeneration(t,i,r){return new De(t,i,r)},schemaValidation(t,i,r){return new fr(t,i,r)},browserConfig(t,i,r,n){return new pe(t,i,r,n)},plugin(t,i,r){return new Ve(t,i,r)}},fc={replace:"replace",concat:"concat",smart:"smart"},sc=/^https?:\/\//,_t=new rn("bunfig",{showTags:!0}),vt=new hf,lc=at(di.cwd(),"config"),cc=at(di.cwd(),"src/generated")});function Pu(t,i={}){let r=Pr.cwd();while(r.includes("storage"))r=rl(r,"..");let n=rl(r,t||"");if(i?.relative)return Io(Pr.cwd(),n);return n}var vu=Pr.env.CLARITY_LOG_DIR||_o(Pu(),"logs"),hc={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},fn={...hc},Yd=(async()=>{try{let{loadConfig:t}=await Vu().then(()=>bl),i=await t({name:"clarity",alias:"logging",defaultConfig:hc,cwd:Pr.cwd()});if(i)Object.assign(fn,i)}catch{}return fn})();function P(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Qu(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let t=Vt.type;if(t==="renderer"||t==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class ac{async format(t){let i=await Qu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},j=it,Ud=it.red,Zu=it.green,Fd=it.yellow,ty=it.blue,Nd=it.magenta,jd=it.cyan,Tl=it.white,Wd=it.gray,iy=it.bgRed,ry=it.bgYellow,Xd=it.bgGray,Cl=it.bold,_d=it.dim,Id=it.italic,Jd=it.underline,Od=it.strikethrough,Hd=it.reset,Ie={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ny={debug:"\uD83D\uDD0D",info:ty("ℹ"),success:Zu("✓"),warning:ry(Tl(Cl(" WARN "))),error:iy(Tl(Cl(" ERROR ")))};class wn{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(t,i={}){this.name=t,this.config={...fn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ac,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ie,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ie};return{...Ie,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:fn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Mo(this.config.logDirectory,sl.F_OK|sl.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await zo(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:kt.from(t);try{if(!Xr(this.currentLogFile))await Fe(this.currentLogFile,"",{mode:420});if(n=fl(this.currentLogFile,"a",420),Ko(n,c,{flag:"a"}),el(n),n!==void 0)Ue(n),n=void 0;if((await Fi(this.currentLogFile)).size===0){if(await Fe(this.currentLogFile,c,{flag:"w",mode:420}),(await Fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let o=s*2**e;await new Promise((y)=>setTimeout(y,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Ue(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}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 Ni(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 Ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,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 t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ye(16).toString("hex")}generateKey(){return Ye(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ye(16),n=Jo("aes-256-gcm",i,r),e=kt.isBuffer(t)?t:kt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=kt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=cl(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(kt.from(kt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Fi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await _r(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Fi(r).catch(()=>null))try{if(await ll(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Ir(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Fe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Fi(r).catch(()=>null))await ll(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await _r(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Ir(Ni(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=nl(t),n=Ho(i),e=cl();await xo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!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(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Xr(this.currentLogFile))try{let t=fl(this.currentLogFile,"r+");el(t),Ue(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await _r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Ir(Ni(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?j.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof I.env.NO_COLOR<"u",i=I.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=I.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${j.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=j.underline(j.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>j.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>j.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>j.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>j.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>j.strikethrough(n)),i}supportsHyperlinks(){if(P())return!1;let t=I.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=I.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Lo(i)||i.startsWith("./")||i.startsWith("../"))i=Go(i);else return null;return Xr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":ny[t],y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:j.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:j.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
44
+ `);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:j.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
45
+ `;if(c)a+=`${c}
46
+ `;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!P()&&I.stdout.isTTY)I.stdout.write(`
47
+ `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:r,message:`${j.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
48
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":j.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new wn(i,{...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(!Xr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return nl(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.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=kt.isBuffer(t)?t:kt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Oo("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,o=kt.allocUnsafe(a);return l.copy(o,0),h.copy(o,l.length),o.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(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
49
+ `),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,o=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:j.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:j.cyan(h),showTimestamp:!1})),o.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:j.cyan(a),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${j.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=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(""),i(e==="y"||e==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let a=i[c++];switch(h){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 l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${c}${s} ${j.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
51
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=j.green("━".repeat(n)),s=j.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?j.green("✓"):j.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",y=`\r${a}${o} ${c} ${l}${h}`,u=I.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,I.stdout.write(t.lastRenderedLine),i)I.stdout.write(`
52
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await _r(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Ni(this.config.logDirectory,n);if(t.before)try{if((await Fi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}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 Ir(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Kd=new wn("stacks");class Ot extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,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(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class oc extends Ot{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class sn extends Ot{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class uc extends Ot{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class yc extends Ot{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class af extends Ot{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class wc extends Ot{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class $c extends Ot{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class ln extends Ot{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class mc extends Ot{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class dc extends Ot{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var _i={configNotFound(t,i,r){return new oc(t,i,r)},configLoad(t,i,r){return new sn(t,i,r)},configValidation(t,i,r){return new uc(t,i,r)},configMerge(t,i,r,n){return new yc(t,i,r,n)},envVar(t,i,r,n){return new af(t,i,r,n)},fileSystem(t,i,r){return new wc(t,i,r)},typeGeneration(t,i,r){return new $c(t,i,r)},schemaValidation(t,i,r){return new ln(t,i,r)},browserConfig(t,i,r,n){return new mc(t,i,r,n)},plugin(t,i,r){return new dc(t,i,r)}};async function ey(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class of{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return rf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=Jr.env[l]||(h?Jr.env[h]:void 0);if(a!==void 0){if(n.verbose){let o=Jr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof af)throw o;throw _i.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw _i.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Jr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
53
+
54
+ `;for(let n of t)r+=`${n.key}
55
+ `,r+=` Type: ${n.type}
56
+ `,r+=` Description: ${n.description}
57
+ `,r+=` Example: ${n.example}
58
+
59
+ `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
60
+
61
+ `;r+=`| Variable | Type | Description | Example |
62
+ `,r+=`|----------|------|-------------|----------|
63
+ `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
64
+ `;return r}}function fy(t,i,r={}){return Ac(t,i,r,new WeakMap)}function Ac(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ec(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return hy(t,i,r,n)}function Ec(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return sy(t,i);case"smart":return ly(t,i,n);default:return i}return i}function sy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Pe(e,n)))r.push(n);return r}function ly(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return cy(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function cy(t,i,r){let n=[...i];for(let e of t){if(!Bt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>Bt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function hy(t,i,r,n){let e=i;if(Bt(e)&&n.has(e))return n.get(e);let f={...t};if(Bt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=Ac(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Ec(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Tc(t,i,r="replace"){return fy(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Pe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Pe(t[r],i[r]))return!1;return!0}if(Bt(t)&&Bt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Pe(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Cc{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=vr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Or(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new sn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new sn(t,Error("Configuration must export a valid object"),"unknown");let m={config:Tc(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)vr.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?_i.configLoad(t,h):_i.configLoad(t,Error(String(h)))}};if(s)return rf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Ne(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return ey(async()=>{return Or(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Or(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Ne(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Ne(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Or(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var ay=/^https?:\/\//;class gc{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await rf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!qo(i))throw new ln(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new ln(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:ay},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var bt=new wn("bunfig",{showTags:!0});function oy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class Sc{fileLoader=new Cc;envProcessor=new of;validator=new gc;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)bt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw bt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||on.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(gt(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw _i.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${oy(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Kr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)bt.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)bt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Kr(t,r,e):r,c=[gt(Ti(),".config",t),gt(Ti(),".config"),Ti()];for(let l of c){if(e)bt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)bt.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Kr(t,n,f):n;try{let l=gt(r,"package.json");if(!no(l))return null;let h={};try{h=JSON.parse(eo(l,"utf8"))}catch(y){if(f)bt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let a=h[t],o=t;if(!a&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if(h[u]){a=h[u],o=u;break}}}if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)bt.success(`Configuration loaded from package.json: ${o}`);return{config:Tc(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)bt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Kr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw _i.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return vr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);vr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,gt(t,"config"),gt(t,".config"),i?gt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(gt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[gt(Ti(),".config",t),gt(Ti(),".config"),Ti()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var Md=new Sc;function Kr(t,i,r=!1){let n=new of,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=on.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}var zd=gt(on.cwd(),"config"),Ld=gt(on.cwd(),"src/generated"),Bc={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:$e.join(we.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:$e.join(we.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:$e.join(we.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},b=Bc,It={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 C={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Wi={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function ve(t,i){let r=[];function n(e){let f;try{f=gl.readdirSync(e)}catch{return}for(let s of f){let c=Xt.join(e,s);try{if(gl.statSync(c).isDirectory())n(c);else if(s===i)r.push(e)}catch{continue}}}return n(t),r}function E(t,i,r){if(r||b.verbose)console.debug(`[tlsx:${t}] ${i}`)}var $y=wy(uy);function Yc(){return Rc.env.SUDO_PASSWORD}var Sl="[redacted]",my=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),dy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Ay(t){let i=t.toLowerCase();return my.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function cn(t){if(Array.isArray(t))return t.map((r)=>cn(r));if(typeof t==="string")return dy.test(t)?Sl:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(Ay(r)){i[r]=Sl;continue}i[r]=cn(n)}return i}function $n(t){return JSON.stringify(cn(t))}function Ey(t){let i=Yc();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function li(t,i={}){let r=Ey(t);try{let{stdout:n,stderr:e}=await $y(r,{cwd:i.cwd||Rc.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
65
+ Error: ${n.message}`);throw e.stack=n.stack,e}}function Uc(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function uf(t){let i=Xt.join(yy.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:b.basePath&&b.basePath.trim()!==""?b.basePath:i,n=t.certPath?Xt.isAbsolute(t.certPath)?t.certPath:Xt.join(r,t.certPath):Xt.join(r,b.certPath),e=t.keyPath?Xt.isAbsolute(t.keyPath)?t.keyPath:Xt.join(r,t.keyPath):Xt.join(r,b.keyPath),f=t.caCertPath?Xt.isAbsolute(t.caCertPath)?t.caCertPath:Xt.join(r,t.caCertPath):Xt.join(r,b.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function Fc(t){let i=[],r=new Set;if(t.domain)r.add(t.domain);if(t.domains?.length)t.domains.forEach((n)=>r.add(n));for(let n of r)i.push({type:2,value:n});if(t.altNameIPs?.length)for(let n of t.altNameIPs)i.push({type:7,ip:n});if(t.altNameURIs?.length)for(let n of t.altNameURIs)i.push({type:6,value:n});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return E(C.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function yf(t){let i=t.notBeforeDays??It.DEFAULT_NOT_BEFORE_DAYS,r=t.validityDays??(t.validityYears?t.validityYears*365:It.DEFAULT_VALIDITY_DAYS);E(C.CERT,"Calculating certificate validity dates",t.verbose);let n=new Date(Date.now()-86400*i*1000),e=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),E(C.CERT,`Validity period: ${n.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:n,notAfter:e}}var Jt={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},ot={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 ir(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function Et(t,i){let r=ir(i.length);return Buffer.concat([Buffer.from([t]),r,i])}function sr(t){let i=t.split(".").map(Number),r=[];r.push(40*i[0]+i[1]);for(let n=2;n<i.length;n++){let e=i[n],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;r.push(...f)}return Et(Jt.OID,Buffer.from(r))}function Qe(t){let i;if(typeof t==="bigint"){let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return Et(Jt.INTEGER,i)}function Nc(t,i=0){return Et(Jt.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function jc(t){return Et(Jt.OCTET_STRING,t)}function At(...t){return Et(Jt.SEQUENCE,Buffer.concat(t))}function Ty(...t){return Et(Jt.SET,Buffer.concat(t))}function Cy(t){return Et(Jt.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function gy(t){return Et(Jt.UTF8_STRING,Buffer.from(t,"utf8"))}function Sy(){return Buffer.from([Jt.NULL,0])}function Bl(t,i,r=!0){let n=160|t|(r?0:0),e=ir(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function Rl(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Et(Jt.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(i%100).toString().padStart(2,"0"),n=(t.getUTCMonth()+1).toString().padStart(2,"0"),e=t.getUTCDate().toString().padStart(2,"0"),f=t.getUTCHours().toString().padStart(2,"0"),s=t.getUTCMinutes().toString().padStart(2,"0"),c=t.getUTCSeconds().toString().padStart(2,"0"),l=`${r}${n}${e}${f}${s}${c}Z`;return Et(Jt.UTC_TIME,Buffer.from(l,"ascii"))}}function By(t,i){return At(Rl(t),Rl(i))}function Yl(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=ot.COMMON_NAME;break;case"C":n=ot.COUNTRY;break;case"L":n=ot.LOCALITY;break;case"ST":n=ot.STATE;break;case"O":n=ot.ORGANIZATION;break;case"OU":n=ot.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?Cy(r.value):gy(r.value),f=At(sr(n),e);i.push(Ty(f))}return At(...i)}function Wc(t){return At(sr(t),Sy())}function Ry(t){return t.export({type:"spki",format:"der"})}function Yy(t){if(t.includes(":")){let i=t;if(t.includes("::")){let e=t.split("::"),f=e[0]?e[0].split(":"):[],s=e[1]?e[1].split(":"):[],c=8-f.length-s.length,l=Array.from({length:c},()=>"0");i=[...f,...l,...s].join(":")}let r=i.split(":"),n=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(r[e]||"0",16);n.writeUInt16BE(f,e*2)}return n}else{let i=t.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(i)}}function Uy(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=ir(r.value.length);i.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=Yy(r.ip),e=ir(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=ir(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return At(...i)}function Fy(t,i){if(t){if(i!==void 0)return At(Et(1,Buffer.from([255])),Qe(i));return At(Et(1,Buffer.from([255])))}return At()}function Ny(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let r=0,n=i;while(n>0&&(n&1)===0)r++,n>>=1;if(i===0)r=7;return Nc(Buffer.from([i]),r)}function jy(t){let i=[];if(t.serverAuth)i.push(sr(ot.SERVER_AUTH));if(t.clientAuth)i.push(sr(ot.CLIENT_AUTH));return At(...i)}function Zi(t,i,r){let n=[sr(t)];if(i)n.push(Et(1,Buffer.from([255])));return n.push(jc(r)),At(...n)}function Wy(t){let i=[];if(i.push(Bl(0,Qe(2))),i.push(Qe(t.serialNumber)),i.push(Wc(ot.SHA256_WITH_RSA)),i.push(Yl(t.issuer)),i.push(By(t.notBefore,t.notAfter)),i.push(Yl(t.subject)),i.push(Ry(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(Zi(ot.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,Fy(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(Zi(ot.KEY_USAGE,t.extensions.keyUsage.critical??!0,Ny(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(Zi(ot.EXTENDED_KEY_USAGE,!1,jy(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(Zi(ot.SUBJECT_ALT_NAME,!1,Uy(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(Zi(ot.SUBJECT_KEY_IDENTIFIER,!1,jc(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(Bl(3,At(...r)))}return At(...i)}function Xy(t,i){let r=Ii.createSign("SHA256");r.update(t);let n=r.sign(i);return At(t,Wc(ot.SHA256_WITH_RSA),Nc(n))}function _y(t,i){let r=t.toString("base64"),n=[];for(let e=0;e<r.length;e+=64)n.push(r.slice(e,e+64));return`-----BEGIN ${i}-----
66
+ ${n.join(`
67
+ `)}
68
+ -----END ${i}-----
69
+ `}function wf(){return Ii.randomBytes(20)}function Xc(t=2048){let{privateKey:i,publicKey:r}=Ii.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function Iy(t){let i=t.export({type:"spki",format:"der"});return Ii.createHash("sha1").update(i).digest()}function _c(t){let i={serialNumber:t.serialNumber||wf(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:Iy(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let r=Wy(i),n=Xy(r,t.signingKey);return{certificate:_y(n,"CERTIFICATE"),certificateDer:n}}function Ic(t){return t.export({type:"pkcs8",format:"pem"})}function Jy(t){return Ii.createPrivateKey(t)}function Oy(t){let i=new Ii.X509Certificate(t),r=i.publicKey,n=[],e=i.subject.split(`
70
+ `);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)n.push({shortName:s.trim(),value:l.trim()})}return{publicKey:r,subject:n}}async function $f(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||It.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=Xc(i),e=[{shortName:"C",value:t.countryName||b.countryName},{shortName:"ST",value:t.stateName||b.stateName},{shortName:"L",value:t.localityName||b.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:s}=yf({validityYears:t.validityYears||It.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=_c({serialNumber:wf(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:Ic(r),notBefore:f,notAfter:s}}async function mf(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${$n(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Oy(t.rootCA.certificate),r=Jy(t.rootCA.privateKey);E("ca",`Generating ${It.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=It.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=Xc(n),s=t.commonName||Uc(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||b.countryName},{shortName:"ST",value:t.stateName||b.stateName},{shortName:"L",value:t.localityName||b.localityName},{shortName:"O",value:t.organizationName||b.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=yf({validityDays:t.validityDays||It.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),a=Fc(t),o=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:u}=_c({serialNumber:wf(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:o,extendedKeyUsage:y,subjectAltName:a});return{certificate:u,privateKey:Ic(e),notBefore:l,notAfter:h}}function Jc(t,i){E(C.STORAGE,`Storing certificate and private key with options: ${$n(i)}`,i?.verbose);let{certPath:r,keyPath:n}=uf({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(C.STORAGE,`Certificate path: ${r}`,i?.verbose),E(C.STORAGE,`Private key path: ${n}`,i?.verbose);let e=Ze.dirname(r);if(!Pt.existsSync(e))E(C.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),Pt.mkdirSync(e,{recursive:!0});E(C.STORAGE,"Writing certificate file",i?.verbose),Pt.writeFileSync(r,t.certificate);let f=Ze.dirname(n);if(!Pt.existsSync(f))E(C.STORAGE,`Creating private key directory: ${f}`,i?.verbose),Pt.mkdirSync(f,{recursive:!0});return E(C.STORAGE,"Writing private key file",i?.verbose),Pt.writeFileSync(n,t.privateKey),E(C.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function Oc(t,i){E(C.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=uf({basePath:i?.basePath,caCertPath:i?.caCertPath});E(C.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=Ze.dirname(r);if(!Pt.existsSync(n))E(C.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),Pt.mkdirSync(n,{recursive:!0});return E(C.STORAGE,"Writing CA certificate file",i?.verbose),Pt.writeFileSync(r,t),E(C.STORAGE,"CA certificate stored successfully",i?.verbose),r}async function Hy(t,i){if(hn.platform()!=="darwin")return!1;try{let r=Ul(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return E(C.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Ul("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(r))return E(C.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(C.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return E(C.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Ky={platform:"darwin",async addCertificate(t,i){if(await Hy(t,i?.verbose)){E(C.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Wi.success("Certificate is already trusted in system keychain");return}E(C.TRUST,"Adding certificate to macOS keychain",i?.verbose),await li(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||b.commonName;E(C.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await li(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),E(C.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw E(C.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},My={platform:"win32",async addCertificate(t,i){E(C.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await li(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||b.commonName;E(C.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await li(`certutil -delstore -enterprise Root "${n}"`),E(C.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw E(C.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},zy={platform:"linux",async addCertificate(t,i){E(C.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=hn.homedir(),n=It.LINUX_CERT_DB_FILENAME,e=It.LINUX_TRUST_ARGS;E(C.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=ve(r,n);if(f.length===0){Wi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(C.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(C.TRUST,`Attempting to delete existing cert for ${b.commonName}`,i?.verbose),await li(`certutil -d sql:${s} -D -n ${b.commonName}`)}catch(c){E(C.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(C.TRUST,`Adding new certificate to ${s}`,i?.verbose),await li(`certutil -d sql:${s} -A -t ${e} -n ${b.commonName} -i ${t}`),Wi.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||b.commonName;E(C.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=hn.homedir(),f=It.LINUX_CERT_DB_FILENAME;E(C.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=ve(e,f);if(s.length===0){Wi.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(C.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await li(`certutil -d sql:${c} -D -n "${n}"`),Wi.info(`Cert removed from ${c}`)}catch(l){E(C.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},Ly={darwin:Ky,win32:My,linux:zy};async function df(t,i,r){E(C.TRUST,`Adding certificate to system trust store with options: ${$n(r)}`,r?.verbose),E(C.TRUST,"Storing certificate and private key",r?.verbose);let n=Jc(t,r);E(C.TRUST,"Storing CA certificate",r?.verbose);let e=Oc(i,r),f=hn.platform();E(C.TRUST,`Detected platform: ${f}`,r?.verbose);let s=Ly[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(C.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await s.addCertificate(e,r),E(C.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as fs}from"node:os";import{join as ss,resolve as SE}from"node:path";import{existsSync as Hc,statSync as Kc}from"fs";import{existsSync as Gy,mkdirSync as HA,readdirSync as KA,readFileSync as xy,writeFileSync as MA}from"fs";import{homedir as Ji}from"os";import{dirname as GA,resolve as Rt}from"path";import Vn from"process";import{existsSync as Mc,statSync as zc}from"fs";import{existsSync as Hf,mkdirSync as qy,readdirSync as ky,writeFileSync as by}from"fs";import{homedir as Oi}from"os";import{dirname as Lc,resolve as yt}from"path";import Ai from"process";import{join as Dy,relative as py,resolve as Gc}from"path";import On from"process";import{existsSync as Rh,mkdirSync as QA,readdirSync as ZA,writeFileSync as t1}from"fs";import{homedir as Af}from"os";import{dirname as n1,resolve as ut}from"path";import hr from"process";import{join as Vy,relative as Py,resolve as xc}from"path";import Hn from"process";import{existsSync as Yh,mkdirSync as c1,readdirSync as h1,writeFileSync as a1}from"fs";import{dirname as u1,resolve as Kn}from"path";import Kf from"process";import{Buffer as ai}from"buffer";import{createCipheriv as vy,createDecipheriv as Qy,randomBytes as Ef}from"crypto";import{closeSync as Tf,createReadStream as qc,createWriteStream as Zy,existsSync as Cf,fsyncSync as kc,openSync as bc,writeFileSync as tw}from"fs";import{access as iw,constants as Dc,mkdir as rw,readdir as mn,rename as pc,stat as Hi,unlink as dn,writeFile as gf}from"fs/promises";import{join as Ki}from"path";import st from"process";import{pipeline as nw}from"stream/promises";import{createGzip as Vc}from"zlib";import Mi from"process";import ii from"process";import{Buffer as Qt}from"buffer";import{createCipheriv as ew,createDecipheriv as fw,randomBytes as Sf}from"crypto";import{closeSync as Bf,createReadStream as Pc,createWriteStream as sw,existsSync as An,fsyncSync as vc,openSync as Qc,writeFileSync as lw}from"fs";import{access as cw,constants as Zc,mkdir as hw,readdir as En,rename as th,stat as zi,unlink as Tn,writeFile as Rf}from"fs/promises";import{isAbsolute as aw,join as Li,resolve as ow}from"path";import B from"process";import{pipeline as uw}from"stream/promises";import{createGzip as ih}from"zlib";import Gi from"process";import ri from"process";import Cn from"process";import{existsSync as gn}from"fs";import{resolve as Yf}from"path";import{existsSync as yw}from"fs";import{existsSync as ww,readdirSync as $w}from"fs";import{extname as Uf,resolve as rh}from"path";import mw from"process";import{join as dw,relative as Aw,resolve as nh}from"path";import Mn from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as Ew,createDecipheriv as Tw,randomBytes as Ff}from"crypto";import{closeSync as Nf,createReadStream as eh,createWriteStream as Cw,existsSync as Sn,fsyncSync as fh,openSync as sh,writeFileSync as gw}from"fs";import{access as Sw,constants as lh,mkdir as Bw,readdir as Bn,rename as ch,stat as xi,unlink as Rn,writeFile as jf}from"fs/promises";import{isAbsolute as Rw,join as qi,resolve as Yw}from"path";import R from"process";import{pipeline as Uw}from"stream/promises";import{createGzip as hh}from"zlib";import ki from"process";import ni from"process";import Un from"process";import{existsSync as Fn}from"fs";import{resolve as Of}from"path";import{existsSync as D$}from"fs";class Sh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),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(t,i){try{if(!Hc(t))return!0;return Kc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Hc(r)?Kc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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 t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Bh{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Jn=new Sh,Vf=new Bh;var Fw=Object.defineProperty,Nw=(t)=>t;function jw(t,i){this[t]=Nw.bind(null,i)}var Ww=(t,i)=>{for(var r in i)Fw(t,r,{get:i[r],enumerable:!0,configurable:!0,set:jw.bind(i,r)})},Xw=(t,i)=>()=>(t&&(i=t(t=0)),i),Uh={};Ww(Uh,{withErrorRecovery:()=>jh,tryLoadConfig:()=>i$,loadConfigWithResult:()=>Zw,loadConfig:()=>Jh,isRetryableError:()=>Dw,isConfigNotFoundError:()=>bw,isBunfigError:()=>Wh,globalPerformanceMonitor:()=>ur,globalCache:()=>bi,getEnvOrDefault:()=>pw,generateConfigTypes:()=>r$,defaultGeneratedDir:()=>xh,defaultConfigDir:()=>Gh,deepMergeWithArrayStrategy:()=>ts,deepMerge:()=>Xh,createLibraryConfig:()=>n$,config:()=>t$,bunfigPlugin:()=>e$,applyEnvVarsToConfig:()=>cr,TypeGenerationError:()=>kf,SchemaValidationError:()=>or,PluginError:()=>Df,PerformanceMonitor:()=>vf,FileSystemError:()=>qf,ErrorFactory:()=>oi,EnvVarError:()=>kn,EnvProcessor:()=>Pn,ConfigValidator:()=>is,ConfigValidationError:()=>Gf,ConfigNotFoundError:()=>qn,ConfigMergeError:()=>xf,ConfigLoader:()=>rs,ConfigLoadError:()=>ar,ConfigFileLoader:()=>vn,ConfigCache:()=>Pf,CacheUtils:()=>Hh,BunfigError:()=>Tt,BrowserConfigError:()=>bf,ArrayMergeStrategies:()=>zh});class Pf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),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(t,i){try{if(!Mc(t))return!0;return zc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Mc(r)?zc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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 t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class vf{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function _w(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function Iw(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Jw(t){return t.getStats().size*2}function Qf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let n=[...i];for(let e of t)if(x(e)&&"name"in e){if(!n.find((s)=>x(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(x(e)&&"path"in e){if(!n.find((s)=>x(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>zn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!x(i)||!x(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(x(e)&&x(r[n]))r[n]=Qf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&x(e[0])&&x(r[n][0])){let f=[...e];for(let s of r[n])if(x(s)&&"name"in s){if(!f.find((l)=>x(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(x(s)&&"path"in s){if(!f.find((l)=>x(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>zn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function zn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!zn(t[r],i[r]))return!1;return!0}if(x(t)&&x(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!zn(t[e],i[e]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ow(t,i){if(!Yh(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Qf(i,n)}catch{return null}}catch{return null}}async function Hw({name:t="",cwd:i,defaultConfig:r}){let n=i||Kf.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Kn(n,`${s}${c}`),h=await Ow(l,r);if(h!==null)return h}try{let s=Kn(n,"package.json");if(Yh(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Qf(r,l)}catch{}}}catch{}return r}function Kw(t,i={}){let r=Hn.cwd();while(r.includes("storage"))r=xc(r,"..");let n=xc(r,t||"");if(i?.relative)return Py(Hn.cwd(),n);return n}async function Mw(){try{let t=await Hw({name:"clarity",defaultConfig:Wn,cwd:Hn.cwd(),endpoint:"",headers:{}});return{...Wn,...t}}catch{return Wn}}function k(){if(ii.env.NODE_ENV==="test"||ii.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zw(){if(ii.env.NODE_ENV==="test"||ii.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ii<"u"){let t=ii.type;if(t==="renderer"||t==="worker")return!1;return!!(ii.versions&&(ii.versions.node||ii.versions.bun))}return!1}class Fh{async format(t){let i=await zw(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Mi.pid,hostname:i(),environment:Mi.env.NODE_ENV||"development",platform:Mi.platform,version:Mi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mi.env.NODE_ENV||Mi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ln{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(t,i={}){this.name=t,this.config={...zf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Fh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??st.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Xn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Xn};return{...Xn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:zf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await iw(this.config.logDirectory,Dc.F_OK|Dc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await rw(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ai.from(t);try{if(!Cf(this.currentLogFile))await gf(this.currentLogFile,"",{mode:420});if(e=bc(this.currentLogFile,"a",420),tw(e,l,{flag:"a"}),kc(e),e!==void 0)Tf(e),e=void 0;if((await Hi(this.currentLogFile)).size===0){if(await gf(this.currentLogFile,l,{flag:"w",mode:420}),(await Hi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let o=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let y=c*2**f;await new Promise((u)=>setTimeout(u,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Tf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,o=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Ki(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 Ki(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ki(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=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 e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ef(16).toString("hex")}generateKey(){return Ef(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ef(16),n=vy("aes-256-gcm",i,r),e=ai.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ai.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Vc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ai.from(ai.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Hi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await mn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Hi(r).catch(()=>null))try{if(await pc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await dn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await gf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Hi(r).catch(()=>null))await pc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await mn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await dn(Ki(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=qc(t),n=Zy(i),e=Vc();await nw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!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(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Cf(this.currentLogFile))try{let t=bc(this.currentLogFile,"r+");kc(t),Tf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await mn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await dn(Ki(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=st.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${z.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!k()){let h=Kh[t],a=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:z.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:z.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o),c){let y=c.split(`
71
+ `);for(let u of y)if(u.trim()&&!u.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:z.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
72
+ `;if(c)l+=`${c}
73
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!k()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:z.blue("◐"),tag:r,message:`${z.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
74
+ `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let a=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:z.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Ln(i,{...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(k())throw Error("createReadStream is not supported in browser environments");if(!Cf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return qc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.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=ai.isBuffer(t)?t:ai.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=Qy("aes-256-gcm",r,e);return c.setAuthTag(f),ai.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!k()){let f=t.split(`
75
+ `),s=Math.max(...f.map((a)=>a.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((a)=>{let o=" ".repeat(s-a.length-2);return`│ ${a}${o} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(c)})),h.forEach((a)=>console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(a),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(l),showTimestamp:!1}))}else if(!k())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
76
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${z.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();st.stdin.removeListener("data",r);try{if(typeof st.stdin.setRawMode==="function")st.stdin.setRawMode(!1)}catch{}st.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof st.stdin.setRawMode==="function")st.stdin.setRawMode(!0)}catch{}st.stdin.resume(),st.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let a=i[c++];switch(h){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 l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!k()){let s=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=z.blue("◐");console.error(`${c} ${s} ${z.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
77
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=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:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;st.stdout.write(`${"\r".padEnd(st.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!st.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=z.green("━".repeat(n)),s=z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=i||r===100?z.green("✓"):z.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",y=`\r${a}${o} ${c} ${l}${h}`,u=st.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,st.stdout.write(t.lastRenderedLine),i)st.stdout.write(`
78
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!st.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await mn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Ki(this.config.logDirectory,n);if(t.before)try{if((await Hi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);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 dn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function jn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&H(i[0])&&"id"in i[0]&&i[0].id===3&&H(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(H(i)&&H(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(H(t)&&"arr"in t&&Array.isArray(t.arr)&&H(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&H(i[0])&&H(t[0])){let n=[...i];for(let e of t)if(H(e)&&"name"in e){if(!n.find((s)=>H(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(H(e)&&"path"in e){if(!n.find((s)=>H(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Gn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!H(i)||!H(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(H(e)&&H(r[n]))r[n]=jn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&H(e[0])&&H(r[n][0])){let f=[...e];for(let s of r[n])if(H(s)&&"name"in s){if(!f.find((l)=>H(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(H(s)&&"path"in s){if(!f.find((l)=>H(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Gn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Zf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:jn(t,i);if(Array.isArray(t))return r==="replace"?i:jn(t,i);if(!H(i)||!H(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=jn(s,f);else if(H(f)&&H(s))n[e]=Zf(s,f,r);else n[e]=f}return n}function Gn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Gn(t[r],i[r]))return!1;return!0}if(H(t)&&H(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Gn(t[e],i[e]))return!1}return!0}return!1}function H(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Yn(t,i,r="replace"){if(!Rh(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Zf(i,e,r)}catch{return null}}catch{return null}}function Lw(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${n}_${o.map(y).join("_")}`,m=`${n}_${o.map((w)=>w.toUpperCase()).join("_")}`;if(r)ct.info(`Checking environment variable ${u} for config ${t}.${o.join(".")}`);if(typeof a==="object"&&a!==null&&!Array.isArray(a))l[h]=f(a,o);else{let w=hr.env[u]||hr.env[m];if(w!==void 0){if(r)ct.info(`Using environment variable ${w?u:m} for config ${t}.${o.join(".")}`);if(typeof a==="number")l[h]=Number(w);else if(typeof a==="boolean")l[h]=w.toLowerCase()==="true";else if(Array.isArray(a))try{let d=JSON.parse(w);if(Array.isArray(d))l[h]=d;else l[h]=w.split(",").map((A)=>A.trim())}catch{l[h]=w.split(",").map((d)=>d.trim())}else l[h]=w}}}return l}return f(e)}async function Gw({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?Lw(t,e,f):e,h=r||hr.cwd(),a=[".ts",".js",".mjs",".cjs",".json"];if(f)ct.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],w=Array.from(new Set([h,ut(h,"config"),ut(h,".config"),n?ut(h,n):void 0].filter(Boolean)));for(let d of w){if(f)ct.info(`Searching for configuration in: ${d}`);let T=[ut(h,"config"),ut(h,".config")].concat(n?[ut(h,n)]:[]).includes(d)?[...o,...y,...u,...m]:[...y,...o,...m,...u];for(let Y of T)for(let S of a){let X=ut(d,`${Y}${S}`),xt=await Yn(X,l,c);if(xt!==null){if(f)ct.success(`Configuration loaded from: ${X}`);return xt}}}if(t){let d=ut(Af(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)ct.info(`Checking user config directory: ${d}`);for(let T of A)for(let Y of a){let S=ut(d,`${T}${Y}`),X=await Yn(S,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user config directory: ${S}`);return X}}}if(t){let d=ut(Af(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)ct.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ut(d,`${T}${Y}`),X=await Yn(S,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user config directory dotfile: ${S}`);return X}}}if(t){let d=Af(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)ct.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ut(d,`${T}${Y}`),X=await Yn(S,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user home directory: ${S}`);return X}}}try{let d=ut(h,"package.json");if(Rh(d)){let A=await import(d),T=A[t];if(!T&&i){if(T=A[i],T&&f)ct.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)ct.success(`Configuration loaded from package.json: ${T===A[t]?t:i}`);return Zf(l,T,c)}catch(Y){if(f)ct.warn("Failed to merge package.json config:",Y)}}}catch(d){if(f)ct.warn("Failed to load package.json:",d)}if(f)ct.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function xw(t,i={}){let r=On.cwd();while(r.includes("storage"))r=Gc(r,"..");let n=Gc(r,t||"");if(i?.relative)return py(On.cwd(),n);return n}async function qw(){try{let t=await Gw({name:"clarity",alias:"logging",defaultConfig:_n,cwd:On.cwd()});return{..._n,...t||{}}}catch{return _n}}function v(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kw(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ri<"u"){let t=ri.type;if(t==="renderer"||t==="worker")return!1;return!!(ri.versions&&(ri.versions.node||ri.versions.bun))}return!1}class Nh{async format(t){let i=await kw(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Gi.pid,hostname:i(),environment:Gi.env.NODE_ENV||"development",platform:Gi.platform,version:Gi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gi.env.NODE_ENV||Gi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xn{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(t,i={}){this.name=t,this.config={...Lf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Nh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??B.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...In,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...In};return{...In,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Lf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!v()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await cw(this.config.logDirectory,Zc.F_OK|Zc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await hw(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Qt.from(t);try{if(!An(this.currentLogFile))await Rf(this.currentLogFile,"",{mode:420});if(e=Qc(this.currentLogFile,"a",420),lw(e,l,{flag:"a"}),vc(e),e!==void 0)Bf(e),e=void 0;if((await zi(this.currentLogFile)).size===0){if(await Rf(this.currentLogFile,l,{flag:"w",mode:420}),(await zi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let o=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let y=c*2**f;await new Promise((u)=>setTimeout(u,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Bf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,o=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Li(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 Li(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Li(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(v())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=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 e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Sf(16).toString("hex")}generateKey(){return Sf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Sf(16),n=ew("aes-256-gcm",i,r),e=Qt.isBuffer(t)?t:Qt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Qt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ih(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Qt.from(Qt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(v())return;if(!this.shouldWriteToFile())return;let t=await zi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await En(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await zi(r).catch(()=>null))try{if(await th(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Tn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Rf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await zi(r).catch(()=>null))await th(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await En(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await Tn(Li(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=Pc(t),n=sw(i),e=ih();await uw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!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(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),An(this.currentLogFile))try{let t=Qc(this.currentLogFile,"r+");vc(t),Bf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!v()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await En(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Tn(Li(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v())return!1;let t=typeof B.env.NO_COLOR<"u",i=B.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof B.stderr<"u"&&B.stderr.isTTY||typeof B.stdout<"u"&&B.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=B.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${F.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=F.underline(F.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>F.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>F.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>F.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>F.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>F.strikethrough(n)),i}supportsHyperlinks(){if(v())return!1;let t=B.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=B.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(aw(i)||i.startsWith("./")||i.startsWith("../"))i=ow(i);else return null;return An(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":Mh[t],y=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:F.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:F.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
79
+ `);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:F.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!v()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
80
+ `;if(c)a+=`${c}
81
+ `;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!v()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!v()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!v()&&B.stdout.isTTY)B.stdout.write(`
82
+ `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!v()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":F.blue("◐"),tag:r,message:`${F.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
83
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!v())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new xn(i,{...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(v())throw Error("createReadStream is not supported in browser environments");if(!An(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Pc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.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=Qt.isBuffer(t)?t:Qt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=fw("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,o=Qt.allocUnsafe(a);return l.copy(o,0),h.copy(o,l.length),o.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 v()}isServerMode(){return!v()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
84
+ `),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,o=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:F.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(h),showTimestamp:!1})),o.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(a),showTimestamp:!1}))}else if(!v())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
85
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(v())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();B.stdin.removeListener("data",r);try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!1)}catch{}B.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!0)}catch{}B.stdin.resume(),B.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(a,o)=>{if(o==="%")return"%";if(h>=i.length)return a;let y=i[h++];switch(o){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 a}}),h<i.length)r+=` ${i.slice(h).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${F.blue("◐")} `;console.error(`${h}${l} ${F.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
86
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!B.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=F.green("━".repeat(n)),s=F.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",y=`\r${a}${o} ${c} ${l}${h}`,u=B.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,B.stdout.write(t.lastRenderedLine),i)B.stdout.write(`
87
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||v()||!B.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(v()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await En(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Li(this.config.logDirectory,n);if(t.before)try{if((await zi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);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 Tn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function jh(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Wh(t){return t instanceof Tt}function bw(t){return t instanceof qn}function Dw(t){if(Wh(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>t.message.toLowerCase().includes(r.toLowerCase()))}class Pn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ur.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=Cn.env[l]||(h?Cn.env[h]:void 0);if(a!==void 0){if(n.verbose){let o=Cn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof kn)throw o;throw oi.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw oi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Cn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
88
+
89
+ `;for(let n of t)r+=`${n.key}
90
+ `,r+=` Type: ${n.type}
91
+ `,r+=` Description: ${n.description}
92
+ `,r+=` Example: ${n.example}
93
+
94
+ `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
95
+
96
+ `;r+=`| Variable | Type | Description | Example |
97
+ `,r+=`|----------|------|-------------|----------|
98
+ `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
99
+ `;return r}}function pw(t,i){let r=Oh("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function Xh(t,i,r={}){return _h(t,i,r,new WeakMap)}function _h(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ih(t,i,e,n);if(!Yt(i)||!Yt(t))return i;return Qw(t,i,r,n)}function Ih(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Vw(t,i);case"smart":return Pw(t,i,n);default:return i}return i}function Vw(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Mf(e,n)))r.push(n);return r}function Pw(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Yt(i[0])&&Yt(t[0]))return vw(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function vw(t,i,r){let n=[...i];for(let e of t){if(!Yt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Yt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Qw(t,i,r,n){let e=i;if(Yt(e)&&n.has(e))return n.get(e);let f={...t};if(Yt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Yt(c)&&Yt(l))f[s]=_h(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Ih(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ts(t,i,r="replace"){return Xh(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mf(t[r],i[r]))return!1;return!0}if(Yt(t)&&Yt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Mf(t[e],i[e]))return!1}return!0}return!1}function Yt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class vn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=bi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!gn(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new ar(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new ar(t,Error("Configuration must export a valid object"),"unknown");let d={config:ts(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)bi.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?oi.configLoad(t,h):oi.configLoad(t,Error(String(h)))}};if(s)return ur.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Yf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return jh(async()=>{return gn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!gn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Yf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Yf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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(t))}async validateConfigFile(t){let i=[];try{if(!gn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class is{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await ur.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!yw(i))throw new or(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new or(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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 rs{fileLoader=new vn;envProcessor=new Pn;validator=new is;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Ht.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Ht.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||Ai.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(yt(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw oi.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?cr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)Ht.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)Ht.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?cr(t,r,e):r,c=[yt(Oi(),".config",t),yt(Oi(),".config"),Oi()];for(let l of c){if(e)Ht.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)Ht.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?cr(t,n,f):n;try{let l=yt(r,"package.json");if(!Hf(l))return null;let h=await import(l),a=h[t],o=t;if(!a&&i)a=h[i],o=i;if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)Ht.success(`Configuration loaded from package.json: ${o}`);return{config:ts(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Ht.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:cr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw oi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return bi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);bi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(yt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[yt(Oi(),".config",t),yt(Oi(),".config"),Oi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function ah(t){let r=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return r||n}async function Zw(t){return ei.loadConfig({...t,__strictErrorHandling:!0})}async function Jh(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await ei.loadConfig(t);else n=await ei.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Ht.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ei.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function t$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ei.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ah(r)))return(await ei.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await ei.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&ah(i)))return(await ei.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function i$(t,i,r="replace"){let n=new vn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function cr(t,i,r=!1){let n=new Pn,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=Ai.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}function r$(t){let i=yt(Ai.cwd(),t.configDir),r=yt(Ai.cwd(),t.generatedDir),n=yt(r,"config-types.ts");if(!Hf(Lc(n)))qy(Lc(n),{recursive:!0,mode:511});let e=Hf(i)?ky(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${W$}
100
+ export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
101
+ `;by(n,f,{mode:438})}function n$(t){let i=null,r=null,n=()=>{if(!r)r=Jh(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)Ht.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function e$(t){let i=rh(mw.cwd(),t?.configDir||"./config");function r(){if(!ww(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=$w(i).filter((l)=>e.has(Uf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let a=Uf(h).toLowerCase(),o=c.get(l);if(!o){c.set(l,h);continue}let y=Uf(o).toLowerCase();if(f.indexOf(a)<f.indexOf(y))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((h)=>h.base),s=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
102
+ ${e.map((h)=>{let a=rh(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${a}').default`}).join(`,
103
+ `)}
104
+ }`:"Record<string, any>";return`export type ConfigNames = ${s}
105
+ export type ConfigByName = ${c}
106
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
107
+ export type ConfigOf = Config
108
+ `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var Oh,bi,ur,Hh,f$,s$,oh,Wn,zf,lt,z,l$,uh,c$,yh,h$,a$,Wf,o$,wh,$h,Xf,u$,y$,w$,$$,Xn,Kh,m$,ct,d$,A$,mh,_n,Lf,Q,F,E$,dh,T$,Ah,C$,g$,_f,S$,Eh,Th,B$,If,R$,Y$,U$,F$,N$,In,Mh,j$,W$="0.15.6",Tt,qn,ar,Gf,xf,kn,qf,kf,or,bf,Df,oi,zh,Lh,Ht,ei,Gh,xh,X$=Xw(async()=>{Oh=import.meta.require,bi=new Pf,ur=new vf,Hh={createKey:_w,isEquivalent:Iw,estimateMemoryUsage:Jw},f$=Kn(Kf.cwd(),"config"),s$=Kn(Kf.cwd(),"src/generated"),oh=Hn.env.CLARITY_LOG_DIR||Vy(Kw(),"logs"),Wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},zf=await Mw(),lt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},z=lt,l$=lt.red,uh=lt.green,c$=lt.yellow,yh=lt.blue,h$=lt.magenta,a$=lt.cyan,Wf=lt.white,o$=lt.gray,wh=lt.bgRed,$h=lt.bgYellow,Xf=lt.bold,u$=lt.dim,y$=lt.italic,w$=lt.underline,$$=lt.reset,Xn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Kh={debug:"\uD83D\uDD0D",info:yh("ℹ"),success:uh("✓"),warning:$h(Wf(Xf(" WARN "))),error:wh(Wf(Xf(" ERROR ")))},m$=new Ln("stacks"),ct=new Ln("bunfig",{showTags:!0}),d$=ut(hr.cwd(),"config"),A$=ut(hr.cwd(),"src/generated"),mh=On.env.CLARITY_LOG_DIR||Dy(xw(),"logs"),_n={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lf=await qw(),Q={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},F=Q,E$=Q.red,dh=Q.green,T$=Q.yellow,Ah=Q.blue,C$=Q.magenta,g$=Q.cyan,_f=Q.white,S$=Q.gray,Eh=Q.bgRed,Th=Q.bgYellow,B$=Q.bgGray,If=Q.bold,R$=Q.dim,Y$=Q.italic,U$=Q.underline,F$=Q.strikethrough,N$=Q.reset,In={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Mh={debug:"\uD83D\uDD0D",info:Ah("ℹ"),success:dh("✓"),warning:Th(_f(If(" WARN "))),error:Eh(_f(If(" ERROR ")))},j$=new xn("stacks"),Tt=class extends Error{timestamp;context;constructor(i,r={}){super(i);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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},qn=class extends Tt{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},ar=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Gf=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},xf=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},kn=class extends Tt{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},qf=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},kf=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},or=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},bf=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},Df=class extends Tt{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},oi={configNotFound(t,i,r){return new qn(t,i,r)},configLoad(t,i,r){return new ar(t,i,r)},configValidation(t,i,r){return new Gf(t,i,r)},configMerge(t,i,r,n){return new xf(t,i,r,n)},envVar(t,i,r,n){return new kn(t,i,r,n)},fileSystem(t,i,r){return new qf(t,i,r)},typeGeneration(t,i,r){return new kf(t,i,r)},schemaValidation(t,i,r){return new or(t,i,r)},browserConfig(t,i,r,n){return new bf(t,i,r,n)},plugin(t,i,r){return new Df(t,i,r)}},zh={replace:"replace",concat:"concat",smart:"smart"},Lh=/^https?:\/\//,Ht=new xn("bunfig",{showTags:!0}),ei=new rs,Gh=yt(Ai.cwd(),"config"),xh=yt(Ai.cwd(),"src/generated")});function _$(t,i={}){let r=Mn.cwd();while(r.includes("storage"))r=nh(r,"..");let n=nh(r,t||"");if(i?.relative)return Aw(Mn.cwd(),n);return n}var I$=Mn.env.CLARITY_LOG_DIR||dw(_$(),"logs"),qh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bn={...qh},Z1=(async()=>{try{let{loadConfig:t}=await X$().then(()=>Uh),i=await t({name:"clarity",alias:"logging",defaultConfig:qh,cwd:Mn.cwd()});if(i)Object.assign(bn,i)}catch{}return bn})();function Z(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function J$(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ni<"u"){let t=ni.type;if(t==="renderer"||t==="worker")return!1;return!!(ni.versions&&(ni.versions.node||ni.versions.bun))}return!1}class kh{async format(t){let i=await J$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ki.pid,hostname:i(),environment:ki.env.NODE_ENV||"development",platform:ki.platform,version:ki.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ki.env.NODE_ENV||ki.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var rt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=rt,tE=rt.red,O$=rt.green,iE=rt.yellow,H$=rt.blue,rE=rt.magenta,nE=rt.cyan,Ch=rt.white,eE=rt.gray,K$=rt.bgRed,M$=rt.bgYellow,fE=rt.bgGray,gh=rt.bold,sE=rt.dim,lE=rt.italic,cE=rt.underline,hE=rt.strikethrough,aE=rt.reset,Jf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},z$={debug:"\uD83D\uDD0D",info:H$("ℹ"),success:O$("✓"),warning:M$(Ch(gh(" WARN "))),error:K$(Ch(gh(" ERROR ")))};class Qn{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(t,i={}){this.name=t,this.config={...bn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new kh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Jf,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Jf};return{...Jf,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:bn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!Z()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Sw(this.config.logDirectory,lh.F_OK|lh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Bw(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Zt.from(t);try{if(!Sn(this.currentLogFile))await jf(this.currentLogFile,"",{mode:420});if(e=sh(this.currentLogFile,"a",420),gw(e,l,{flag:"a"}),fh(e),e!==void 0)Nf(e),e=void 0;if((await xi(this.currentLogFile)).size===0){if(await jf(this.currentLogFile,l,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let o=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let y=c*2**f;await new Promise((u)=>setTimeout(u,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Nf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,o=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 qi(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 qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(Z())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=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 e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ff(16).toString("hex")}generateKey(){return Ff(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ff(16),n=Ew("aes-256-gcm",i,r),e=Zt.isBuffer(t)?t:Zt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Zt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=hh(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Zt.from(Zt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(Z())return;if(!this.shouldWriteToFile())return;let t=await xi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Bn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await xi(r).catch(()=>null))try{if(await ch(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Rn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await jf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await xi(r).catch(()=>null))await ch(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await Bn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await Rn(qi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=eh(t),n=Cw(i),e=hh();await Uw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!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(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Sn(this.currentLogFile))try{let t=sh(this.currentLogFile,"r+");fh(t),Nf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!Z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Bn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Rn(qi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z())return!1;let t=typeof R.env.NO_COLOR<"u",i=R.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=R.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${W.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=W.underline(W.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>W.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>W.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>W.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>W.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>W.strikethrough(n)),i}supportsHyperlinks(){if(Z())return!1;let t=R.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=R.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Rw(i)||i.startsWith("./")||i.startsWith("../"))i=Yw(i);else return null;return Sn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":z$[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:W.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:W.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
109
+ `);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:W.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!Z()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
110
+ `;if(c)a+=`${c}
111
+ `;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Z()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!Z()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!Z()&&R.stdout.isTTY)R.stdout.write(`
112
+ `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Z()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:r,message:`${W.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
113
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":W.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Z())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Qn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Z())throw Error("createReadStream is not supported in browser environments");if(!Sn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return eh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.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=Zt.isBuffer(t)?t:Zt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Tw("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,o=Zt.allocUnsafe(a);return l.copy(o,0),h.copy(o,l.length),o.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Z()}isServerMode(){return!Z()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
114
+ `),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,o=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:W.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(h),showTimestamp:!1})),o.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(a),showTimestamp:!1}))}else if(!Z())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
115
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(Z())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();R.stdin.removeListener("data",r);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(a,o)=>{if(o==="%")return"%";if(h>=i.length)return a;let y=i[h++];switch(o){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 a}}),h<i.length)r+=` ${i.slice(h).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${h}${l} ${W.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
116
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=W.green("━".repeat(n)),s=W.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?W.green("✓"):W.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",y=`\r${a}${o} ${c} ${l}${h}`,u=R.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,R.stdout.write(t.lastRenderedLine),i)R.stdout.write(`
117
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||Z()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(Z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Bn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=qi(this.config.logDirectory,n);if(t.before)try{if((await xi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);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 Rn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var oE=new Qn("stacks");class Kt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,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(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class bh extends Kt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class Dn extends Kt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class Dh extends Kt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class ph extends Kt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class ns extends Kt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class Vh extends Kt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ph extends Kt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class pn extends Kt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class vh extends Kt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class Qh extends Kt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Di={configNotFound(t,i,r){return new bh(t,i,r)},configLoad(t,i,r){return new Dn(t,i,r)},configValidation(t,i,r){return new Dh(t,i,r)},configMerge(t,i,r,n){return new ph(t,i,r,n)},envVar(t,i,r,n){return new ns(t,i,r,n)},fileSystem(t,i,r){return new Vh(t,i,r)},typeGeneration(t,i,r){return new Ph(t,i,r)},schemaValidation(t,i,r){return new pn(t,i,r)},browserConfig(t,i,r,n){return new vh(t,i,r,n)},plugin(t,i,r){return new Qh(t,i,r)}};async function L$(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class es{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Vf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=Un.env[l]||(h?Un.env[h]:void 0);if(a!==void 0){if(n.verbose){let o=Un.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof ns)throw o;throw Di.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Di.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Un.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
118
+
119
+ `;for(let n of t)r+=`${n.key}
120
+ `,r+=` Type: ${n.type}
121
+ `,r+=` Description: ${n.description}
122
+ `,r+=` Example: ${n.example}
123
+
124
+ `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
125
+
126
+ `;r+=`| Variable | Type | Description | Example |
127
+ `,r+=`|----------|------|-------------|----------|
128
+ `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
129
+ `;return r}}function G$(t,i,r={}){return Zh(t,i,r,new WeakMap)}function Zh(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return ta(t,i,e,n);if(!Ut(i)||!Ut(t))return i;return b$(t,i,r,n)}function ta(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return x$(t,i);case"smart":return q$(t,i,n);default:return i}return i}function x$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>pf(e,n)))r.push(n);return r}function q$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Ut(i[0])&&Ut(t[0]))return k$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function k$(t,i,r){let n=[...i];for(let e of t){if(!Ut(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Ut(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function b$(t,i,r,n){let e=i;if(Ut(e)&&n.has(e))return n.get(e);let f={...t};if(Ut(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Ut(c)&&Ut(l))f[s]=Zh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ta(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ia(t,i,r="replace"){return G$(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function pf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!pf(t[r],i[r]))return!1;return!0}if(Ut(t)&&Ut(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!pf(t[e],i[e]))return!1}return!0}return!1}function Ut(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class ra{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Jn.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Fn(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new Dn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new Dn(t,Error("Configuration must export a valid object"),"unknown");let d={config:ia(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Jn.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?Di.configLoad(t,h):Di.configLoad(t,Error(String(h)))}};if(s)return Vf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Of(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return L$(async()=>{return Fn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Fn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Of(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Of(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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(t))}async validateConfigFile(t){let i=[];try{if(!Fn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var p$=/^https?:\/\//;class na{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await Vf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!D$(i))throw new pn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new pn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:p$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ti=new Qn("bunfig",{showTags:!0});function V$(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class ea{fileLoader=new ra;envProcessor=new es;validator=new na;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)ti.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw ti.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||Vn.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(Rt(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw Di.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${V$(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Nn(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)ti.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)ti.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Nn(t,r,e):r,c=[Rt(Ji(),".config",t),Rt(Ji(),".config"),Ji()];for(let l of c){if(e)ti.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)ti.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Nn(t,n,f):n;try{let l=Rt(r,"package.json");if(!Gy(l))return null;let h={};try{h=JSON.parse(xy(l,"utf8"))}catch(y){if(f)ti.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let a=h[t],o=t;if(!a&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if(h[u]){a=h[u],o=u;break}}}if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)ti.success(`Configuration loaded from package.json: ${o}`);return{config:ia(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)ti.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Nn(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Di.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Jn.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Jn.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Rt(t,"config"),Rt(t,".config"),i?Rt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Rt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Rt(Ji(),".config",t),Rt(Ji(),".config"),Ji()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var mE=new ea;function Nn(t,i,r=!1){let n=new es,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=Vn.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}var dE=Rt(Vn.cwd(),"config"),AE=Rt(Vn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",P$={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:ss(fs(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:ss(fs(),".stacks","ssl","stacks.localhost.crt"),keyPath:ss(fs(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var fa=P$;import{execSync as wr}from"node:child_process";import{homedir as i0}from"node:os";import{join as r0}from"node:path";import{execSync as Zn}from"node:child_process";function sa(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function te(t){try{let i=Zn(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return sa(i)}catch{return null}}function v$(t){try{return Zn(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function Q$(t,i){try{let r=Zn(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((n)=>r.includes(`DNS:${n}`))}catch{return!1}}function Z$(t,i,r=443){try{return Zn(`echo | openssl s_client -connect ${t}:${r} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function t0(t){let i=[];for(let r of t.split(`
130
+ `)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var ui="-d -r trustRoot -p ssl -p basic",Ei="/Library/Keychains/System.keychain",ls="rpx.localhost";function $r(){return r0(i0(),"Library/Keychains/login.keychain-db")}function cs(){return[Ei,$r()]}function la(t,i=ls){let r=wr(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let e of r.split(`
131
+ `)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function ie(t){if(process.platform!=="darwin")return;let i=te(t.caPath);if(!i)return;let r=t.commonName??ls,n=t.keychains??cs();for(let e of n)for(let f of la(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))yr(`security delete-certificate -Z ${f} "${e}"`);else wr(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});$("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function mr(t,i,r){if(process.platform!=="darwin")return dr(t,r);try{let e=wr(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return $("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,r?.verbose),e}catch{return!1}}function dr(t,i){let r=te(t);if(!r)return!1;for(let n of cs())try{let e=wr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let f of e.split(`
132
+ `))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return $("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function hs(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;ie({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=$r();try{wr(`security add-trusted-cert ${ui} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{yr(`security add-trusted-cert ${ui} -k ${Ei} "${t}"`)}catch{return!1}return mr(t,r,{verbose:i.verbose})||dr(t,{verbose:i.verbose})}var yi=null,n0="rpx-root-ca.crt",e0="rpx-root-ca.key";function us(t){return{caCertPath:tt(t,n0),caKeyPath:tt(t,e0)}}function qE(t){return{certPath:tt(t,"rpx.localhost.crt"),keyPath:tt(t,"rpx.localhost.key"),caCertPath:tt(t,"rpx.localhost.ca.crt"),rootCA:us(t)}}async function f0(t,i){try{let[r,n]=await Promise.all([D.readFile(t.caCertPath,"utf8"),D.readFile(t.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return $("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:r,privateKey:n}}catch(r){return $("ssl",`No existing Root CA at ${t.caCertPath} (${r.code||r}), will create one`,i),null}}function ca(t){let i=new Set;i.add(t);let r=t.split(".");if(r.length>=2)i.add(`*.${r.slice(1).join(".")}`);return Array.from(i)}function ya(t){let r=os(t).replace(/\*/g,"wildcard"),n=tt(ne(),".stacks","ssl"),e=n;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:n,{caCertPath:t.https.caCertPath||tt(e,`${r}.ca.crt`),certPath:t.https.certPath||tt(e,`${r}.crt`),keyPath:t.https.keyPath||tt(e,`${r}.key`)};return{caCertPath:tt(e,`${r}.ca.crt`),certPath:tt(e,`${r}.crt`),keyPath:tt(e,`${r}.key`)}}function ha(t){let i=new Set;if(re(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";ca(n).forEach((e)=>i.add(e))});else if(oa(t)){let r=t.to||"rpx.localhost";ca(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function kE(t){$("ssl","Loading SSL configuration",t.verbose);let i={...fa,...t};if(t.https=ws(i),!t.https?.keyPath&&!t.https?.certPath)return $("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let r=!t.https?.keyPath?"keyPath":"certPath";throw $("ssl",`Invalid SSL configuration - missing ${r}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{$("ssl","Reading SSL certificate files",t.verbose);let r=await D.readFile(t.https?.keyPath,"utf8"),n=await D.readFile(t.https?.certPath,"utf8");return $("ssl","SSL configuration loaded successfully",t.verbose),{key:r,cert:n}}catch(r){return $("ssl",`Failed to read certificates: ${r}`,t.verbose),null}}catch(r){throw $("ssl",`SSL configuration error: ${r}`,t.verbose),r}}async function bE(t,i){if(Mt.platform==="darwin")return s0(t,i);if(Mt.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)n(!0);else r(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function s0(t,i){if(Mt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(mr(t,r,{verbose:n}))return $("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return $("ssl","Trusting Root CA for browsers (login + system keychains)",n),hs(t,{serverName:r,verbose:n})}catch{return!1}}async function wa(t){if(yi&&!t.forceRegenerate){$("ssl","Using cached SSL configuration",t.verbose);return}l0();let i=re(t)?t.proxies.map((a)=>a.to):[t.to];$("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=ws(t,t.verbose),n=r.basePath||tt(ne(),".stacks","ssl");await D.mkdir(n,{recursive:!0});let e=us(n),f=await f0(e,t.verbose),s=!1;if(!f){if(t.verbose)K.info("Generating Root CA certificate (one-time)...");f=await $f(r);try{await Promise.all([D.writeFile(e.caCertPath,f.certificate),D.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,$("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(a){throw $("ssl",`Error saving Root CA files: ${a}`,t.verbose),Error(`Failed to save Root CA files: ${a}`)}}else $("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)K.info(`Generating host certificate for: ${i.join(", ")}`);let c=await mf({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([D.writeFile(r.certPath,c.certificate),D.writeFile(r.keyPath,c.privateKey),D.writeFile(r.caCertPath,f.certificate)]),$("ssl","Certificate files saved successfully",t.verbose)}catch(a){throw $("ssl",`Error saving certificate files: ${a}`,t.verbose),Error(`Failed to save certificate files: ${a}`)}if(s?!1:await $a(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if($("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)K.success("Root CA is already trusted in system trust store");if(yi={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)K.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)K.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Mt.platform==="darwin")try{ie({caPath:e.caCertPath,verbose:t.verbose});let a=$r();try{pi(`security add-trusted-cert ${ui} -k "${a}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(yr(`security add-trusted-cert ${ui} -k ${Ei} "${e.caCertPath}"`),t.verbose)K.success("Successfully added Root CA to system trust store");h=!0;let o=tt(n,"trust-rpx-cert.sh"),y=`#!/bin/bash
133
+ echo "Trusting RPX Root CA"
134
+ sudo security add-trusted-cert ${ui} -k ${Ei} "${e.caCertPath}"
135
+ echo "Root CA trusted! Please restart your browser."
136
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
137
+ `;await D.writeFile(o,y,{mode:493})}catch(a){if(t.verbose)K.warn(`Could not add Root CA to trust store automatically: ${a}`);let o=tt(n,"trust-rpx-cert.sh"),y=`#!/bin/bash
138
+ echo "Trusting RPX Root CA"
139
+ sudo security add-trusted-cert ${ui} -k ${Ei} "${e.caCertPath}"
140
+ echo "Root CA trusted! Please restart your browser."
141
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
142
+ `;if(await D.writeFile(o,y,{mode:493}),t.verbose)K.info(`Created a trust helper script at: ${o}`),K.info(`If you're still having certificate issues, run: sh ${o}`)}else if(Mt.platform==="linux")try{let{exec:a}=await import("node:child_process"),o="/usr/local/share/ca-certificates/rpx",y=`
143
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
144
+ cp "${e.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
145
+ update-ca-certificates
146
+ echo "RPX Root CA installed. Please restart your browser."
147
+ `,u=tt(as.tmpdir(),`rpx-trust-${Date.now()}.sh`);await D.writeFile(u,y,{mode:493}),await new Promise((m)=>{a(`sudo bash "${u}"`,(w)=>{if(w){if(t.verbose)K.warn(`Could not trust certificates: ${w}`);m(!1)}else{if(t.verbose)K.success("Successfully added certificates to system trust store");m(!0)}})}),await D.unlink(u).catch(()=>{}),h=!0}catch(a){if(t.verbose)K.warn(`Failed to trust certificates: ${a}`)}else if(Mt.platform==="win32")try{let a=`
148
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${e.caCertPath.replace(/\//g,"\\")}")
149
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
150
+ $store.Open("ReadWrite")
151
+ $store.Add($cert)
152
+ $store.Close()
153
+ Write-Host "Root CA trusted successfully!"
154
+ `,o=tt(as.tmpdir(),"rpx-trust.ps1");if(await D.writeFile(o,a),pi(`powershell -ExecutionPolicy Bypass -File "${o}"`),t.verbose)K.success("Successfully added certificate to Windows trust store");h=!0}catch(a){if(t.verbose)K.warn(`Could not trust certificate: ${a}`)}else try{await df(c,f.certificate,r),h=!0}catch(a){if(t.verbose)K.warn(`Could not add certificate to trust store: ${a}`)}if(yi={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)K.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)K.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),K.warn("This will bypass the warning and you should only need to do it once")}function l0(){yi=null}async function ys(t){if(!t)return null;if(yi)return yi;let i=ws(t);try{let[r,n,e]=await Promise.all([D.access(i.keyPath).then(()=>!0).catch(()=>!1),D.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?D.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return $("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;$("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||tt(ne(),".stacks","ssl"),h=us(l);if(!(c?await $a(h.caCertPath,t):!0))return $("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[o,y,u]=await Promise.all([D.readFile(i.keyPath,"utf8"),D.readFile(i.certPath,"utf8"),e&&i.caCertPath?D.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(u&&!u.includes("-----BEGIN CERTIFICATE-----"))return $("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(re(t))try{let{X509Certificate:m}=await import("node:crypto"),d=new m(y).subjectAltName||"",T=t.proxies.map((Y)=>Y.to).filter((Y)=>!d.includes(`DNS:${Y}`));if(T.length>0)return $("ssl",`Certificate missing SANs for: ${T.join(", ")}, will regenerate`,t.verbose),null}catch(m){$("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return $("ssl","Successfully loaded existing certificates",t.verbose),yi={key:o,cert:y,ca:u},yi}catch(r){return $("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function ws(t,i){let r=os(t);$("ssl",`Primary domain: ${r}`,i);let n=ya(t),e=tt(ne(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(ha(t)).map((c)=>({type:2,value:c}))};if(aa(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(ha(t)).map((f)=>({type:2,value:f}))}}async function DE(t,i){let r=ya({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];$("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>ua(e,i)))}async function $a(t,i){try{if($("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Mt.platform==="darwin"){if(i?.serverName)return mr(t,i.serverName,{verbose:i.verbose});return dr(t,{verbose:i.verbose})}else if(Mt.platform==="win32")try{let n=pi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!n)return $("ssl","Could not extract certificate subject",i?.verbose),!1;let e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(pi(e).toString().includes(n))return $("ssl","Certificate found in trusted root store",i?.verbose),!0;return $("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return $("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Mt.platform==="linux")try{let n=pi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",e=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of e)try{if(pi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${n}"`).toString().includes(n))return $("ssl",`Certificate fingerprint found in ${f}`,i?.verbose),!0}catch{}return $("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return $("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return $("ssl",`Platform ${Mt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return $("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}import*as Ft from"node:path";function ma(t,i){if(typeof t==="string")return{dir:t,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:i};return{dir:t.dir,spa:t.spa??!1,pathRewriteStyle:t.pathRewriteStyle??"directory",maxAge:t.maxAge??0,cleanUrls:i}}var c0={".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 h0(t){let i=Ft.extname(t).toLowerCase();return c0[i]??"application/octet-stream"}function a0(t){let i;try{i=decodeURIComponent(t)}catch{return null}if(i.includes("\x00")||i.includes("\\"))return null;let r=Ft.posix.normalize(`/${i}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function o0(t,i){let r=a0(t);if(r===null)return null;let n=Ft.posix.extname(r);if(i.cleanUrls&&n===".html"){let e=t.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ft.join(i.dir,r),redirectTo:e||"/"}}if(r===""||t.endsWith("/"))return{filePath:Ft.join(i.dir,r,"index.html")};if(n!=="")return{filePath:Ft.join(i.dir,r)};if(i.pathRewriteStyle==="flat")return{filePath:Ft.join(i.dir,`${r}.html`)};return{filePath:Ft.join(i.dir,r,"index.html")}}async function da(t,i){let r=o0(t,i);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=i.maxAge>0?`public, max-age=${i.maxAge}`:"no-cache",e=Bun.file(r.filePath);if(await e.exists())return new Response(e,{status:200,headers:{"Content-Type":h0(r.filePath),"Cache-Control":n}});if(i.spa){let f=Ft.join(i.dir,"index.html"),s=Bun.file(f);if(await s.exists())return new Response(s,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var u0=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function y0(t){return(t.headers.get("host")||"").split(":")[0]}function Aa(t,i,r){let n=new URL(t.url),e=i.sourceHost??"",f=n.pathname,s=Ea(n.pathname,i.pathRewrites);if(s)e=s.targetHost,f=s.targetPath,$("request",`Path rewrite: ${n.pathname} → ${e}${f}`,r);return{targetHost:e,targetPath:f,search:n.search}}function Ta(t,i){return async(r,n)=>{let e=new URL(r.url),f=y0(r),s=t(f);if(!s)return $("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});if(s.static)return da(e.pathname,s.static);if(r.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!n||!s.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:o,targetPath:y,search:u}=Aa(r,s,i),m=`ws://${o}${y}${u}`,w={};for(let[T,Y]of r.headers)if(!u0.has(T.toLowerCase())&&T.toLowerCase()!=="host")w[T]=Y;w.host=o,w["x-forwarded-for"]="127.0.0.1",w["x-forwarded-proto"]="https",w["x-forwarded-host"]=f;let d={targetUrl:m,forwardHeaders:w};if(n.upgrade(r,{data:d})){$("ws",`upgraded ${f}${y} → ${m}`,i);return}return new Response("WebSocket upgrade failed",{status:400})}if(!s.sourceHost)return new Response(`No upstream configured for ${f}`,{status:502});let{targetHost:c,targetPath:l,search:h}=Aa(r,s,i),a=`http://${c}${l}${h}`;try{let o=new Headers(r.headers);if(o.set("host",c),s.changeOrigin)o.set("origin",`http://${s.sourceHost}`);o.set("x-forwarded-for","127.0.0.1"),o.set("x-forwarded-proto","https"),o.set("x-forwarded-host",f);let y=await fetch(a,{method:r.method,headers:o,body:r.body,redirect:"manual"});if(s.cleanUrls&&e.pathname.endsWith(".html")){let m=e.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let u=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:u})}catch(o){return $("request",`Proxy error for ${f}: ${o}`,i),new Response(`Proxy Error: ${o}`,{status:502})}}}function Ca(t){let i=new WeakMap;return{open(r){let{targetUrl:n,forwardHeaders:e}=r.data,f;try{f=new WebSocket(n,{headers:e})}catch(c){$("ws",`failed to open upstream ${n}: ${c}`,t),r.close(1011,"upstream connect failed");return}f.binaryType="arraybuffer";let s={upstream:f,upstreamOpen:!1,pending:[]};i.set(r,s),f.addEventListener("open",()=>{s.upstreamOpen=!0;for(let c of s.pending)f.send(c);s.pending=[]}),f.addEventListener("message",(c)=>{r.send(c.data)}),f.addEventListener("close",(c)=>{try{r.close(c.code||1000,c.reason||"")}catch{}}),f.addEventListener("error",()=>{$("ws",`upstream error for ${n}`,t);try{r.close(1011,"upstream error")}catch{}})},message(r,n){let e=i.get(r);if(!e)return;let f=typeof n==="string"?n:new Uint8Array(n);if(e.upstreamOpen)e.upstream.send(f);else e.pending.push(f)},close(r,n,e){let f=i.get(r);if(!f)return;i.delete(r);try{f.upstream.close(n||1000,e||"")}catch{}}}}function ga(t){return t.startsWith("*.")}function w0(t,i){if(!ga(i))return!1;let r=i.slice(1);return t.length>r.length&&t.endsWith(r)}function Sa(t,i){let r=t.get(i);if(r!==void 0)return r;let n,e=-1;for(let[f,s]of t){if(!ga(f))continue;if(w0(i,f)){let c=f.length-1;if(c>e)e=c,n=s}}return n}import*as Ar from"node:fs/promises";import*as $s from"node:path";function $0(t){if(!t.endsWith(".crt"))return null;let i=t.slice(0,-4);if(i.length===0)return null;if(i.startsWith("_wildcard."))return`*.${i.slice(10)}`;return i}async function m0(t,i,r,n){try{let[e,f]=await Promise.all([Ar.readFile(i,"utf8"),Ar.readFile(r,"utf8")]);return{serverName:t,cert:e,key:f}}catch(e){return $("sni",`skipping ${t}: ${e.message}`,n),null}}async function Ba(t,i){let r=new Map;if(t.certsDir){let e=[];try{e=await Ar.readdir(t.certsDir)}catch(f){$("sni",`certsDir read failed (${t.certsDir}): ${f.message}`,i)}for(let f of e){let s=$0(f);if(!s)continue;let c=f.slice(0,-4);r.set(s,{certPath:$s.join(t.certsDir,f),keyPath:$s.join(t.certsDir,`${c}.key`)})}}if(t.domains)for(let[e,f]of Object.entries(t.domains))r.set(e,f);let n=[];for(let[e,f]of r){let s=await m0(e,f.certPath,f.keyPath,i);if(s)n.push(s)}return n}import*as wi from"node:fs/promises";import*as ms from"node:path";var d0=60000;function A0(t,i){if(!i||i.length===0)return!1;return i.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return t===n||t.endsWith(`.${n}`)})}function E0(t){if(!t||t.length>253)return!1;if(t.includes("/")||t.includes(":")||t.includes(" "))return!1;if(t.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(t)}class ds{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(t){this.config=t.config,this.certsDir=t.certsDir,this.onCertAdded=t.onCertAdded,this.http01Store=t.http01Store??an,this.issuer=t.issuer??tf,this.verbose=t.verbose??!1,this.negativeCacheMs=t.negativeCacheMs??d0;for(let i of t.initial??[])this.certs.set(i.serverName,i)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(t){return this.certs.has(t)}async isApproved(t){if(!E0(t))return!1;if(A0(t,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(t)}catch(i){return $("on-demand",`ask(${t}) threw: ${i.message}`,this.verbose),!1}return!1}async ensureCert(t){if(!this.config.enabled)return!1;if(this.certs.has(t))return!0;let i=this.inFlight.get(t);if(i)return i;let r=this.negativeCache.get(t);if(r!==void 0&&Date.now()<r)return $("on-demand",`${t} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(t).finally(()=>{this.inFlight.delete(t)});return this.inFlight.set(t,n),n}async issue(t){if(this.certs.has(t))return!0;if(await this.loadFromDisk(t))return!0;if(!await this.isApproved(t))return $("on-demand",`refused issuance for ${t} (not approved)`,this.verbose),!1;try{$("on-demand",`issuing cert for ${t} (staging=${this.config.staging??!1})`,this.verbose);let i=await this.issuer({domains:[t],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(t,i.fullChainPem,i.keyPem);let r={serverName:t,cert:i.fullChainPem,key:i.keyPem};return this.certs.set(t,r),this.negativeCache.delete(t),$("on-demand",`issued + installed cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(i){return this.negativeCache.set(t,Date.now()+this.negativeCacheMs),$("on-demand",`issuance for ${t} failed: ${i.message}`,this.verbose),!1}}async loadFromDisk(t){let{certPath:i,keyPath:r}=this.pathsFor(t);try{let[n,e]=await Promise.all([wi.readFile(i,"utf8"),wi.readFile(r,"utf8")]),f={serverName:t,cert:n,key:e};return this.certs.set(t,f),$("on-demand",`adopted existing on-disk cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(t){return{certPath:ms.join(this.certsDir,`${t}.crt`),keyPath:ms.join(this.certsDir,`${t}.key`)}}async persist(t,i,r){await wi.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:e}=this.pathsFor(t);await Promise.all([wi.writeFile(n,i,"utf8"),wi.writeFile(e,r,{encoding:"utf8",mode:384})])}}import*as ee from"node:fs";import*as wt from"node:fs/promises";import{homedir as T0}from"node:os";import*as As from"node:path";import*as fe from"node:process";var C0=/^[a-zA-Z0-9._-]+$/;function Pi(){return As.join(T0(),".stacks","rpx","registry.d")}function Es(t){return typeof t==="string"&&t.length>0&&t.length<=128&&C0.test(t)}function Ts(t,i){if(!Es(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return As.join(t,`${i}.json`)}function zt(t){if(!Number.isInteger(t)||t<=0)return!1;try{return fe.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Ra(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0,n=typeof i.from==="string"&&i.from.length>0,e=typeof i.static==="string"||!!i.static&&typeof i.static==="object"&&typeof i.static.dir==="string";return typeof i.id==="string"&&Es(i.id)&&(n||e)&&typeof i.to==="string"&&i.to.length>0&&r&&typeof i.createdAt==="string"}async function g0(t){await wt.mkdir(t,{recursive:!0})}async function hT(t,i=Pi(),r){if(!Ra(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await g0(i);let n=Ts(i,t.id),e=`${n}.tmp.${fe.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await wt.writeFile(e,f,{encoding:"utf8",mode:420}),await wt.rename(e,n),$("registry",`wrote entry ${t.id} → ${n}`,r)}catch(s){throw await wt.unlink(e).catch(()=>{}),s}}async function S0(t,i=Pi(),r){let n=Ts(i,t);try{await wt.unlink(n),$("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function B0(t,i=Pi(),r){let n=Ts(i,t);try{let e=await wt.readFile(n,"utf8"),f=JSON.parse(e);if(!Ra(f))return $("registry",`entry ${t} failed validation, removing`,r),await wt.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return $("registry",`entry ${t} has invalid JSON, removing`,r),await wt.unlink(n).catch(()=>{}),null;throw e}}async function Vi(t=Pi(),i){let r;try{r=await wt.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!Es(f))continue;let s=await B0(f,t,i);if(s)n.push(s)}return n}async function Cs(t=Pi(),i){let r=await Vi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!zt(e.pid))$("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await S0(e.id,t,i).catch(()=>{}),n++}return n}function Ya(t,i={}){let r=i.dir??Pi(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;ee.mkdirSync(r,{recursive:!0});let s=null,c=!1,l=null,h=!1,a=(d)=>{return JSON.stringify(d.map((A)=>({id:A.id,from:A.from,to:A.to,pid:A.pid,pathRewrites:A.pathRewrites,cleanUrls:A.cleanUrls,changeOrigin:A.changeOrigin,static:A.static})).sort((A,T)=>A.id.localeCompare(T.id)))},o=()=>{if(s=null,c)return;Vi(r,f).then((d)=>{return l=a(d),t(d)}).catch((d)=>{$("registry",`watcher onChange failed: ${d}`,f)})},y=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(o,n)},m=setInterval(()=>{if(c||h)return;h=!0,Vi(r,f).then((d)=>{if(a(d)!==l)y()}).catch((d)=>{$("registry",`watcher poll failed: ${d}`,f)}).finally(()=>{h=!1})},e),w=ee.watch(r,{persistent:!0},(d,A)=>{if(A&&/\.tmp\.\d+\.\d+$/.test(A))return;y()});return w.on("error",(d)=>{$("registry",`watcher error: ${d}`,f)}),y(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),w.close()}}}var R0=5000;function $t(){return Nt.join(Ss(),".stacks","rpx")}function se(t=$t()){return Nt.join(t,"daemon.pid")}async function vi(t=$t()){try{let i=await Gt.readFile(se(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Y0(t=$t()){let i=await vi(t);return i!==null&&zt(i)}async function U0(t=$t()){await Gt.mkdir(t,{recursive:!0});let i=se(t);while(!0){try{let n=await Gt.open(i,"wx");try{await n.write(`${N.pid}
155
+ `)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await vi(t);if(r!==null&&zt(r))throw Error(`rpx daemon already running (pid=${r})`);await Gt.unlink(i).catch(()=>{})}}async function Er(t=$t()){await Gt.unlink(se(t)).catch(()=>{})}function F0(t){let i=t.cleanUrls??!1;if(t.static)return{static:ma(t.static,i),cleanUrls:i};let r=t.from??"localhost:1";return{sourceHost:new URL(r.startsWith("http")?r:`http://${r}`).host,cleanUrls:i,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function N0(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function j0(t,i){let r=await Vi(i,t.verbose),n=[...new Set(r.map((a)=>a.to))],e=N0(n),f=[...new Set([e,...n,"rpx.localhost"])],s=Nt.join(Ss(),".stacks","ssl"),c=Nt.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:Nt.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:Nt.join(s,"rpx.localhost.key"),caCertPath:Nt.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((a)=>({from:"localhost:1",to:a}))}:{to:e,from:"localhost:1"}},h=await ys(l);if(!h)$("daemon","no usable cert on disk, generating one",t.verbose),await wa(l),h=await ys(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function W0(t,i,r,n){let e=N.env.SUDO_PASSWORD,f=N.env.HOME??Ss(),s=[N.execPath,...N.argv.slice(1)],c=[`HOME=${f}`,`PATH=${N.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");let l=e?["-S","-p","","env",...c,...s]:["-n","env",...c,...s];$("daemon",`elevating daemon via sudo for privileged ports ${i}/${r}`,n);let h=Ua("sudo",l,{detached:!0,stdio:["pipe","ignore","ignore"]}),a=null,o=null;if(h.once("error",(m)=>{a=m}),h.once("exit",(m)=>{o=m??0}),e&&h.stdin)h.stdin.write(`${e}
156
+ `),h.stdin.end();h.unref();let y=se(t),u=Date.now()+15000;while(Date.now()<u){if(a)throw a;let m=await vi(t);if(m!==null&&zt(m)){if(n)K.success(`rpx daemon elevated to root (pid=${m}, https on :${i})`);return{httpsPort:i,httpPort:r,pidPath:y,done:Promise.resolve(),stop:async()=>{try{N.kill(m,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(o!==null&&o!==0)throw Error(`rpx daemon could not elevate to bind :${i} (sudo exited ${o}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((w)=>setTimeout(w,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${t})`)}async function BT(t={}){let i=t.verbose??!1,r=t.rpxDir??$t(),n=t.registryDir??Nt.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??R0,l=e>0&&e<1024||f>0&&f<1024,h=typeof N.getuid==="function"&&N.getuid()===0;if(N.platform!=="win32"&&l&&!h)return W0(r,e,f,i);let a=await U0(r),o=new Map,y=(g)=>Sa(o,g);function u(g){let L=new Map;for(let Wt of g)L.set(Wt.to,F0(Wt));o=L,$("daemon",`routing table now covers ${L.size} host(s): ${Array.from(L.keys()).join(", ")||"<empty>"}`,i)}await Cs(n,i).catch((g)=>{$("daemon",`initial gc failed: ${g}`,i)});let m=await Vi(n,i);u(m),await Cr({rpxDir:r,verbose:i}).catch((g)=>{$("daemon",`DNS reconcile on start failed: ${g}`,i)}),await gs(m,{rpxDir:r,verbose:i,ownerPid:N.pid}).catch((g)=>{$("daemon",`DNS setup on start failed: ${g}`,i)});let w=[];if(t.productionCerts){if(w=await Ba(t.productionCerts,i),i&&w.length>0)K.info(`SNI: serving ${w.length} real cert(s): ${w.map((g)=>g.serverName).join(", ")}`)}let d=Ta(y,i),A=Ca(i),T=null;if(w.length===0)T=await j0(t,n);let Y=t.onDemandTls,S=Y?.enabled?new ds({config:Y,certsDir:Y.certsDir??t.productionCerts?.certsDir??Nt.join(r,"on-demand-certs"),initial:w,verbose:i,onCertAdded:(g)=>{Qi(g)}}):null;function X(g){if(g.length>0)return g.map((L)=>({serverName:L.serverName,cert:L.cert,key:L.key}));return{key:T.key,cert:T.cert,ca:T.ca,requestCert:!1,rejectUnauthorized:!1}}function xt(g){return Bun.serve({port:e,hostname:s,tls:X(g),fetch(L,Wt){return d(L,Wt)},websocket:A,error(L){return $("daemon",`https server error: ${L}`,i),new Response(`Server Error: ${L.message}`,{status:500})}})}let jt=xt(S?S.sniEntries():w);async function Qi(g){if(Sr)return;$("daemon",`rebuilding :443 with ${g.length} SNI cert(s)`,i),jt.stop(!1);let L;for(let Wt=0;Wt<20&&!Sr;Wt++)try{jt=xt(g);return}catch(Br){L=Br,await new Promise((za)=>setTimeout(za,25))}K.error(`rpx: failed to rebuild :443 after issuing cert: ${L?.message}`)}let Lt=null;if(f>0)Lt=Bun.serve({port:f,hostname:s,fetch(g){let L=new URL(g.url),Wt=(g.headers.get("host")??L.hostname).split(":")[0];if(S&&L.pathname.startsWith("/.well-known/acme-challenge/")){let Br=S.challengeStore.handlePath(L.pathname);if(Br!==void 0)return new Response(Br,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(S&&!S.hasCert(Wt))S.ensureCert(Wt).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${Wt}${L.pathname}${L.search}`}})}});if(i)K.success(`rpx daemon listening on https://${s}:${e}${Lt?` (http→https on :${f})`:""}`),K.info(`pid file: ${a}`),K.info(`registry: ${n}`);let Ma=Ya((g)=>{u(g),gs(g,{rpxDir:r,verbose:i,ownerPid:N.pid}).catch((L)=>{$("daemon",`DNS sync on registry change failed: ${L}`,i)})},{dir:n,verbose:i}),oe=setInterval(()=>{Cs(n,i).then((g)=>{if(g>0)$("daemon",`gc reaped ${g} stale entries`,i)}).catch((g)=>{$("daemon",`periodic gc failed: ${g}`,i)})},c);if(typeof oe.unref==="function")oe.unref();let Sr=!1,Xs,ue=new Promise((g)=>{Xs=g});async function _s(){if(Sr)return ue;if(Sr=!0,clearInterval(oe),Ma.close(),jt.stop(!1),Lt?.stop(!1),await Tr({rpxDir:r,verbose:i}).catch((g)=>{$("daemon",`DNS teardown failed: ${g}`,i)}),await Er(r),i)K.info("rpx daemon stopped");return Xs(),ue}let Is=(g)=>{$("daemon",`received ${g}, shutting down`,i),_s().catch(()=>{})};return N.once("SIGINT",Is),N.once("SIGTERM",Is),{stop:_s,done:ue,httpsPort:typeof jt.port==="number"?jt.port:e,httpPort:Lt&&typeof Lt.port==="number"?Lt.port:f,pidPath:a,ensureCert:(g)=>S?S.ensureCert(g):Promise.resolve(!1)}}function X0(){let t=N.execPath,i=Nt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&N.argv[1])return[t,N.argv[1],"daemon:start"];return[t,"daemon:start"]}async function RT(t={}){let i=t.rpxDir??$t(),r=t.verbose??!1;await Cr({rpxDir:i,verbose:r}).catch((a)=>{$("daemon",`DNS reconcile before ensureDaemonRunning: ${a}`,r)});let n=await vi(i);if(n!==null&&zt(n))return $("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)$("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await Er(i);await Gt.mkdir(i,{recursive:!0});let e=t.spawnCommand??X0();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");$("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=Ua(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??N.cwd(),env:t.spawnEnv?{...N.env,...t.spawnEnv}:N.env});f.unref();let s=null;f.once("error",(a)=>{s=a});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let a=await vi(i);if(a!==null&&zt(a))return $("daemon",`daemon registered with pid=${a}`,r),{pid:a,spawned:!0};await new Promise((o)=>setTimeout(o,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function YT(t={}){let i=t.rpxDir??$t(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await vi(i);if(s===null||!zt(s)){if(s!==null)await Er(i);return await Cr({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{N.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await Er(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+n;while(Date.now()<c){if(!zt(s))return $("daemon",`daemon pid=${s} stopped cleanly`,r),{stopped:!0,pid:s,forced:!1};await new Promise((l)=>setTimeout(l,e))}if(!f)throw Error(`rpx daemon (pid=${s}) did not exit within ${n}ms`);$("daemon",`daemon pid=${s} did not exit, escalating to SIGKILL`,r);try{N.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await Er(i),await Tr({rpxDir:i,verbose:r}).catch((l)=>{$("daemon",`DNS teardown after SIGKILL: ${l}`,r)}),{stopped:!0,pid:s,forced:!0}}async function UT(t={}){let i=t.rpxDir??$t();if(await Y0(i))return;await Cr({rpxDir:i,verbose:t.verbose})}import*as $i from"node:fs/promises";import{homedir as _0}from"node:os";import*as Bs from"node:path";var le=1,I0="dns-state.json",Fa=["com","test","dev","app","page","local","localhost","example","invalid"];function Na(){return Bs.join(_0(),".stacks","rpx")}function Rs(t=Na()){return Bs.join(t,I0)}async function ce(t=Na()){try{let i=await $i.readFile(Rs(t),"utf8"),r=JSON.parse(i);if(r.version!==le||!Array.isArray(r.resolvers))return null;return{version:le,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(i){if(i.code==="ENOENT")return null;throw i}}async function ja(t,i){await $i.mkdir(t,{recursive:!0}),await $i.writeFile(Rs(t),`${JSON.stringify(i,null,2)}
157
+ `,"utf8")}async function Ys(t){await $i.rm(Rs(t),{force:!0})}function Wa(t){let i=t.trim().toLowerCase().replace(/\.$/,"");if(!i||i.includes("127.0.0.1"))return null;if(i==="localhost"||i.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(i))return null;return i}function J0(t){let i=Wa(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function Us(t){let i=new Set;for(let r of t){let n=J0(r);if(n)i.add(n)}return Array.from(i).sort()}function Fs(t){let i=new Set;for(let r of t){let n=Wa(r);if(n)i.add(n)}return Array.from(i).sort()}var Ns=15353,H0="# managed-by: rpx",Ia="/etc/resolver",mt=null,he=new Set;function K0(t){return{id:t.readUInt16BE(0),flags:t.readUInt16BE(2),qdcount:t.readUInt16BE(4),ancount:t.readUInt16BE(6),nscount:t.readUInt16BE(8),arcount:t.readUInt16BE(10)}}function Ja(t,i){let r=[],n=i;while(!0){let e=t[n];if(e===0){n++;break}if((e&192)===192){let f=t.readUInt16BE(n)&16383,{name:s}=Ja(t,f);r.push(s),n+=2;break}n++,r.push(t.subarray(n,n+e).toString("ascii")),n+=e}return{name:r.join("."),newOffset:n}}function M0(t,i){let{name:r,newOffset:n}=Ja(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function ae(t){let i=t.split("."),r=[];for(let n of i)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function z0(t,i,r){let n=[],e=Buffer.alloc(12);e.writeUInt16BE(t,0),e.writeUInt16BE(33152,2),e.writeUInt16BE(1,4),e.writeUInt16BE(1,6),e.writeUInt16BE(0,8),e.writeUInt16BE(0,10),n.push(e),n.push(ae(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(ae(i.name));let s=Buffer.alloc(10);if(s.writeUInt16BE(i.type,0),s.writeUInt16BE(1,2),s.writeUInt32BE(300,4),i.type===1){s.writeUInt16BE(4,8),n.push(s);let c=r.split(".").map((l)=>Number.parseInt(l,10));n.push(Buffer.from(c))}else if(i.type===28)s.writeUInt16BE(16,8),n.push(s),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return e.writeUInt16BE(33155,2),e.writeUInt16BE(0,6),Buffer.concat([e,ae(i.name),f]);return Buffer.concat(n)}function L0(t,i){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(t,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(ae(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),r.push(e),Buffer.concat(r)}async function G0(t,i){if(fi.platform!=="darwin")return!1;let r=Fs(t);if(r.length===0)return!1;if(mt){for(let n of r)he.add(n);return $("dns","DNS server already running — merged domains",i),!0}return he=new Set(r),new Promise((n)=>{mt=O0.createSocket("udp4"),mt.on("error",(e)=>{$("dns",`DNS server error: ${e.message}`,i),mt?.close(),mt=null,n(!1)}),mt.on("message",(e,f)=>{try{let s=K0(e),{question:c}=M0(e,12);$("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let o of he)if(l===o||l.endsWith(`.${o}`)){h=!0;break}let a;if(h&&(c.type===1||c.type===28))a=z0(s.id,c,"127.0.0.1"),$("dns",`Responding with localhost for ${c.name}`,i);else a=L0(s.id,c),$("dns",`NXDOMAIN for ${c.name}`,i);mt?.send(a,f.port,f.address)}catch(s){$("dns",`Error processing DNS query: ${s}`,i)}}),mt.on("listening",()=>{let e=mt?.address();$("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),n(!0)});try{mt.bind(Ns,"127.0.0.1")}catch(e){$("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function Oa(t){if(mt)$("dns","Stopping DNS server",t),mt.close(),mt=null,he=new Set}function OT(){return mt!==null}function x0(){return`${H0}
158
+ nameserver 127.0.0.1
159
+ port ${Ns}
160
+ `}function gr(t){return _a.join(Ia,t)}function q0(t){return t.includes("127.0.0.1")&&t.includes(String(Ns))}async function k0(t){try{return await Xa.readFile(gr(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function js(t){if(fi.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:r}=await import("./chunk-kv17r01q.js");if(!r()){$("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),$("dns","DNS cache flushed",t)}catch(n){$("dns",`Could not flush DNS cache: ${n}`,t)}}async function b0(t,i){let{execSudoSync:r}=await import("./chunk-kv17r01q.js"),n=x0().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Ia} && printf "%b" "${n}" > ${gr(t)}'`;r(e),$("dns",`Created ${gr(t)}`,i)}async function D0(t,i){let{execSudoSync:r}=await import("./chunk-kv17r01q.js");r(`rm -f ${gr(t)}`),$("dns",`Removed ${gr(t)}`,i)}async function HT(t,i){return Ka({domains:i??[],verbose:t})}async function p0(t,i){if(fi.platform!=="darwin")return!0;let{getSudoPassword:r}=await import("./chunk-kv17r01q.js");if(!r())return $("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let n of t)await b0(n,i);return await js(i),!0}catch(n){return $("dns",`Failed to create resolver file: ${n}`,i),!1}}async function Ws(t,i){if(fi.platform!=="darwin")return;let{getSudoPassword:r}=await import("./chunk-kv17r01q.js");if(!r())return;try{for(let n of t)await D0(n,i);await js(i)}catch(n){$("dns",`Failed to remove resolver files: ${n}`,i)}}async function Ha(t){if(fi.platform!=="darwin")return[];let i=[];for(let r of Fa){let n=await k0(r);if(n&&q0(n))await Ws([r],t),i.push(r)}return i}async function Ka(t){let i=t.rpxDir??$t(),r=Fs(t.domains);if(r.length===0)return!1;let n=Us(r);if(!await G0(r,t.verbose))return!1;if(!await p0(n,t.verbose))return!1;let s={version:le,resolvers:n,domains:r,ownerPid:t.ownerPid??fi.pid,updatedAt:new Date().toISOString()};return await ja(i,s),!0}async function gs(t,i={}){let r=t.map((l)=>l.to).filter(Boolean),n=i.rpxDir??$t(),e=Us(r),c=((await ce(n))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await Ws(c,i.verbose);if(e.length===0){Oa(i.verbose),await Ys(n);return}await Ka({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??fi.pid})}async function Tr(t={}){let i=t.rpxDir??$t();Oa(t.verbose);let n=(await ce(i))?.resolvers??[];await Ws(n,t.verbose),await Ha(t.verbose),await Ys(i)}async function KT(t){await Tr({verbose:t})}async function Cr(t={}){let i=t.rpxDir??$t(),r=await ce(i),n=r?.ownerPid!=null&&zt(r.ownerPid);if(r&&!n){$("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,t.verbose),await Tr(t);return}let e=await Ha(t.verbose);if(e.length>0)$("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await js(t.verbose)}
161
+ export{K as a,fa as b,sa as c,te as d,v$ as e,Q$ as f,Z$ as g,t0 as h,ui as i,Ei as j,ls as k,$r as l,cs as m,la as n,ie as o,mr as p,dr as q,hs as r,us as s,qE as t,kE as u,bE as v,wa as w,l0 as x,ys as y,ws as z,DE as A,$a as B,ma as C,h0 as D,a0 as E,o0 as F,da as G,Ta as H,Ca as I,ga as J,w0 as K,Sa as L,$0 as M,Ba as N,A0 as O,E0 as P,ds as Q,Pi as R,Es as S,zt as T,hT as U,S0 as V,B0 as W,Vi as X,Cs as Y,Ya as Z,le as _,Fa as $,Wa as aa,J0 as ba,Us as ca,Fs as da,Ns as ea,H0 as fa,G0 as ga,Oa as ha,OT as ia,gr as ja,q0 as ka,HT as la,Ha as ma,Ka as na,gs as oa,Tr as pa,KT as qa,Cr as ra,$t as sa,se as ta,vi as ua,Y0 as va,U0 as wa,Er as xa,BT as ya,X0 as za,RT as Aa,YT as Ba,UT as Ca};