@stacksjs/rpx 0.11.27 → 0.11.29
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.
- package/dist/bin/cli.js +130 -110
- package/dist/{chunk-6nvjwawp.js → chunk-22h4jf2c.js} +1 -1
- package/dist/chunk-9dh9jhc6.js +252 -0
- package/dist/{chunk-r1k4wgag.js → chunk-ws2cmbxh.js} +1 -1
- package/dist/{chunk-2yk7jygq.js → chunk-z86swbd8.js} +1 -1
- package/dist/daemon.d.ts +11 -0
- package/dist/hosts.d.ts +70 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +2 -9
- package/dist/load-balancer.d.ts +8 -0
- package/package.json +2 -2
- package/dist/chunk-6m0f5m3q.js +0 -224
package/dist/chunk-6m0f5m3q.js
DELETED
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import{Ab as Xf,Bb as Ah,Db as dh,Eb as Eh,ob as g,rb as Or,sb as T,tb as Yu,xb as eh,yb as i0}from"./chunk-2yk7jygq.js";import Nu from"node:dgram";import*as Fu from"node:fs/promises";import*as Xu from"node:path";import*as ut from"node:process";import{spawn as mu}from"node:child_process";import*as Ai from"node:fs/promises";import{homedir as Bu}from"node:os";import*as bi from"node:path";import*as s from"node:process";var X={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as oc}from"node:child_process";import v from"node:fs/promises";import*as pc from"node:os";import{homedir as Ar}from"node:os";import*as Th from"node:path";import{join as b}from"node:path";import*as gi from"node:process";import{createRequire as qu}from"node:module";import{Resolver as vf}from"node:dns/promises";import{createHash as gu,sign as xu}from"node:crypto";import{createHash as du}from"node:crypto";import{sign as ku}from"node:crypto";import{generateKeyPairSync as x$,X509Certificate as pu}from"node:crypto";import Zf from"node:os";import of from"node:path";import{existsSync as q0,statSync as L0}from"fs";import{existsSync as te,mkdirSync as mB,readdirSync as BB,readFileSync as re,writeFileSync as CB}from"fs";import{homedir as qt}from"os";import{dirname as UB,resolve as Fi}from"path";import Gn from"process";import{existsSync as g0,statSync as x0}from"fs";import{existsSync as Ul,mkdirSync as ne,readdirSync as fe,writeFileSync as le}from"fs";import{homedir as Lt}from"os";import{dirname as d0,resolve as Ti}from"path";import Wt from"process";import{join as ce,relative as $e,resolve as k0}from"path";import Cn from"process";import{existsSync as d$,mkdirSync as IB,readdirSync as KB,writeFileSync as zB}from"fs";import{homedir as pf}from"os";import{dirname as MB,resolve as Ei}from"path";import ar from"process";import{join as we,relative as ye,resolve as V0}from"path";import sn from"process";import{existsSync as k$,mkdirSync as xB,readdirSync as dB,writeFileSync as kB}from"fs";import{dirname as DB,resolve as Rn}from"path";import jl from"process";import{Buffer as At}from"buffer";import{createCipheriv as he,createDecipheriv as ue,randomBytes as il}from"crypto";import{closeSync as tl,createReadStream as D0,createWriteStream as ee,existsSync as rl,fsyncSync as b0,openSync as Q0,writeFileSync as Ae}from"fs";import{access as Ee,constants as P0,mkdir as Te,readdir as vr,rename as v0,stat as gt,unlink as Zr,writeFile as nl}from"fs/promises";import{join as xt}from"path";import $i from"process";import{pipeline as Ye}from"stream/promises";import{createGzip as Z0}from"zlib";import dt from"process";import oi from"process";import{Buffer as Pi}from"buffer";import{createCipheriv as me,createDecipheriv as Be,randomBytes as fl}from"crypto";import{closeSync as ll,createReadStream as o0,createWriteStream as Ce,existsSync as or,fsyncSync as p0,openSync as i$,writeFileSync as se}from"fs";import{access as Re,constants as t$,mkdir as Ue,readdir as pr,rename as r$,stat as kt,unlink as tn,writeFile as cl}from"fs/promises";import{isAbsolute as je,join as Vt,resolve as Se}from"path";import H from"process";import{pipeline as ae}from"stream/promises";import{createGzip as n$}from"zlib";import Dt from"process";import pi from"process";import rn from"process";import{existsSync as nn}from"fs";import{resolve as $l}from"path";import{existsSync as Ne}from"fs";import{existsSync as Fe,readdirSync as Xe}from"fs";import{extname as wl,resolve as f$}from"path";import We from"process";import{join as Je,relative as _e,resolve as l$}from"path";import Un from"process";import{Buffer as vi}from"buffer";import{createCipheriv as Ie,createDecipheriv as Ke,randomBytes as yl}from"crypto";import{closeSync as hl,createReadStream as c$,createWriteStream as ze,existsSync as fn,fsyncSync as $$,openSync as w$,writeFileSync as Oe}from"fs";import{access as Ge,constants as y$,mkdir as Me,readdir as ln,rename as h$,stat as bt,unlink as cn,writeFile as ul}from"fs/promises";import{isAbsolute as He,join as Qt,resolve as qe}from"path";import q from"process";import{pipeline as Le}from"stream/promises";import{createGzip as u$}from"zlib";import Pt from"process";import it from"process";import $n from"process";import{existsSync as wn}from"fs";import{resolve as el}from"path";import{existsSync as ge}from"fs";import{exec as yA}from"node:child_process";import zl from"node:fs";import hA from"node:os";import zi from"node:path";import Nw from"node:process";import{promisify as uA}from"node:util";import pt from"node:crypto";import tt from"node:fs";import Ml from"node:path";import zA from"node:crypto";import OA from"node:fs";import GA from"node:tls";import{execSync as qA}from"node:child_process";import zn from"node:os";var Lu=qu(import.meta.url);async function W$(i,t,r={}){let n=r.timeoutMs??120000,f=r.intervalMs??3000,l=i.split(".").slice(-2).join("."),c;try{let y=new vf,h=await y.resolveNs(l),u=(await Promise.all(h.map((e)=>y.resolve4(e).catch(()=>[])))).flat();if(u.length>0)c=new vf,c.setServers(u)}catch{}let $=Date.now()+n,w=c??new vf;for(;;){try{if((await w.resolveTxt(i)).some((y)=>y.join("")===t))return!0}catch{}if(Date.now()>=$)return!1;await new Promise((y)=>setTimeout(y,f))}}class Sr{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Sr.PATH_PREFIX);if(t===-1)return;let r=i.slice(t+Sr.PATH_PREFIX.length);return this.get(r)}}var On=new Sr;function un(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function Bl(i){return Buffer.from(i,"base64url")}function J$(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function _$(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return gu("sha256").update(t).digest("base64url")}function I$(i){let{protectedHeader:t,payload:r,privateKey:n}=i,f=un(JSON.stringify(t)),l=r===""?"":un(JSON.stringify(r)),c=`${f}.${l}`,$=xu("sha256",Buffer.from(c),{key:n,dsaEncoding:"ieee-p1363"});return{protected:f,payload:l,signature:un($)}}var K$="https://acme-staging-v02.api.letsencrypt.org/directory",z$="https://acme-v02.api.letsencrypt.org/directory";class mn extends Error{problem;httpStatus;constructor(i,t,r){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class Bn{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=J$(i.accountPublicKey),this.thumbprint=_$(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await fetch(this.directoryUrl);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await fetch(i.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:r,useJwk:n}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)f.jwk=this.jwk;else f.kid=this.requireKid();let l=I$({protectedHeader:f,payload:r,privateKey:this.accountKey}),c=await fetch(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(l)}),$=c.headers.get("replay-nonce");if($)this.nonce=$;let w=c.headers.get("content-type")??"",y;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))y=await c.text();else{let h=await c.text();y=h?JSON.parse(h):{}}if(c.status>=400){let h=y??{};throw new mn(`ACME request to ${t} failed (HTTP ${c.status}): ${h.type??""} ${h.detail??""}`.trim(),h,c.status)}return{status:c.status,headers:c.headers,body:y,location:c.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(i.email)r.contact=[`mailto:${i.email}`];let n=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(i){let t=await this.directory(),r={identifiers:i.map((f)=>({type:"dns",value:f}))},n=await this.signedPost({url:t.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return du("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let l=await this.getAuthorization(i);if(l.status==="valid")return;if(l.status==="invalid"){let c=l.challenges.find(($)=>$.status==="invalid");throw new mn(`Authorization for ${l.identifier.value} became invalid: ${c?.error?.detail??"unknown reason"}`,c?.error??{},0)}await H0(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let l=await this.getOrder(i);if(l.status==="valid"){if(!l.certificate)throw Error("ACME order is valid but has no certificate URL");return l.certificate}if(l.status==="invalid")throw Error(`ACME order ${i} became invalid`);await H0(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let r=i.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return r}}function O$(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${i.trim()}
|
|
2
|
-
`,chainPem:""};let n=`${r.trim()}
|
|
3
|
-
`,f=t.slice(1).map((l)=>l.trim()).join(`
|
|
4
|
-
`);return{certPem:n,chainPem:f?`${f}
|
|
5
|
-
`:""}}function G$(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function H0(i){return new Promise((t)=>setTimeout(t,i))}function Vu(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Yt(i,t){return Buffer.concat([Buffer.from([i]),Vu(t.length),t])}function M$(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=[],n=i;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Yt(2,t)}function Xt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let f=t[n],l=[f&127];f=Math.floor(f/128);while(f>0)l.unshift(f&127|128),f=Math.floor(f/128);r.push(...l)}return Yt(6,Buffer.from(r))}function Ni(...i){return Yt(48,Buffer.concat(i))}function Cl(...i){return Yt(49,Buffer.concat(i))}function sl(i){return Yt(3,Buffer.concat([Buffer.from([0]),i]))}function H$(i){return Yt(4,i)}function q$(i){return Yt(12,Buffer.from(i,"utf8"))}function Rl(i,t,r){let n=128|(r?32:0)|i;return Yt(n,t)}var Du="1.2.840.10045.2.1",bu="1.2.840.10045.3.1.7",Qu="1.2.840.10045.4.3.2",Pu="2.5.4.3",vu="1.2.840.113549.1.9.14",Zu="2.5.29.17";function ou(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Bl(t.x),n=Bl(t.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function L$(i){let{domains:t,publicKey:r,privateKey:n}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Ni(Cl(Ni(Xt(Pu),q$(t[0])))),l=Ni(Ni(Xt(Du),Xt(bu)),sl(ou(r))),c=t.map((E)=>Rl(2,Buffer.from(E,"ascii"),!1)),$=Ni(...c),w=Ni(Xt(Zu),H$($)),y=Ni(w),h=Ni(Xt(vu),Cl(y)),u=Rl(0,h,!0),e=Ni(M$(0),f,l,u),A=ku("sha256",e,n),m=Ni(Xt(Qu));return Ni(e,m,sl(A))}function g$(i){return L$(i).toString("base64url")}function ie(i){if(i){let{createPrivateKey:f,createPublicKey:l}=Lu("node:crypto"),c=f(i),$=l(c);return{privateKey:c,publicKey:$,pem:i}}let{privateKey:t,publicKey:r}=x$("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function Hl(i){let{domains:t,method:r}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((u)=>u.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=i.directoryUrl??(i.staging===!1?z$:K$),f=ie(i.accountKeyPem),l=new Bn({directoryUrl:n,accountKey:f.privateKey,accountPublicKey:f.publicKey});await l.newAccount({email:i.email});let{order:c,orderUrl:$}=await l.newOrder(t),w=i.http01Store??On,y=[],h=[];try{for(let j of c.authorizations){let F=await l.getAuthorization(j);if(F.status==="valid")continue;let M=Bn.selectChallenge(F,r);if(r==="dns-01"){let o=G$(F.identifier.value),ki=l.dns01TxtValue(M.token);await i.dnsProvider.setTxt(o,ki),y.push({name:o,value:ki}),await W$(o,ki,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(M.token,l.keyAuthorization(M.token)),h.push(M.token);await l.notifyChallengeReady(M.url),await l.pollAuthorization(j,{timeoutMs:i.timeoutMs})}let{privateKey:u,publicKey:e}=x$("ec",{namedCurve:"P-256"}),A=g$({domains:t,publicKey:e,privateKey:u});await l.finalizeOrder(c.finalize,A);let m=await l.pollOrder($,{timeoutMs:i.timeoutMs}),E=await l.downloadCertificate(m),{certPem:Y,chainPem:B}=O$(E),C=B?`${Y}${B}`:Y,a=u.export({format:"pem",type:"pkcs8"}).toString(),N=new Date(new pu(Y).validTo);return{certPem:Y,keyPem:a,chainPem:B,fullChainPem:C,accountKeyPem:f.pem,notAfter:N}}finally{for(let{name:u,value:e}of y)await i.dnsProvider?.removeTxt(u,e).catch(()=>{});for(let u of h)w.remove(u)}}class V${cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!q0(i))return!0;return L0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=q0(r)?L0(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class D${metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var jn=new V$,ql=new D$,xe=Object.defineProperty,de=(i)=>i;function ke(i,t){this[i]=de.bind(null,t)}var Ve=(i,t)=>{for(var r in t)xe(i,r,{get:t[r],enumerable:!0,configurable:!0,set:ke.bind(t,r)})},De=(i,t)=>()=>(i&&(t=i(i=0)),t),b$={};Ve(b$,{withErrorRecovery:()=>v$,tryLoadConfig:()=>T1,loadConfigWithResult:()=>A1,loadConfig:()=>tw,isRetryableError:()=>$1,isConfigNotFoundError:()=>c1,isBunfigError:()=>Z$,globalPerformanceMonitor:()=>Wr,globalCache:()=>Zt,getEnvOrDefault:()=>w1,generateConfigTypes:()=>Y1,defaultGeneratedDir:()=>yw,defaultConfigDir:()=>ww,deepMergeWithArrayStrategy:()=>kl,deepMerge:()=>o$,createLibraryConfig:()=>m1,config:()=>E1,bunfigPlugin:()=>B1,applyEnvVarsToConfig:()=>Ur,TypeGenerationError:()=>Jl,SchemaValidationError:()=>Fr,PluginError:()=>Il,PerformanceMonitor:()=>gl,FileSystemError:()=>Wl,ErrorFactory:()=>Tt,EnvVarError:()=>Wn,EnvProcessor:()=>Mn,ConfigValidator:()=>Vl,ConfigValidationError:()=>Fl,ConfigNotFoundError:()=>Xn,ConfigMergeError:()=>Xl,ConfigLoader:()=>Dl,ConfigLoadError:()=>Nr,ConfigFileLoader:()=>Hn,ConfigCache:()=>Ll,CacheUtils:()=>nw,BunfigError:()=>Ui,BrowserConfigError:()=>_l,ArrayMergeStrategies:()=>cw});class Ll{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!g0(i))return!0;return x0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=g0(r)?x0(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class gl{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function be(i,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${i}:${r}`:i}function Qe(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function Pe(i){return i.getStats().size*2}function xl(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let n=[...t];for(let f of i)if(V(f)&&"name"in f){if(!n.find((l)=>V(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(V(f)&&"path"in f){if(!n.find((l)=>V(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((l)=>Sn(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!V(t)||!V(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(V(f)&&V(r[n]))r[n]=xl(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&V(f[0])&&V(r[n][0])){let l=[...f];for(let c of r[n])if(V(c)&&"name"in c){if(!l.find(($)=>V($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(V(c)&&"path"in c){if(!l.find(($)=>V($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some(($)=>Sn($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Sn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Sn(i[r],t[r]))return!1;return!0}if(V(i)&&V(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Sn(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function ve(i,t){if(!k$(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return xl(t,n)}catch{return null}}catch{return null}}async function Ze({name:i="",cwd:t,defaultConfig:r}){let n=t||jl.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let $ of f){let w=Rn(n,`${c}${$}`),y=await ve(w,r);if(y!==null)return y}try{let c=Rn(n,"package.json");if(k$(c)){let $=(await import(c))[i];if($&&typeof $==="object"&&!Array.isArray($))try{return xl(r,$)}catch{}}}catch{}return r}function oe(i,t={}){let r=sn.cwd();while(r.includes("storage"))r=V0(r,"..");let n=V0(r,i||"");if(t?.relative)return ye(sn.cwd(),n);return n}async function pe(){try{let i=await Ze({name:"clarity",defaultConfig:An,cwd:sn.cwd(),endpoint:"",headers:{}});return{...An,...i}}catch{return An}}function Q(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function i1(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof oi<"u"){let i=oi.type;if(i==="renderer"||i==="worker")return!1;return!!(oi.versions&&(oi.versions.node||oi.versions.bun))}return!1}class Q${async format(i){let t=await i1(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:dt.pid,hostname:t(),environment:dt.env.NODE_ENV||"development",platform:dt.platform,version:dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dt.env.NODE_ENV||dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class an{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...al},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Q$,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??$i.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...En,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...En};return{...En,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:al.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await Ee(this.config.logDirectory,P0.F_OK|P0.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await Te(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:At.from(i);try{if(!rl(this.currentLogFile))await nl(this.currentLogFile,"",{mode:420});if(n=Q0(this.currentLogFile,"a",420),Ae(n,$,{flag:"a"}),b0(n),n!==void 0)tl(n),n=void 0;if((await gt(this.currentLogFile)).size===0){if(await nl(this.currentLogFile,$,{flag:"w",mode:420}),(await gt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let y=w;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(f<l-1){let h=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,h);let u=c*2**f;await new Promise((e)=>setTimeout(e,u)),f++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(n!==void 0)try{tl(n)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch($){if(f===l-1){let y=$,h=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),$}f++;let w=c*2**(f-1);await new Promise((y)=>setTimeout(y,w))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return xt(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 xt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return xt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return il(16).toString("hex")}generateKey(){return il(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=il(16),n=he("aes-256-gcm",t,r),f=At.concat([n.update(i,"utf8"),n.final()]),l=n.getAuthTag();return{encrypted:At.concat([r,f,l]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Z0(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(At.from(At.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(Q())return;let i=await gt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await vr(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await gt(r).catch(()=>null))try{if(await v0(r,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await Zr($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await nl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await gt(r).catch(()=>null))await v0(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await vr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await Zr(xt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=D0(i),n=ee(t),f=Z0();await Ye(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),rl(this.currentLogFile))try{let i=Q0(this.currentLogFile,"r+");b0(i),tl(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await vr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Zr(xt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?d.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=$i.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${d.cyan(f)}`;if(!c)return y.trim();let h=$(y).trim().length,u=$(t).length,e=Math.max(1,w-2-h-u);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);if(this.fancy&&!Q()){let y=fw[i],h=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",u;switch(i){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:d.gray(c),level:i}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:d.green(c),level:i}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(u),$){let e=$.split(`
|
|
6
|
-
`);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:d.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let w=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
|
|
7
|
-
`;if($)w+=`${$}
|
|
8
|
-
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!Q()){let r=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:d.blue("◐"),tag:r,message:`${d.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)w+=` ${JSON.stringify(r)}`;if(w+=`
|
|
9
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!Q()){let y=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:d.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Q())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new an(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Q())throw Error("createReadStream is not supported in browser environments");if(!rl(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return D0(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=At.isBuffer(i)?i:At.from(i,"base64"),f=n.slice(0,16),l=n.slice(-16),c=n.slice(16,-16),$=ue("aes-256-gcm",r,f);return $.setAuthTag(l),At.concat([$.update(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(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!Q()){let l=i.split(`
|
|
10
|
-
`),c=Math.max(...l.map((h)=>h.length))+2,$=`┌${"─".repeat(c)}┐`,w=`└${"─".repeat(c)}┘`,y=l.map((h)=>{let u=" ".repeat(c-h.length-2);return`│ ${h}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:d.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:d.cyan($)})),y.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:d.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:d.cyan(w),showTimestamp:!1}))}else if(!Q())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${d.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();$i.stdin.removeListener("data",r);try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!1)}catch{}$i.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!0)}catch{}$i.stdin.resume(),$i.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,l=0;if(r=i.replace(f,(c,$)=>{if($==="%")return"%";if(l>=t.length)return c;let w=t[l++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return c}}),l<t.length)r+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!Q()){let f=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",l=d.blue("◐");console.error(`${l} ${f} ${d.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(i,t=""){if(!this.enabled||!this.fancy||Q()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,n)),f!==void 0)this.activeProgressBar.message=f;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},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,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;$i.stdout.write(`${"\r".padEnd($i.stdout.columns||80)}\r`),this.log(f,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||Q()||!$i.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=d.green("━".repeat(n)),c=d.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=t||r===100?d.green("✓"):d.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",e=`\r${h}${u} ${$} ${w}${y}`,A=$i.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,$i.stdout.write(i.lastRenderedLine),t)$i.stdout.write(`
|
|
13
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||Q()||!$i.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await vr(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=xt(this.config.logDirectory,n);if(i.before)try{if((await gt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);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 Zr(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function en(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&L(t[0])&&"id"in t[0]&&t[0].id===3&&L(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(L(t)&&L(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&L(t[0])&&L(i[0])){let n=[...t];for(let f of i)if(L(f)&&"name"in f){if(!n.find((l)=>L(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(L(f)&&"path"in f){if(!n.find((l)=>L(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((l)=>Nn(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!L(t)||!L(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(L(f)&&L(r[n]))r[n]=en(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&L(f[0])&&L(r[n][0])){let l=[...f];for(let c of r[n])if(L(c)&&"name"in c){if(!l.find(($)=>L($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(L(c)&&"path"in c){if(!l.find(($)=>L($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some(($)=>Nn($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function dl(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:en(i,t);if(Array.isArray(i))return r==="replace"?t:en(i,t);if(!L(t)||!L(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=n[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(r==="replace")n[f]=l;else n[f]=en(c,l);else if(L(l)&&L(c))n[f]=dl(c,l,r);else n[f]=l}return n}function Nn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Nn(i[r],t[r]))return!1;return!0}if(L(i)&&L(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Nn(i[f],t[f]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function yn(i,t,r="replace"){if(!d$(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return dl(t,f,r)}catch{return null}}catch{return null}}function t1(i,t,r=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,$=[]){let w={...c};for(let[y,h]of Object.entries(c)){let u=[...$,y],e=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${n}_${u.map(e).join("_")}`,m=`${n}_${u.map((E)=>E.toUpperCase()).join("_")}`;if(r)yi.info(`Checking environment variable ${A} for config ${i}.${u.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[y]=l(h,u);else{let E=ar.env[A]||ar.env[m];if(E!==void 0){if(r)yi.info(`Using environment variable ${E?A:m} for config ${i}.${u.join(".")}`);if(typeof h==="number")w[y]=Number(E);else if(typeof h==="boolean")w[y]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let Y=JSON.parse(E);if(Array.isArray(Y))w[y]=Y;else w[y]=E.split(",").map((B)=>B.trim())}catch{w[y]=E.split(",").map((Y)=>Y.trim())}else w[y]=E}}}return w}return l(f)}async function r1({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:$="replace"}){let w=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?t1(i,f,l):f,y=r||ar.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(l)yi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${y}`);let u=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([y,Ei(y,"config"),Ei(y,".config"),n?Ei(y,n):void 0].filter(Boolean)));for(let Y of E){if(l)yi.info(`Searching for configuration in: ${Y}`);let B=[Ei(y,"config"),Ei(y,".config")].concat(n?[Ei(y,n)]:[]).includes(Y)?[...u,...e,...A,...m]:[...e,...u,...m,...A];for(let C of B)for(let a of h){let N=Ei(Y,`${C}${a}`),j=await yn(N,w,$);if(j!==null){if(l)yi.success(`Configuration loaded from: ${N}`);return j}}}if(i){let Y=Ei(pf(),".config",i),B=["config",`${i}.config`];if(t)B.push(`${t}.config`);if(l)yi.info(`Checking user config directory: ${Y}`);for(let C of B)for(let a of h){let N=Ei(Y,`${C}${a}`),j=await yn(N,w,$);if(j!==null){if(l)yi.success(`Configuration loaded from user config directory: ${N}`);return j}}}if(i){let Y=Ei(pf(),".config"),B=[`.${i}.config`];if(t)B.push(`.${t}.config`);if(l)yi.info(`Checking user config directory for dotfile configs: ${Y}`);for(let C of B)for(let a of h){let N=Ei(Y,`${C}${a}`),j=await yn(N,w,$);if(j!==null){if(l)yi.success(`Configuration loaded from user config directory dotfile: ${N}`);return j}}}if(i){let Y=pf(),B=[`.${i}.config`,`.${i}`];if(t)B.push(`.${t}.config`),B.push(`.${t}`);if(l)yi.info(`Checking user home directory for dotfile configs: ${Y}`);for(let C of B)for(let a of h){let N=Ei(Y,`${C}${a}`),j=await yn(N,w,$);if(j!==null){if(l)yi.success(`Configuration loaded from user home directory: ${N}`);return j}}}try{let Y=Ei(y,"package.json");if(d$(Y)){let B=await import(Y),C=B[i];if(!C&&t){if(C=B[t],C&&l)yi.success(`Using alias "${t}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(l)yi.success(`Configuration loaded from package.json: ${C===B[i]?i:t}`);return dl(w,C,$)}catch(a){if(l)yi.warn("Failed to merge package.json config:",a)}}}catch(Y){if(l)yi.warn("Failed to load package.json:",Y)}if(l)yi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function n1(i,t={}){let r=Cn.cwd();while(r.includes("storage"))r=k0(r,"..");let n=k0(r,i||"");if(t?.relative)return $e(Cn.cwd(),n);return n}async function f1(){try{let i=await r1({name:"clarity",alias:"logging",defaultConfig:Tn,cwd:Cn.cwd()});return{...Tn,...i||{}}}catch{return Tn}}function p(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function l1(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pi<"u"){let i=pi.type;if(i==="renderer"||i==="worker")return!1;return!!(pi.versions&&(pi.versions.node||pi.versions.bun))}return!1}class P${async format(i){let t=await l1(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Fn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Nl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new P$,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Yn,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Yn};return{...Yn,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Nl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await Re(this.config.logDirectory,t$.F_OK|t$.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await Ue(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Pi.from(i);try{if(!or(this.currentLogFile))await cl(this.currentLogFile,"",{mode:420});if(n=i$(this.currentLogFile,"a",420),se(n,$,{flag:"a"}),p0(n),n!==void 0)ll(n),n=void 0;if((await kt(this.currentLogFile)).size===0){if(await cl(this.currentLogFile,$,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let y=w;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(f<l-1){let h=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,h);let u=c*2**f;await new Promise((e)=>setTimeout(e,u)),f++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(n!==void 0)try{ll(n)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch($){if(f===l-1){let y=$,h=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),$}f++;let w=c*2**(f-1);await new Promise((y)=>setTimeout(y,w))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return fl(16).toString("hex")}generateKey(){return fl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=fl(16),n=me("aes-256-gcm",t,r),f=Pi.isBuffer(i)?i:Pi.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,w=n.getAuthTag(),y=Pi.allocUnsafe(16+$+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),w.copy(y,16+$),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=n$(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(Pi.from(Pi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let i=await kt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await pr(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await kt(r).catch(()=>null))try{if(await r$(r,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await tn($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await cl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await kt(r).catch(()=>null))await r$(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await pr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await tn(Vt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=o0(i),n=Ce(t),f=n$();await ae(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),or(this.currentLogFile))try{let i=i$(this.currentLogFile,"r+");p0(i),ll(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await pr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await tn(Vt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?K.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=H.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${K.cyan(f)}`;if(!c)return y.trim();let h=$(y).trim().length,u=$(t).length,e=Math.max(1,w-2-h-u);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=K.underline(K.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>K.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>K.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>K.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>K.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>K.strikethrough(n)),t}supportsHyperlinks(){if(p())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=H.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(je(t)||t.startsWith("./")||t.startsWith("../"))t=Se(t);else return null;return or(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":lw[i],e=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:K.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:K.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let m=$.split(`
|
|
14
|
-
`);for(let E of m)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
15
|
-
`;if($)h+=`${$}
|
|
16
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!p()&&H.stdout.isTTY)H.stdout.write(`
|
|
17
|
-
`);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:r,message:`${K.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)w+=` ${JSON.stringify(r)}`;if(w+=`
|
|
18
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":K.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!p())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Fn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!or(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return o0(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Pi.isBuffer(i)?i:Pi.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=Be("aes-256-gcm",r,f);$.setAuthTag(l);let w=$.update(c),y=$.final(),h=w.length+y.length,u=Pi.allocUnsafe(h);return w.copy(u,0),y.copy(u,w.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
19
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,y=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:K.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(y),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(h),showTimestamp:!1}))}else if(!p())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(p())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();H.stdin.removeListener("data",r);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(r=i.replace(c,(w,y)=>{if(y==="%")return"%";if($>=t.length)return w;let h=t[$++];switch(y){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),$<t.length)r+=` ${t.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${$}${c} ${K.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=K.green("━".repeat(n)),c=K.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?K.green("✓"):K.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",e=`\r${h}${u} ${$} ${w}${y}`,A=H.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
|
|
22
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await pr(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,n);if(i.before)try{if((await kt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);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(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function v$(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function Z$(i){return i instanceof Ui}function c1(i){return i instanceof Xn}function $1(i){if(Z$(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class Mn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Wr.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${$.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=rn.env[w]||(y?rn.env[y]:void 0);if(h!==void 0){if(n.verbose){let u=rn.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,w,n.customParsers,n.configName)}catch(u){if(u instanceof Wn)throw u;throw Tt.envVar(w,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Tt.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(rn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
23
|
-
|
|
24
|
-
`;for(let n of i)r+=`${n.key}
|
|
25
|
-
`,r+=` Type: ${n.type}
|
|
26
|
-
`,r+=` Description: ${n.description}
|
|
27
|
-
`,r+=` Example: ${n.example}
|
|
28
|
-
|
|
29
|
-
`;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
|
|
30
|
-
|
|
31
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
32
|
-
`,r+=`|----------|------|-------------|----------|
|
|
33
|
-
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
34
|
-
`;return r}}function w1(i,t){let r=rw("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function o$(i,t,r={}){return p$(i,t,r,new WeakMap)}function p$(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return iw(i,t,f,n);if(!Xi(t)||!Xi(i))return t;return e1(i,t,r,n)}function iw(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return y1(i,t);case"smart":return h1(i,t,n);default:return t}return t}function y1(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Sl(f,n)))r.push(n);return r}function h1(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Xi(t[0])&&Xi(i[0]))return u1(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function u1(i,t,r){let n=[...t];for(let f of i){if(!Xi(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((w)=>Xi(w)&&($ in w)&&w[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function e1(i,t,r,n){let f=t;if(Xi(f)&&n.has(f))return n.get(f);let l={...i};if(Xi(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Xi($)&&Xi(w))l[c]=p$(w,$,r,n);else if(Array.isArray($)||Array.isArray(w))l[c]=iw(w,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function kl(i,t,r="replace"){return o$(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Sl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Sl(i[r],t[r]))return!1;return!0}if(Xi(i)&&Xi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Sl(i[f],t[f]))return!1}return!0}return!1}function Xi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Hn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let y=Zt.getWithFileCheck("file",i);if(y){if($)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!nn(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),u=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new Nr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Nr(i,Error("Configuration must export a valid object"),"unknown");let m={config:kl(t,u,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Zt.setWithFileCheck("file",m,i,l);return m}catch(y){throw y instanceof Error?Tt.configLoad(i,y):Tt.configLoad(i,Error(String(y)))}};if(c)return Wr.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push($l(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return v$(async()=>{return nn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!nn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=$l(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=$l(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!nn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class Vl{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=r,y=async()=>{let h=[],u=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:u}}};if($)return await Wr.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!Ne(t))throw new Fr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Fr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let y=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:$w},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Dl{fileLoader=new Hn;envProcessor=new Mn;validator=new Vl;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw w;if(u&&(!y||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)Oi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){let w=Date.now()-t;throw Oi.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:y="replace",verbose:h=!1}=i,u=l||Wt.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,u,c,$,y,h,w,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,u,c)),this.finalizeResult(A,e,w,n,h);let m=await this.loadHomeConfiguration(n,f,$,y,h,w);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,u,$,y,h,w);if(E)return e.push(Ti(u,"package.json")),this.finalizeResult(E,e,w,n,h);if(e.push(...this.getAllSearchPaths(n,f,u,c)),t)throw Tt.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,w,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,w){let y=$?Ur(i,f,c):f,h=this.getLocalDirectories(r,n);for(let u of h){if(c)Oi.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)Oi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?Ur(i,r,f):r,$=[Ti(Lt(),".config",i),Ti(Lt(),".config"),Lt()];for(let w of $){if(f)Oi.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)Oi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?Ur(i,n,l):n;try{let w=Ti(r,"package.json");if(!Ul(w))return null;let y=await import(w),h=y[i],u=i;if(!h&&t)h=y[t],u=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)Oi.success(`Configuration loaded from package.json: ${u}`);return{config:kl($,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)Oi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ur(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Tt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return Zt.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);Zt.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ti(i,"config"),Ti(i,".config"),t?Ti(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ti(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ti(Lt(),".config",i),Ti(Lt(),".config"),Lt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function e$(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||r}async function A1(i){return rt.loadConfig({...i,__strictErrorHandling:!0})}async function tw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await rt.loadConfig(i);else n=await rt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",l=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)Oi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await rt.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function E1(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await rt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&e$(r)))return(await rt.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await rt.loadConfig({...i,cwd:i.cwd||Wt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&e$(t)))return(await rt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function T1(i,t,r="replace"){let n=new Hn;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Ur(i,t,r=!1){let n=new Mn,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[y,h]of Object.entries(c)){let u=[...$,y],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let E of e)if(A=Wt.env[E],A!==void 0){m=E;break}if(A!==void 0&&m)if(typeof h==="boolean")w[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let E=Number(A);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(h))try{w[y]=JSON.parse(A)}catch{w[y]=A.split(",").map((E)=>E.trim())}else w[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))w[y]=l(h,u)}return w}return l(t)}function Y1(i){let t=Ti(Wt.cwd(),i.configDir),r=Ti(Wt.cwd(),i.generatedDir),n=Ti(r,"config-types.ts");if(!Ul(d0(n)))ne(d0(n),{recursive:!0,mode:511});let f=Ul(t)?fe(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${V1}
|
|
35
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
36
|
-
`;le(n,l,{mode:438})}function m1(i){let t=null,r=null,n=()=>{if(!r)r=tw(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)Oi.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(l,c){if(t)return t[c];let $=f[c];return n(),$},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,$){if(!t)t={...f};return t[c]=$,!0}})}function B1(i){let t=f$(We.cwd(),i?.configDir||"./config");function r(){if(!Fe(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=Xe(t).filter((w)=>f.has(wl(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),$=new Map;for(let{base:w,file:y}of c){let h=wl(y).toLowerCase(),u=$.get(w);if(!u){$.set(w,y);continue}let e=wl(u).toLowerCase();if(l.indexOf(h)<l.indexOf(e))$.set(w,y)}return Array.from($.entries()).map(([w,y])=>({base:w,file:y})).sort((w,y)=>w.base.localeCompare(y.base))}function n(){let f=r(),l=f.map((w)=>w.base),c=l.length?l.map((w)=>`'${w}'`).join(" | "):"string",$=f.length?`{
|
|
37
|
-
${f.map((w)=>{let y=f$(t,w.file).replace(/\\/g,"/");return` '${w.base}': typeof import('${y}').default`}).join(`,
|
|
38
|
-
`)}
|
|
39
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
40
|
-
export type ConfigByName = ${$}
|
|
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(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var rw,Zt,Wr,nw,C1,s1,A$,An,al,wi,d,R1,E$,U1,T$,j1,S1,Al,a1,Y$,m$,El,N1,F1,X1,W1,En,fw,J1,yi,_1,I1,B$,Tn,Nl,ii,K,K1,C$,z1,s$,O1,G1,Tl,M1,R$,U$,H1,Yl,q1,L1,g1,x1,d1,Yn,lw,k1,V1="0.15.6",Ui,Xn,Nr,Fl,Xl,Wn,Wl,Jl,Fr,_l,Il,Tt,cw,$w,Oi,rt,ww,yw,D1=De(async()=>{rw=import.meta.require,Zt=new Ll,Wr=new gl,nw={createKey:be,isEquivalent:Qe,estimateMemoryUsage:Pe},C1=Rn(jl.cwd(),"config"),s1=Rn(jl.cwd(),"src/generated"),A$=sn.env.CLARITY_LOG_DIR||we(oe(),"logs"),An={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:A$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},al=await pe(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},d=wi,R1=wi.red,E$=wi.green,U1=wi.yellow,T$=wi.blue,j1=wi.magenta,S1=wi.cyan,Al=wi.white,a1=wi.gray,Y$=wi.bgRed,m$=wi.bgYellow,El=wi.bold,N1=wi.dim,F1=wi.italic,X1=wi.underline,W1=wi.reset,En={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fw={debug:"\uD83D\uDD0D",info:T$("ℹ"),success:E$("✓"),warning:m$(Al(El(" WARN "))),error:Y$(Al(El(" ERROR ")))},J1=new an("stacks"),yi=new an("bunfig",{showTags:!0}),_1=Ei(ar.cwd(),"config"),I1=Ei(ar.cwd(),"src/generated"),B$=Cn.env.CLARITY_LOG_DIR||ce(n1(),"logs"),Tn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:B$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nl=await f1(),ii={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},K=ii,K1=ii.red,C$=ii.green,z1=ii.yellow,s$=ii.blue,O1=ii.magenta,G1=ii.cyan,Tl=ii.white,M1=ii.gray,R$=ii.bgRed,U$=ii.bgYellow,H1=ii.bgGray,Yl=ii.bold,q1=ii.dim,L1=ii.italic,g1=ii.underline,x1=ii.strikethrough,d1=ii.reset,Yn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lw={debug:"\uD83D\uDD0D",info:s$("ℹ"),success:C$("✓"),warning:U$(Tl(Yl(" WARN "))),error:R$(Tl(Yl(" ERROR ")))},k1=new Fn("stacks"),Ui=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Xn=class extends Ui{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${i}"${n} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}},Nr=class extends Ui{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Fl=class extends Ui{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}},Xl=class extends Ui{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Wn=class extends Ui{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}},Wl=class extends Ui{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Jl=class extends Ui{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Fr=class extends Ui{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}},_l=class extends Ui{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}},Il=class extends Ui{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Tt={configNotFound(i,t,r){return new Xn(i,t,r)},configLoad(i,t,r){return new Nr(i,t,r)},configValidation(i,t,r){return new Fl(i,t,r)},configMerge(i,t,r,n){return new Xl(i,t,r,n)},envVar(i,t,r,n){return new Wn(i,t,r,n)},fileSystem(i,t,r){return new Wl(i,t,r)},typeGeneration(i,t,r){return new Jl(i,t,r)},schemaValidation(i,t,r){return new Fr(i,t,r)},browserConfig(i,t,r,n){return new _l(i,t,r,n)},plugin(i,t,r){return new Il(i,t,r)}},cw={replace:"replace",concat:"concat",smart:"smart"},$w=/^https?:\/\//,Oi=new Fn("bunfig",{showTags:!0}),rt=new Dl,ww=Ti(Wt.cwd(),"config"),yw=Ti(Wt.cwd(),"src/generated")});function b1(i,t={}){let r=Un.cwd();while(r.includes("storage"))r=l$(r,"..");let n=l$(r,i||"");if(t?.relative)return _e(Un.cwd(),n);return n}var Q1=Un.env.CLARITY_LOG_DIR||Je(b1(),"logs"),hw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Q1,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jn={...hw},MC=(async()=>{try{let{loadConfig:i}=await D1().then(()=>b$),t=await i({name:"clarity",alias:"logging",defaultConfig:hw,cwd:Un.cwd()});if(t)Object.assign(Jn,t)}catch{}return Jn})();function ti(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function P1(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof it<"u"){let i=it.type;if(i==="renderer"||i==="worker")return!1;return!!(it.versions&&(it.versions.node||it.versions.bun))}return!1}class uw{async format(i){let t=await P1(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Pt.pid,hostname:t(),environment:Pt.env.NODE_ENV||"development",platform:Pt.platform,version:Pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pt.env.NODE_ENV||Pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=li,HC=li.red,v1=li.green,qC=li.yellow,Z1=li.blue,LC=li.magenta,gC=li.cyan,j$=li.white,xC=li.gray,o1=li.bgRed,p1=li.bgYellow,dC=li.bgGray,S$=li.bold,kC=li.dim,VC=li.italic,DC=li.underline,bC=li.strikethrough,QC=li.reset,ml={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},iA={debug:"\uD83D\uDD0D",info:Z1("ℹ"),success:v1("✓"),warning:p1(j$(S$(" WARN "))),error:o1(j$(S$(" 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(i,t={}){this.name=i,this.config={...Jn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...ml,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...ml};return{...ml,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Jn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await Ge(this.config.logDirectory,y$.F_OK|y$.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await Me(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:vi.from(i);try{if(!fn(this.currentLogFile))await ul(this.currentLogFile,"",{mode:420});if(n=w$(this.currentLogFile,"a",420),Oe(n,$,{flag:"a"}),$$(n),n!==void 0)hl(n),n=void 0;if((await bt(this.currentLogFile)).size===0){if(await ul(this.currentLogFile,$,{flag:"w",mode:420}),(await bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let y=w;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(f<l-1){let h=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,h);let u=c*2**f;await new Promise((e)=>setTimeout(e,u)),f++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(n!==void 0)try{hl(n)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch($){if(f===l-1){let y=$,h=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),$}f++;let w=c*2**(f-1);await new Promise((y)=>setTimeout(y,w))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Qt(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 Qt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Qt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return yl(16).toString("hex")}generateKey(){return yl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=yl(16),n=Ie("aes-256-gcm",t,r),f=vi.isBuffer(i)?i:vi.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,w=n.getAuthTag(),y=vi.allocUnsafe(16+$+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),w.copy(y,16+$),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=u$(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(vi.from(vi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ln(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await bt(r).catch(()=>null))try{if(await h$(r,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await cn($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await ul(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await bt(r).catch(()=>null))await h$(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await ln(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await cn(Qt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=c$(i),n=ze(t),f=u$();await Le(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),fn(this.currentLogFile))try{let i=w$(this.currentLogFile,"r+");$$(i),hl(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await ln(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await cn(Qt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=q.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${O.cyan(f)}`;if(!c)return y.trim();let h=$(y).trim().length,u=$(t).length,e=Math.max(1,w-2-h-u);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=O.underline(O.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>O.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>O.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>O.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>O.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>O.strikethrough(n)),t}supportsHyperlinks(){if(ti())return!1;let i=q.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=q.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(He(t)||t.startsWith("./")||t.startsWith("../"))t=qe(t);else return null;return fn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":iA[i],e=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:O.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:O.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let m=$.split(`
|
|
44
|
-
`);for(let E of m)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
45
|
-
`;if($)h+=`${$}
|
|
46
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!ti()&&q.stdout.isTTY)q.stdout.write(`
|
|
47
|
-
`);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:r,message:`${O.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)w+=` ${JSON.stringify(r)}`;if(w+=`
|
|
48
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":O.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ti())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new qn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!fn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return c$(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=vi.isBuffer(i)?i:vi.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=Ke("aes-256-gcm",r,f);$.setAuthTag(l);let w=$.update(c),y=$.final(),h=w.length+y.length,u=vi.allocUnsafe(h);return w.copy(u,0),y.copy(u,w.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ti()}isServerMode(){return!ti()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
49
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,y=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:O.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(y),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(h),showTimestamp:!1}))}else if(!ti())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();q.stdin.removeListener("data",r);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(r=i.replace(c,(w,y)=>{if(y==="%")return"%";if($>=t.length)return w;let h=t[$++];switch(y){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),$<t.length)r+=` ${t.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${$}${c} ${O.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=O.green("━".repeat(n)),c=O.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?O.green("✓"):O.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",e=`\r${h}${u} ${$} ${w}${y}`,A=q.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
|
|
52
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!q.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ln(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Qt(this.config.logDirectory,n);if(i.before)try{if((await bt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);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 cn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var PC=new qn("stacks");class Hi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class ew extends Hi{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class _n extends Hi{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Aw extends Hi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Ew extends Hi{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class bl extends Hi{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class Tw extends Hi{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Yw extends Hi{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class In extends Hi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class mw extends Hi{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class Bw extends Hi{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var ot={configNotFound(i,t,r){return new ew(i,t,r)},configLoad(i,t,r){return new _n(i,t,r)},configValidation(i,t,r){return new Aw(i,t,r)},configMerge(i,t,r,n){return new Ew(i,t,r,n)},envVar(i,t,r,n){return new bl(i,t,r,n)},fileSystem(i,t,r){return new Tw(i,t,r)},typeGeneration(i,t,r){return new Yw(i,t,r)},schemaValidation(i,t,r){return new In(i,t,r)},browserConfig(i,t,r,n){return new mw(i,t,r,n)},plugin(i,t,r){return new Bw(i,t,r)}};async function tA(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class Ql{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return ql.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${$.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=$n.env[w]||(y?$n.env[y]:void 0);if(h!==void 0){if(n.verbose){let u=$n.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,w,n.customParsers,n.configName)}catch(u){if(u instanceof bl)throw u;throw ot.envVar(w,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw ot.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries($n.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
53
|
-
|
|
54
|
-
`;for(let n of i)r+=`${n.key}
|
|
55
|
-
`,r+=` Type: ${n.type}
|
|
56
|
-
`,r+=` Description: ${n.description}
|
|
57
|
-
`,r+=` Example: ${n.example}
|
|
58
|
-
|
|
59
|
-
`;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
|
|
60
|
-
|
|
61
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
62
|
-
`,r+=`|----------|------|-------------|----------|
|
|
63
|
-
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
64
|
-
`;return r}}function rA(i,t,r={}){return Cw(i,t,r,new WeakMap)}function Cw(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return sw(i,t,f,n);if(!Wi(t)||!Wi(i))return t;return cA(i,t,r,n)}function sw(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return nA(i,t);case"smart":return fA(i,t,n);default:return t}return t}function nA(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Kl(f,n)))r.push(n);return r}function fA(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Wi(t[0])&&Wi(i[0]))return lA(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function lA(i,t,r){let n=[...t];for(let f of i){if(!Wi(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((w)=>Wi(w)&&($ in w)&&w[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function cA(i,t,r,n){let f=t;if(Wi(f)&&n.has(f))return n.get(f);let l={...i};if(Wi(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Wi($)&&Wi(w))l[c]=Cw(w,$,r,n);else if(Array.isArray($)||Array.isArray(w))l[c]=sw(w,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function Rw(i,t,r="replace"){return rA(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Kl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Kl(i[r],t[r]))return!1;return!0}if(Wi(i)&&Wi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Kl(i[f],t[f]))return!1}return!0}return!1}function Wi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Uw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let y=jn.getWithFileCheck("file",i);if(y){if($)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!wn(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),u=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new _n(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new _n(i,Error("Configuration must export a valid object"),"unknown");let m={config:Rw(t,u,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)jn.setWithFileCheck("file",m,i,l);return m}catch(y){throw y instanceof Error?ot.configLoad(i,y):ot.configLoad(i,Error(String(y)))}};if(c)return ql.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(el(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of n){if(!l)continue;if(r.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)r.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return r.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return tA(async()=>{return wn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!wn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=el(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=el(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!wn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var $A=/^https?:\/\//;class jw{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=r,y=async()=>{let h=[],u=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:u}}};if($)return await ql.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!ge(t))throw new In(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new In(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let y=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:$A},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Zi=new qn("bunfig",{showTags:!0});function wA(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Sw{fileLoader=new Uw;envProcessor=new Ql;validator=new jw;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw w;if(u&&(!y||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)Zi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){if($ instanceof Error&&$.name==="ConfigNotFoundError")throw $;let w=Date.now()-t;throw Zi.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:y="replace",verbose:h=!1}=i,u=l||Gn.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,u,c,$,y,h,w,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,u,c)),this.finalizeResult(A,e,w,n,h);let m=await this.loadHomeConfiguration(n,f,$,y,h,w);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,u,$,y,h,w);if(E)return e.push(Fi(u,"package.json")),this.finalizeResult(E,e,w,n,h);if(e.push(...this.getAllSearchPaths(n,f,u,c)),t)throw ot.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,w,h),warnings:[`No configuration file found for "${n}"${wA(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,w){let y=$?hn(i,f,c):f,h=this.getLocalDirectories(r,n);for(let u of h){if(c)Zi.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)Zi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?hn(i,r,f):r,$=[Fi(qt(),".config",i),Fi(qt(),".config"),qt()];for(let w of $){if(f)Zi.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)Zi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?hn(i,n,l):n;try{let w=Fi(r,"package.json");if(!te(w))return null;let y={};try{y=JSON.parse(re(w,"utf8"))}catch(e){if(l)Zi.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let h=y[i],u=i;if(!h&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(y[A]){h=y[A],u=A;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)Zi.success(`Configuration loaded from package.json: ${u}`);return{config:Rw($,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)Zi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:hn(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw ot.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return jn.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);jn.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Fi(i,"config"),Fi(i,".config"),t?Fi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Fi(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Fi(qt(),".config",i),Fi(qt(),".config"),qt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var vC=new Sw;function hn(i,t,r=!1){let n=new Ql,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[y,h]of Object.entries(c)){let u=[...$,y],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let E of e)if(A=Gn.env[E],A!==void 0){m=E;break}if(A!==void 0&&m)if(typeof h==="boolean")w[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let E=Number(A);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(h))try{w[y]=JSON.parse(A)}catch{w[y]=A.split(",").map((E)=>E.trim())}else w[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))w[y]=l(h,u)}return w}return l(t)}var ZC=Fi(Gn.cwd(),"config"),oC=Fi(Gn.cwd(),"src/generated"),aw={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:of.join(Zf.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:of.join(Zf.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:of.join(Zf.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},Z=aw,Gi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},vt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function Fw(i){return zl.readFileSync(i,"utf8")}function Ol(i,t){let r=[];function n(f){let l;try{l=zl.readdirSync(f)}catch{return}for(let c of l){let $=zi.join(f,c);try{if(zl.statSync($).isDirectory())n($);else if(c===t)r.push(f)}catch{continue}}}return n(i),r}function U(i,t,r){if(r||Z.verbose)console.debug(`[tlsx:${i}] ${t}`)}var eA=uA(yA);function Xw(){return Nw.env.SUDO_PASSWORD}var a$="[redacted]",AA=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),EA=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function TA(i){let t=i.toLowerCase();return AA.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Kn(i){if(Array.isArray(i))return i.map((r)=>Kn(r));if(typeof i==="string")return EA.test(i)?a$:i;if(!i||typeof i!=="object")return i;let t={};for(let[r,n]of Object.entries(i)){if(TA(r)){t[r]=a$;continue}t[r]=Kn(n)}return t}function Ln(i){return JSON.stringify(Kn(i))}function YA(i){let t=Xw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let r=t.replace(/'/g,"'\\''"),n=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function Et(i,t={}){let r=YA(i);try{let{stdout:n,stderr:f}=await eA(r,{cwd:t.cwd||Nw.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:f.trim()}}catch(n){let f=Error(`Failed to execute command: ${i}
|
|
65
|
-
Error: ${n.message}`);throw f.stack=n.stack,f}}function Ww(i){if(i.domain)return i.domain;if(i.domains?.length)return i.domains[0];throw Error("Either domain or domains must be specified")}function Pl(i){let t=zi.join(hA.homedir(),".stacks","ssl"),r=i.basePath&&i.basePath.trim()!==""?i.basePath:Z.basePath&&Z.basePath.trim()!==""?Z.basePath:t,n=i.certPath?zi.isAbsolute(i.certPath)?i.certPath:zi.join(r,i.certPath):zi.join(r,Z.certPath),f=i.keyPath?zi.isAbsolute(i.keyPath)?i.keyPath:zi.join(r,i.keyPath):zi.join(r,Z.keyPath),l=i.caCertPath?zi.isAbsolute(i.caCertPath)?i.caCertPath:zi.join(r,i.caCertPath):zi.join(r,Z.caCertPath);return{certPath:n,keyPath:f,caCertPath:l,basePath:r}}function Jw(i){let t=[],r=new Set;if(i.domain)r.add(i.domain);if(i.domains?.length)i.domains.forEach((n)=>r.add(n));for(let n of r)t.push({type:2,value:n});if(i.altNameIPs?.length)for(let n of i.altNameIPs)t.push({type:7,ip:n});if(i.altNameURIs?.length)for(let n of i.altNameURIs)t.push({type:6,value:n});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return U(S.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function vl(i){let t=i.notBeforeDays??Gi.DEFAULT_NOT_BEFORE_DAYS,r=i.validityDays??(i.validityYears?i.validityYears*365:Gi.DEFAULT_VALIDITY_DAYS);U(S.CERT,"Calculating certificate validity dates",i.verbose);let n=new Date(Date.now()-86400*t*1000),f=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),U(S.CERT,`Validity period: ${n.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:n,notAfter:f}}var Mi={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},Yi={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 jr(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Si(i,t){let r=jr(t.length);return Buffer.concat([Buffer.from([i]),r,t])}function Xr(i){let t=i.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let f=t[n],l=[];l.unshift(f&127),f>>=7;while(f>0)l.unshift(f&127|128),f>>=7;r.push(...l)}return Si(Mi.OID,Buffer.from(r))}function Gl(i){let t;if(typeof i==="bigint"){let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Si(Mi.INTEGER,t)}function _w(i,t=0){return Si(Mi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Iw(i){return Si(Mi.OCTET_STRING,i)}function ji(...i){return Si(Mi.SEQUENCE,Buffer.concat(i))}function mA(...i){return Si(Mi.SET,Buffer.concat(i))}function BA(i){return Si(Mi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function CA(i){return Si(Mi.UTF8_STRING,Buffer.from(i,"utf8"))}function sA(){return Buffer.from([Mi.NULL,0])}function N$(i,t,r=!0){let n=160|i|(r?0:0),f=jr(t.length);return Buffer.concat([Buffer.from([n]),f,t])}function F$(i){let t=i.getUTCFullYear();if(t>=2050){let r=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Si(Mi.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),n=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),c=i.getUTCMinutes().toString().padStart(2,"0"),$=i.getUTCSeconds().toString().padStart(2,"0"),w=`${r}${n}${f}${l}${c}${$}Z`;return Si(Mi.UTC_TIME,Buffer.from(w,"ascii"))}}function RA(i,t){return ji(F$(i),F$(t))}function X$(i){let t=[];for(let r of i){let n;switch(r.shortName){case"CN":n=Yi.COMMON_NAME;break;case"C":n=Yi.COUNTRY;break;case"L":n=Yi.LOCALITY;break;case"ST":n=Yi.STATE;break;case"O":n=Yi.ORGANIZATION;break;case"OU":n=Yi.ORGANIZATIONAL_UNIT;break;default:continue}let f=r.shortName==="C"?BA(r.value):CA(r.value),l=ji(Xr(n),f);t.push(mA(l))}return ji(...t)}function Kw(i){return ji(Xr(i),sA())}function UA(i){return i.export({type:"spki",format:"der"})}function jA(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),l=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],$=8-l.length-c.length,w=Array.from({length:$},()=>"0");t=[...l,...w,...c].join(":")}let r=t.split(":"),n=Buffer.alloc(16);for(let f=0;f<8;f++){let l=Number.parseInt(r[f]||"0",16);n.writeUInt16BE(l,f*2)}return n}else{let t=i.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function SA(i){let t=[];for(let r of i)if(r.type===2&&r.value){let n=jr(r.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=jA(r.ip),f=jr(n.length);t.push(Buffer.concat([Buffer.from([135]),f,n]))}else if(r.type===6&&r.value){let n=jr(r.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return ji(...t)}function aA(i,t){if(i){if(t!==void 0)return ji(Si(1,Buffer.from([255])),Gl(t));return ji(Si(1,Buffer.from([255])))}return ji()}function NA(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let r=0,n=t;while(n>0&&(n&1)===0)r++,n>>=1;if(t===0)r=7;return _w(Buffer.from([t]),r)}function FA(i){let t=[];if(i.serverAuth)t.push(Xr(Yi.SERVER_AUTH));if(i.clientAuth)t.push(Xr(Yi.CLIENT_AUTH));return ji(...t)}function Rr(i,t,r){let n=[Xr(i)];if(t)n.push(Si(1,Buffer.from([255])));return n.push(Iw(r)),ji(...n)}function XA(i){let t=[];if(t.push(N$(0,Gl(2))),t.push(Gl(i.serialNumber)),t.push(Kw(Yi.SHA256_WITH_RSA)),t.push(X$(i.issuer)),t.push(RA(i.notBefore,i.notAfter)),t.push(X$(i.subject)),t.push(UA(i.publicKey)),i.extensions){let r=[];if(i.extensions.basicConstraints)r.push(Rr(Yi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,aA(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)r.push(Rr(Yi.KEY_USAGE,i.extensions.keyUsage.critical??!0,NA(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)r.push(Rr(Yi.EXTENDED_KEY_USAGE,!1,FA(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)r.push(Rr(Yi.SUBJECT_ALT_NAME,!1,SA(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)r.push(Rr(Yi.SUBJECT_KEY_IDENTIFIER,!1,Iw(i.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(N$(3,ji(...r)))}return ji(...t)}function WA(i,t){let r=pt.createSign("SHA256");r.update(i);let n=r.sign(t);return ji(i,Kw(Yi.SHA256_WITH_RSA),_w(n))}function JA(i,t){let r=i.toString("base64"),n=[];for(let f=0;f<r.length;f+=64)n.push(r.slice(f,f+64));return`-----BEGIN ${t}-----
|
|
66
|
-
${n.join(`
|
|
67
|
-
`)}
|
|
68
|
-
-----END ${t}-----
|
|
69
|
-
`}function Zl(){let i=pt.randomBytes(20);return i[0]=i[0]&127||1,i}function zw(i=2048){let{privateKey:t,publicKey:r}=pt.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:r}}function _A(i){let t=i.export({type:"spki",format:"der"});return pt.createHash("sha1").update(t).digest()}function Ow(i){let t={serialNumber:i.serialNumber||Zl(),notBefore:i.notBefore,notAfter:i.notAfter,subject:i.subject,issuer:i.issuer||i.subject,publicKey:i.publicKey,extensions:{basicConstraints:{isCA:i.isCA??!1,critical:!0,pathLenConstraint:i.pathLenConstraint},subjectKeyIdentifier:_A(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let r=XA(t),n=WA(r,i.signingKey);return{certificate:JA(n,"CERTIFICATE"),certificateDer:n}}function Gw(i){return i.export({type:"pkcs8",format:"pem"})}function IA(i){return pt.createPrivateKey(i)}function KA(i){let t=new pt.X509Certificate(i),r=t.publicKey,n=[],f=t.subject.split(`
|
|
70
|
-
`);for(let l of f){let[c,...$]=l.split("="),w=$.join("=");if(c&&w)n.push({shortName:c.trim(),value:w.trim()})}return{publicKey:r,subject:n}}async function ol(i={}){U("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Gi.DEFAULT_KEY_SIZE;U("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:r,publicKey:n}=zw(t),f=[{shortName:"C",value:i.countryName||Z.countryName},{shortName:"ST",value:i.stateName||Z.stateName},{shortName:"L",value:i.localityName||Z.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:l,notAfter:c}=vl({validityYears:i.validityYears||Gi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:$}=Ow({serialNumber:Zl(),notBefore:l,notAfter:c,subject:f,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:$,privateKey:Gw(r),notBefore:l,notAfter:c}}async function pl(i){if(U("ca","Generating new certificate",i.verbose),U("ca",`Options: ${Ln(i)}`,i.verbose),!i.domain&&!i.domains?.length)throw Error("Either domain or domains must be specified");if(!i.rootCA?.certificate||!i.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=KA(i.rootCA.certificate),r=IA(i.rootCA.privateKey);U("ca",`Generating ${Gi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let n=Gi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:l}=zw(n),c=i.commonName||Ww(i),$=i.certificateAttributes||[{shortName:"C",value:i.countryName||Z.countryName},{shortName:"ST",value:i.stateName||Z.stateName},{shortName:"L",value:i.localityName||Z.localityName},{shortName:"O",value:i.organizationName||Z.organizationName},{shortName:"CN",value:c}],{notBefore:w,notAfter:y}=vl({validityDays:i.validityDays||Gi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=Jw(i),u=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},e=i.extKeyUsage||{serverAuth:!0},{certificate:A}=Ow({serialNumber:Zl(),notBefore:w,notAfter:y,subject:$,issuer:t,publicKey:l,signingKey:r,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:e,subjectAltName:h});return{certificate:A,privateKey:Gw(f),notBefore:w,notAfter:y}}function Mw(i,t){U(S.STORAGE,`Storing certificate and private key with options: ${Ln(t)}`,t?.verbose);let{certPath:r,keyPath:n}=Pl({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});U(S.STORAGE,`Certificate path: ${r}`,t?.verbose),U(S.STORAGE,`Private key path: ${n}`,t?.verbose);let f=Ml.dirname(r);if(!tt.existsSync(f))U(S.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),tt.mkdirSync(f,{recursive:!0});U(S.STORAGE,"Writing certificate file",t?.verbose),tt.writeFileSync(r,i.certificate);let l=Ml.dirname(n);if(!tt.existsSync(l))U(S.STORAGE,`Creating private key directory: ${l}`,t?.verbose),tt.mkdirSync(l,{recursive:!0});return U(S.STORAGE,"Writing private key file",t?.verbose),tt.writeFileSync(n,i.privateKey),U(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function Hw(i,t){U(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=Pl({basePath:t?.basePath,caCertPath:t?.caCertPath});U(S.STORAGE,`CA certificate path: ${r}`,t?.verbose);let n=Ml.dirname(r);if(!tt.existsSync(n))U(S.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),tt.mkdirSync(n,{recursive:!0});return U(S.STORAGE,"Writing CA certificate file",t?.verbose),tt.writeFileSync(r,i),U(S.STORAGE,"CA certificate stored successfully",t?.verbose),r}function gn(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=Fw(i);return new zA.X509Certificate(t)}function xn(i){return gn(i).fingerprint256.replace(/:/g,"").toUpperCase()}function ic(i){return qw(gn(i).subject)}function tc(i,t,r=443,n=4000){let f;try{f=t.includes("-----BEGIN")?t:OA.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((l)=>{let c=!1,$=(y)=>{if(c)return;c=!0,l(y)},w=GA.connect({host:i,port:r,servername:i,ca:f,rejectUnauthorized:!0},()=>{$(w.authorized),w.end()});w.setTimeout(n,()=>{w.destroy(),$(!1)}),w.on("error",()=>$(!1))})}function MA(i){let t=[],r=i.split(`
|
|
71
|
-
`);for(let n of r){let[f,...l]=n.split("="),c=l.join("=");if(f&&c)t.push({shortName:f.trim(),value:c.trim()})}return t}function qw(i){return MA(i).find((t)=>t.shortName==="CN")?.value||""}function HA(i){let t=[],r=qw(i.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let n=i.subjectAltName;if(n){let f=n.split(", ");for(let l of f)if(l.startsWith("DNS:"))t.push(l.slice(4))}return[...new Set(t)]}function rc(i,t){let r=gn(i),n=HA(r);for(let f of n){if(f===t)return!0;if(f.startsWith("*.")){let l=f.slice(2);if(t.endsWith(l)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function LA(i,t){if(zn.platform()!=="darwin")return!1;try{let r=xn(i);if(!r)return U(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(qA("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
72
|
-
`).some((n)=>{let f=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===r}))return U(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return U(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return U(S.TRUST,`Error checking certificate trust: ${r}`,t),!1}}var gA={platform:"darwin",async addCertificate(i,t){if(await LA(i,t?.verbose)){U(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),vt.success("Certificate is already trusted in system keychain");return}U(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await Et(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,r){let n=r||Z.commonName;U(S.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await Et(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),U(S.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},xA={platform:"win32",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await Et(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,r){let n=r||Z.commonName;U(S.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await Et(`certutil -delstore -enterprise Root "${n}"`),U(S.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},dA={platform:"linux",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=zn.homedir(),n=Gi.LINUX_CERT_DB_FILENAME,f=Gi.LINUX_TRUST_ARGS;U(S.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let l=Ol(r,n);if(l.length===0){vt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of l){U(S.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{U(S.TRUST,`Attempting to delete existing cert for ${Z.commonName}`,t?.verbose),await Et(`certutil -d sql:${c} -D -n ${Z.commonName}`)}catch($){U(S.TRUST,`Warning: Error deleting existing cert: ${$}`,t?.verbose),console.warn(`Error deleting existing cert: ${$}`)}U(S.TRUST,`Adding new certificate to ${c}`,t?.verbose),await Et(`certutil -d sql:${c} -A -t ${f} -n ${Z.commonName} -i ${i}`),vt.info(`Cert added to ${c}`)}},async removeCertificate(i,t,r){let n=r||Z.commonName;U(S.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let f=zn.homedir(),l=Gi.LINUX_CERT_DB_FILENAME;U(S.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let c=Ol(f,l);if(c.length===0){vt.warn("No certificate databases found. Cannot remove certificate.");return}for(let $ of c){U(S.TRUST,`Processing certificate database in ${$}`,t?.verbose);try{await Et(`certutil -d sql:${$} -D -n "${n}"`),vt.info(`Cert removed from ${$}`)}catch(w){U(S.TRUST,`Error removing cert from ${$}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${$}: ${w}`)}}}},kA={darwin:gA,win32:xA,linux:dA};async function nc(i,t,r){U(S.TRUST,`Adding certificate to system trust store with options: ${Ln(r)}`,r?.verbose),U(S.TRUST,"Storing certificate and private key",r?.verbose);let n=Mw(i,r);U(S.TRUST,"Storing CA certificate",r?.verbose);let f=Hw(t,r),l=zn.platform();U(S.TRUST,`Detected platform: ${l}`,r?.verbose);let c=kA[l];if(!c){let $=`Unsupported platform: ${l}`;throw U(S.TRUST,`Error: ${$}`,r?.verbose),Error($)}return await c.addCertificate(f,r),U(S.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as Vc}from"node:os";import{join as Dc,resolve as OU}from"node:path";import{existsSync as Lw,statSync as gw}from"fs";import{existsSync as VA,mkdirSync as Ps,readdirSync as vs,readFileSync as DA,writeFileSync as Zs}from"fs";import{homedir as ir}from"os";import{dirname as iR,resolve as Ji}from"path";import jf from"process";import{existsSync as xw,statSync as dw}from"fs";import{existsSync as jc,mkdirSync as bA,readdirSync as QA,writeFileSync as PA}from"fs";import{homedir as tr}from"os";import{dirname as kw,resolve as Bi}from"path";import Jt from"process";import{join as vA,relative as ZA,resolve as Vw}from"path";import hf from"process";import{existsSync as Xy,mkdirSync as hR,readdirSync as uR,writeFileSync as eR}from"fs";import{homedir as fc}from"os";import{dirname as TR,resolve as mi}from"path";import _r from"process";import{join as oA,relative as pA,resolve as Dw}from"path";import uf from"process";import{existsSync as Wy,mkdirSync as sR,readdirSync as RR,writeFileSync as UR}from"fs";import{dirname as SR,resolve as ef}from"path";import Sc from"process";import{Buffer as mt}from"buffer";import{createCipheriv as iE,createDecipheriv as tE,randomBytes as lc}from"crypto";import{closeSync as cc,createReadStream as bw,createWriteStream as rE,existsSync as $c,fsyncSync as Qw,openSync as Pw,writeFileSync as nE}from"fs";import{access as fE,constants as vw,mkdir as lE,readdir as dn,rename as Zw,stat as rr,unlink as kn,writeFile as wc}from"fs/promises";import{join as nr}from"path";import hi from"process";import{pipeline as cE}from"stream/promises";import{createGzip as ow}from"zlib";import fr from"process";import ct from"process";import{Buffer as nt}from"buffer";import{createCipheriv as $E,createDecipheriv as wE,randomBytes as yc}from"crypto";import{closeSync as hc,createReadStream as pw,createWriteStream as yE,existsSync as Vn,fsyncSync as iy,openSync as ty,writeFileSync as hE}from"fs";import{access as uE,constants as ry,mkdir as eE,readdir as Dn,rename as ny,stat as lr,unlink as bn,writeFile as uc}from"fs/promises";import{isAbsolute as AE,join as cr,resolve as EE}from"path";import _ from"process";import{pipeline as TE}from"stream/promises";import{createGzip as fy}from"zlib";import $r from"process";import $t from"process";import Qn from"process";import{existsSync as Pn}from"fs";import{resolve as ec}from"path";import{existsSync as YE}from"fs";import{existsSync as mE,readdirSync as BE}from"fs";import{extname as Ac,resolve as ly}from"path";import CE from"process";import{join as sE,relative as RE,resolve as cy}from"path";import Af from"process";import{Buffer as ft}from"buffer";import{createCipheriv as UE,createDecipheriv as jE,randomBytes as Ec}from"crypto";import{closeSync as Tc,createReadStream as $y,createWriteStream as SE,existsSync as vn,fsyncSync as wy,openSync as yy,writeFileSync as aE}from"fs";import{access as NE,constants as hy,mkdir as FE,readdir as Zn,rename as uy,stat as wr,unlink as on,writeFile as Yc}from"fs/promises";import{isAbsolute as XE,join as yr,resolve as WE}from"path";import I from"process";import{pipeline as JE}from"stream/promises";import{createGzip as ey}from"zlib";import hr from"process";import wt from"process";import tf from"process";import{existsSync as rf}from"fs";import{resolve as Uc}from"path";import{existsSync as vT}from"fs";class Ny{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!Lw(i))return!0;return gw(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=Lw(r)?gw(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Fy{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var yf=new Ny,Oc=new Fy;var _E=Object.defineProperty,IE=(i)=>i;function KE(i,t){this[i]=IE.bind(null,t)}var zE=(i,t)=>{for(var r in t)_E(i,r,{get:t[r],enumerable:!0,configurable:!0,set:KE.bind(t,r)})},OE=(i,t)=>()=>(i&&(t=i(i=0)),t),Jy={};zE(Jy,{withErrorRecovery:()=>Ky,tryLoadConfig:()=>fT,loadConfigWithResult:()=>rT,loadConfig:()=>Hy,isRetryableError:()=>vE,isConfigNotFoundError:()=>PE,isBunfigError:()=>zy,globalPerformanceMonitor:()=>zr,globalCache:()=>ur,getEnvOrDefault:()=>ZE,generateConfigTypes:()=>lT,defaultGeneratedDir:()=>Dy,defaultConfigDir:()=>Vy,deepMergeWithArrayStrategy:()=>Lc,deepMerge:()=>Oy,createLibraryConfig:()=>cT,config:()=>nT,bunfigPlugin:()=>$T,applyEnvVarsToConfig:()=>Jr,TypeGenerationError:()=>_c,SchemaValidationError:()=>Kr,PluginError:()=>Kc,PerformanceMonitor:()=>Mc,FileSystemError:()=>Jc,ErrorFactory:()=>Bt,EnvVarError:()=>Cf,EnvProcessor:()=>Sf,ConfigValidator:()=>gc,ConfigValidationError:()=>Xc,ConfigNotFoundError:()=>Bf,ConfigMergeError:()=>Wc,ConfigLoader:()=>xc,ConfigLoadError:()=>Ir,ConfigFileLoader:()=>af,ConfigCache:()=>Gc,CacheUtils:()=>Ly,BunfigError:()=>ai,BrowserConfigError:()=>Ic,ArrayMergeStrategies:()=>dy});class Gc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(i,t){try{if(!xw(i))return!0;return dw(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=xw(r)?dw(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Mc{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function GE(i,t={}){let n=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return n?`${i}:${n}`:i}function ME(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function HE(i){return i.getStats().size*2}function Hc(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&D(t[0])&&"id"in t[0]&&t[0].id===3&&D(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(D(t)&&D(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(D(i)&&"arr"in i&&Array.isArray(i.arr)&&D(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&D(t[0])&&D(i[0])){let n=[...t];for(let f of i)if(D(f)&&"name"in f){if(!n.find((c)=>D(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(D(f)&&"path"in f){if(!n.find((c)=>D(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((l)=>Ef(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!D(t)||!D(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(D(f)&&D(r[n]))r[n]=Hc(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&D(f[0])&&D(r[n][0])){let l=[...f];for(let c of r[n])if(D(c)&&"name"in c){if(!l.find((w)=>D(w)&&("name"in w)&&w.name===c.name))l.push(c)}else if(D(c)&&"path"in c){if(!l.find((w)=>D(w)&&("path"in w)&&w.path===c.path))l.push(c)}else if(!l.some(($)=>Ef($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Ef(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Ef(i[r],t[r]))return!1;return!0}if(D(i)&&D(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Ef(i[f],t[f]))return!1}return!0}return!1}function D(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function qE(i,t){if(!Wy(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Hc(t,n)}catch{return null}}catch{return null}}async function LE({name:i="",cwd:t,defaultConfig:r}){let n=t||Sc.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let $ of f){let w=ef(n,`${c}${$}`),y=await qE(w,r);if(y!==null)return y}try{let c=ef(n,"package.json");if(Wy(c)){let w=(await import(c))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Hc(r,w)}catch{}}}catch{}return r}function gE(i,t={}){let r=uf.cwd();while(r.includes("storage"))r=Dw(r,"..");let n=Dw(r,i||"");if(t?.relative)return pA(uf.cwd(),n);return n}async function xE(){try{let i=await LE({name:"clarity",defaultConfig:lf,cwd:uf.cwd(),endpoint:"",headers:{}});return{...lf,...i}}catch{return lf}}function P(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function dE(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ct<"u"){let i=ct.type;if(i==="renderer"||i==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class _y{async format(i){let t=await dE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:fr.pid,hostname:t(),environment:fr.env.NODE_ENV||"development",platform:fr.platform,version:fr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fr.env.NODE_ENV||fr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Tf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Nc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new _y,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??hi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...cf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...cf};return{...cf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Nc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await fE(this.config.logDirectory,vw.F_OK|vw.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await lE(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:mt.from(i);try{if(!$c(this.currentLogFile))await wc(this.currentLogFile,"",{mode:420});if(f=Pw(this.currentLogFile,"a",420),nE(f,w,{flag:"a"}),Qw(f),f!==void 0)cc(f),f=void 0;if((await rr(this.currentLogFile)).size===0){if(await wc(this.currentLogFile,w,{flag:"w",mode:420}),(await rr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let h=y;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(l<c-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,u);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{cc(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(l===c-1){let h=w,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),w}l++;let y=$*2**(l-1);await new Promise((h)=>setTimeout(h,y))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return nr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return nr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,w])=>w.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return lc(16).toString("hex")}generateKey(){return lc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=lc(16),n=iE("aes-256-gcm",t,r),f=mt.concat([n.update(i,"utf8"),n.final()]),l=n.getAuthTag();return{encrypted:mt.concat([r,f,l]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=ow(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(mt.from(mt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await rr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await dn(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await rr(r).catch(()=>null))try{if(await Zw(r,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await kn($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await wc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await rr(r).catch(()=>null))await Zw(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await dn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await kn(nr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=bw(i),n=rE(t),f=ow();await cE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),$c(this.currentLogFile))try{let i=Pw(this.currentLogFile,"r+");Qw(i),cc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await dn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await kn(nr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=hi.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${k.cyan(f)}`;if(!c)return y.trim();let h=$(y).trim().length,u=$(t).length,e=Math.max(1,w-2-h-u);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);if(this.fancy&&!P()){let y=gy[i],h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",u;switch(i){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:k.gray(c),level:i}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:k.green(c),level:i}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(u),$){let e=$.split(`
|
|
73
|
-
`);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:k.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let w=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
|
|
74
|
-
`;if($)w+=`${$}
|
|
75
|
-
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!P()){let r=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:k.blue("◐"),tag:r,message:`${k.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
|
|
76
|
-
`,y=y.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:k.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(y.trim());await this.writeToFile(y)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Tf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!$c(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bw(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=mt.isBuffer(i)?i:mt.from(i,"base64"),f=n.slice(0,16),l=n.slice(-16),c=n.slice(16,-16),$=tE("aes-256-gcm",r,f);return $.setAuthTag(l),mt.concat([$.update(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 P()}isServerMode(){return!P()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!P()){let l=i.split(`
|
|
77
|
-
`),c=Math.max(...l.map((h)=>h.length))+2,$=`┌${"─".repeat(c)}┐`,w=`└${"─".repeat(c)}┘`,y=l.map((h)=>{let u=" ".repeat(c-h.length-2);return`│ ${h}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:k.cyan($)})),y.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:k.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:k.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
|
|
78
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${k.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();hi.stdin.removeListener("data",r);try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!1)}catch{}hi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!0)}catch{}hi.stdin.resume(),hi.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(r=i.replace(c,(w,y)=>{if(y==="%")return"%";if($>=t.length)return w;let h=t[$++];switch(y){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),$<t.length)r+=` ${t.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}if(this.fancy&&!P()){let c=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$=k.blue("◐");console.error(`${$} ${c} ${k.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
79
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(l)}progress(i,t=""){if(!this.enabled||!this.fancy||P()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,$)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,c)),$!==void 0)this.activeProgressBar.message=$;let w=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,w)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,$="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;hi.stdout.write(`${"\r".padEnd(hi.stdout.columns||80)}\r`),this.log($,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!hi.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=k.green("━".repeat(n)),c=k.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=t||r===100?k.green("✓"):k.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",e=`\r${h}${u} ${$} ${w}${y}`,A=hi.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,hi.stdout.write(i.lastRenderedLine),t)hi.stdout.write(`
|
|
80
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!hi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await dn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=nr(this.config.logDirectory,n);if(i.before)try{if((await rr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}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 kn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ff(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(x(i)&&"arr"in i&&Array.isArray(i.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&x(t[0])&&x(i[0])){let n=[...t];for(let f of i)if(x(f)&&"name"in f){if(!n.find((c)=>x(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(x(f)&&"path"in f){if(!n.find((c)=>x(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((l)=>Yf(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!x(t)||!x(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(x(f)&&x(r[n]))r[n]=ff(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&x(f[0])&&x(r[n][0])){let l=[...f];for(let c of r[n])if(x(c)&&"name"in c){if(!l.find((w)=>x(w)&&("name"in w)&&w.name===c.name))l.push(c)}else if(x(c)&&"path"in c){if(!l.find((w)=>x(w)&&("path"in w)&&w.path===c.path))l.push(c)}else if(!l.some(($)=>Yf($,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function qc(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:ff(i,t);if(Array.isArray(i))return r==="replace"?t:ff(i,t);if(!x(t)||!x(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=n[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(r==="replace")n[f]=l;else n[f]=ff(c,l);else if(x(l)&&x(c))n[f]=qc(c,l,r);else n[f]=l}return n}function Yf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Yf(i[r],t[r]))return!1;return!0}if(x(i)&&x(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Yf(i[f],t[f]))return!1}return!0}return!1}function x(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function pn(i,t,r="replace"){if(!Xy(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return qc(t,f,r)}catch{return null}}catch{return null}}function kE(i,t,r=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,$=[]){let w={...c};for(let[y,h]of Object.entries(c)){let u=[...$,y],e=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${n}_${u.map(e).join("_")}`,m=`${n}_${u.map((E)=>E.toUpperCase()).join("_")}`;if(r)ei.info(`Checking environment variable ${A} for config ${i}.${u.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[y]=l(h,u);else{let E=_r.env[A]||_r.env[m];if(E!==void 0){if(r)ei.info(`Using environment variable ${E?A:m} for config ${i}.${u.join(".")}`);if(typeof h==="number")w[y]=Number(E);else if(typeof h==="boolean")w[y]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let Y=JSON.parse(E);if(Array.isArray(Y))w[y]=Y;else w[y]=E.split(",").map((B)=>B.trim())}catch{w[y]=E.split(",").map((Y)=>Y.trim())}else w[y]=E}}}return w}return l(f)}async function VE({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:$="replace"}){let w=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?kE(i,f,l):f,y=r||_r.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(l)ei.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${y}`);let u=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([y,mi(y,"config"),mi(y,".config"),n?mi(y,n):void 0].filter(Boolean)));for(let Y of E){if(l)ei.info(`Searching for configuration in: ${Y}`);let C=[mi(y,"config"),mi(y,".config")].concat(n?[mi(y,n)]:[]).includes(Y)?[...u,...e,...A,...m]:[...e,...u,...m,...A];for(let a of C)for(let N of h){let j=mi(Y,`${a}${N}`),F=await pn(j,w,$);if(F!==null){if(l)ei.success(`Configuration loaded from: ${j}`);return F}}}if(i){let Y=mi(fc(),".config",i),B=["config",`${i}.config`];if(t)B.push(`${t}.config`);if(l)ei.info(`Checking user config directory: ${Y}`);for(let C of B)for(let a of h){let N=mi(Y,`${C}${a}`),j=await pn(N,w,$);if(j!==null){if(l)ei.success(`Configuration loaded from user config directory: ${N}`);return j}}}if(i){let Y=mi(fc(),".config"),B=[`.${i}.config`];if(t)B.push(`.${t}.config`);if(l)ei.info(`Checking user config directory for dotfile configs: ${Y}`);for(let C of B)for(let a of h){let N=mi(Y,`${C}${a}`),j=await pn(N,w,$);if(j!==null){if(l)ei.success(`Configuration loaded from user config directory dotfile: ${N}`);return j}}}if(i){let Y=fc(),B=[`.${i}.config`,`.${i}`];if(t)B.push(`.${t}.config`),B.push(`.${t}`);if(l)ei.info(`Checking user home directory for dotfile configs: ${Y}`);for(let C of B)for(let a of h){let N=mi(Y,`${C}${a}`),j=await pn(N,w,$);if(j!==null){if(l)ei.success(`Configuration loaded from user home directory: ${N}`);return j}}}try{let Y=mi(y,"package.json");if(Xy(Y)){let B=await import(Y),C=B[i];if(!C&&t){if(C=B[t],C&&l)ei.success(`Using alias "${t}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(l)ei.success(`Configuration loaded from package.json: ${C===B[i]?i:t}`);return qc(w,C,$)}catch(a){if(l)ei.warn("Failed to merge package.json config:",a)}}}catch(Y){if(l)ei.warn("Failed to load package.json:",Y)}if(l)ei.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function DE(i,t={}){let r=hf.cwd();while(r.includes("storage"))r=Vw(r,"..");let n=Vw(r,i||"");if(t?.relative)return ZA(hf.cwd(),n);return n}async function bE(){try{let i=await VE({name:"clarity",alias:"logging",defaultConfig:$f,cwd:hf.cwd()});return{...$f,...i||{}}}catch{return $f}}function ri(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function QE(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class Iy{async format(i){let t=await QE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$r.pid,hostname:t(),environment:$r.env.NODE_ENV||"development",platform:$r.platform,version:$r.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$r.env.NODE_ENV||$r.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Fc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Iy,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...wf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...wf};return{...wf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Fc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ri()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await uE(this.config.logDirectory,ry.F_OK|ry.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await eE(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:nt.from(i);try{if(!Vn(this.currentLogFile))await uc(this.currentLogFile,"",{mode:420});if(f=ty(this.currentLogFile,"a",420),hE(f,w,{flag:"a"}),iy(f),f!==void 0)hc(f),f=void 0;if((await lr(this.currentLogFile)).size===0){if(await uc(this.currentLogFile,w,{flag:"w",mode:420}),(await lr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let h=y;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(l<c-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,u);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{hc(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(l===c-1){let h=w,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),w}l++;let y=$*2**(l-1);await new Promise((h)=>setTimeout(h,y))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return cr(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 cr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return cr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ri())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,w])=>w.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return yc(16).toString("hex")}generateKey(){return yc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=yc(16),n=$E("aes-256-gcm",t,r),f=nt.isBuffer(i)?i:nt.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,w=n.getAuthTag(),y=nt.allocUnsafe(16+$+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),w.copy(y,16+$),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=fy(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(nt.from(nt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ri())return;if(!this.shouldWriteToFile())return;let i=await lr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Dn(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await lr(r).catch(()=>null))try{if(await ny(r,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await bn($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await uc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await lr(r).catch(()=>null))await ny(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Dn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await bn(cr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=pw(i),n=yE(t),f=fy();await TE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Vn(this.currentLogFile))try{let i=ty(this.currentLogFile,"r+");iy(i),hc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ri()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Dn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await bn(cr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?z.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ri())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=_.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${z.cyan(f)}`;if(!c)return y.trim();let h=$(y).trim().length,u=$(t).length,e=Math.max(1,w-2-h-u);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=z.underline(z.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>z.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>z.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>z.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>z.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>z.strikethrough(n)),t}supportsHyperlinks(){if(ri())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(AE(t)||t.startsWith("./")||t.startsWith("../"))t=EE(t);else return null;return Vn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":xy[i],e=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:z.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:z.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let m=$.split(`
|
|
81
|
-
`);for(let E of m)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:z.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ri()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
82
|
-
`;if($)h+=`${$}
|
|
83
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:($,w)=>{},finish:($)=>{},interrupt:($,w)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ri()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:($,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,$),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ri()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:($)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,$)},interrupt:($,w="info")=>{if(!ri()&&_.stdout.isTTY)_.stdout.write(`
|
|
84
|
-
`);if(this[w==="warning"?"warn":w]($),this.activeProgressBar&&this.shouldStyleConsole()&&!ri()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){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:this.options.showIcons===!1?"":z.blue("◐"),tag:r,message:`${z.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
|
|
85
|
-
`,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":z.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ri())console.error(y.trim());if(this.shouldWriteToFile())await this.writeToFile(y)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new mf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ri())throw Error("createReadStream is not supported in browser environments");if(!Vn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pw(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=nt.isBuffer(i)?i:nt.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=wE("aes-256-gcm",r,f);$.setAuthTag(l);let w=$.update(c),y=$.final(),h=w.length+y.length,u=nt.allocUnsafe(h);return w.copy(u,0),y.copy(u,w.length),u.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 ri()}isServerMode(){return!ri()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
86
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,y=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:z.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(y),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(h),showTimestamp:!1}))}else if(!ri())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
|
|
87
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ri())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${z.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,y=0;if(r=i.replace(w,(h,u)=>{if(u==="%")return"%";if(y>=t.length)return h;let e=t[y++];switch(u){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return h}}),y<t.length)r+=` ${t.slice(y).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${y}${w} ${z.cyan(n)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
88
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=z.green("━".repeat(n)),c=z.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?z.green("✓"):z.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",e=`\r${h}${u} ${$} ${w}${y}`,A=_.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
|
|
89
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ri()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ri()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Dn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=cr(this.config.logDirectory,n);if(i.before)try{if((await lr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}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 bn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ky(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function zy(i){return i instanceof ai}function PE(i){return i instanceof Bf}function vE(i){if(zy(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>i.message.toLowerCase().includes(r.toLowerCase()))}class Sf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return zr.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${$.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=Qn.env[w]||(y?Qn.env[y]:void 0);if(h!==void 0){if(n.verbose){let u=Qn.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,w,n.customParsers,n.configName)}catch(u){if(u instanceof Cf)throw u;throw Bt.envVar(w,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Bt.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(Qn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
90
|
-
|
|
91
|
-
`;for(let n of i)r+=`${n.key}
|
|
92
|
-
`,r+=` Type: ${n.type}
|
|
93
|
-
`,r+=` Description: ${n.description}
|
|
94
|
-
`,r+=` Example: ${n.example}
|
|
95
|
-
|
|
96
|
-
`;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
|
|
97
|
-
|
|
98
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
99
|
-
`,r+=`|----------|------|-------------|----------|
|
|
100
|
-
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
101
|
-
`;return r}}function ZE(i,t){let r=qy("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function Oy(i,t,r={}){return Gy(i,t,r,new WeakMap)}function Gy(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return My(i,t,f,n);if(!_i(t)||!_i(i))return t;return tT(i,t,r,n)}function My(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return oE(i,t);case"smart":return pE(i,t,n);default:return t}return t}function oE(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>ac(f,n)))r.push(n);return r}function pE(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return iT(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function iT(i,t,r){let n=[...t];for(let f of i){if(!_i(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((y)=>_i(y)&&($ in y)&&y[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function tT(i,t,r,n){let f=t;if(_i(f)&&n.has(f))return n.get(f);let l={...i};if(_i(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(_i($)&&_i(w))l[c]=Gy(w,$,r,n);else if(Array.isArray($)||Array.isArray(w))l[c]=My(w,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function Lc(i,t,r="replace"){return Oy(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ac(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!ac(i[r],t[r]))return!1;return!0}if(_i(i)&&_i(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!ac(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class af{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let y=ur.getWithFileCheck("file",i);if(y){if($)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!Pn(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),u=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new Ir(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Ir(i,Error("Configuration must export a valid object"),"unknown");let Y={config:Lc(t,u,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)ur.setWithFileCheck("file",Y,i,l);return Y}catch(y){throw y instanceof Error?Bt.configLoad(i,y):Bt.configLoad(i,Error(String(y)))}};if(c)return zr.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(ec(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return Ky(async()=>{return Pn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!Pn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=ec(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=ec(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!Pn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class gc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=r,y=async()=>{let h=[],u=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:u}}};if($)return await zr.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!YE(t))throw new Kr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Kr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let y=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ky},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class xc{fileLoader=new af;envProcessor=new Sf;validator=new gc;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw w;if(u&&(!y||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)qi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){let w=Date.now()-t;throw qi.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:y="replace",verbose:h=!1}=i,u=l||Jt.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,u,c,$,y,h,w,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,u,c)),this.finalizeResult(A,e,w,n,h);let m=await this.loadHomeConfiguration(n,f,$,y,h,w);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,u,$,y,h,w);if(E)return e.push(Bi(u,"package.json")),this.finalizeResult(E,e,w,n,h);if(e.push(...this.getAllSearchPaths(n,f,u,c)),t)throw Bt.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,w,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,w){let y=$?Jr(i,f,c):f,h=this.getLocalDirectories(r,n);for(let u of h){if(c)qi.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)qi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?Jr(i,r,f):r,$=[Bi(tr(),".config",i),Bi(tr(),".config"),tr()];for(let w of $){if(f)qi.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)qi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?Jr(i,n,l):n;try{let w=Bi(r,"package.json");if(!jc(w))return null;let y=await import(w),h=y[i],u=i;if(!h&&t)h=y[t],u=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)qi.success(`Configuration loaded from package.json: ${u}`);return{config:Lc($,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)qi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Jr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Bt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return ur.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);ur.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Bi(i,"config"),Bi(i,".config"),t?Bi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Bi(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Bi(tr(),".config",i),Bi(tr(),".config"),tr()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function Ay(i){let r=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return r||n}async function rT(i){return yt.loadConfig({...i,__strictErrorHandling:!0})}async function Hy(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await yt.loadConfig(i);else n=await yt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",l=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)qi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let $=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await yt.applyEnvironmentVariables($.name||"",t,!0,$.verbose||!1))?.config??t;return t}}async function nT(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await yt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ay(r)))return(await yt.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await yt.loadConfig({...i,cwd:i.cwd||Jt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ay(t)))return(await yt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function fT(i,t,r="replace"){let n=new af;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Jr(i,t,r=!1){let n=new Sf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[y,h]of Object.entries(c)){let u=[...$,y],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let E of e)if(A=Jt.env[E],A!==void 0){m=E;break}if(A!==void 0&&m)if(typeof h==="boolean")w[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let E=Number(A);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(h))try{w[y]=JSON.parse(A)}catch{w[y]=A.split(",").map((E)=>E.trim())}else w[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))w[y]=l(h,u)}return w}return l(t)}function lT(i){let t=Bi(Jt.cwd(),i.configDir),r=Bi(Jt.cwd(),i.generatedDir),n=Bi(r,"config-types.ts");if(!jc(kw(n)))bA(kw(n),{recursive:!0,mode:511});let f=jc(t)?QA(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${zT}
|
|
102
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
103
|
-
`;PA(n,l,{mode:438})}function cT(i){let t=null,r=null,n=()=>{if(!r)r=Hy(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)qi.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(l,c){if(t)return t[c];let $=f[c];return n(),$},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,$){if(!t)t={...f};return t[c]=$,!0}})}function $T(i){let t=ly(CE.cwd(),i?.configDir||"./config");function r(){if(!mE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=BE(t).filter((w)=>f.has(Ac(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),$=new Map;for(let{base:w,file:y}of c){let h=Ac(y).toLowerCase(),u=$.get(w);if(!u){$.set(w,y);continue}let e=Ac(u).toLowerCase();if(l.indexOf(h)<l.indexOf(e))$.set(w,y)}return Array.from($.entries()).map(([w,y])=>({base:w,file:y})).sort((w,y)=>w.base.localeCompare(y.base))}function n(){let f=r(),l=f.map((y)=>y.base),c=l.length?l.map((y)=>`'${y}'`).join(" | "):"string",$=f.length?`{
|
|
104
|
-
${f.map((y)=>{let h=ly(t,y.file).replace(/\\/g,"/");return` '${y.base}': typeof import('${h}').default`}).join(`,
|
|
105
|
-
`)}
|
|
106
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
107
|
-
export type ConfigByName = ${$}
|
|
108
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
109
|
-
export type ConfigOf = Config
|
|
110
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var qy,ur,zr,Ly,wT,yT,Ey,lf,Nc,ui,k,hT,Ty,uT,Yy,eT,AT,mc,ET,my,By,Bc,TT,YT,mT,BT,cf,gy,CT,ei,sT,RT,Cy,$f,Fc,ni,z,UT,sy,jT,Ry,ST,aT,Cc,NT,Uy,jy,FT,sc,XT,WT,JT,_T,IT,wf,xy,KT,zT="0.15.6",ai,Bf,Ir,Xc,Wc,Cf,Jc,_c,Kr,Ic,Kc,Bt,dy,ky,qi,yt,Vy,Dy,OT=OE(async()=>{qy=import.meta.require,ur=new Gc,zr=new Mc,Ly={createKey:GE,isEquivalent:ME,estimateMemoryUsage:HE},wT=ef(Sc.cwd(),"config"),yT=ef(Sc.cwd(),"src/generated"),Ey=uf.env.CLARITY_LOG_DIR||oA(gE(),"logs"),lf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ey,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Nc=await xE(),ui={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},k=ui,hT=ui.red,Ty=ui.green,uT=ui.yellow,Yy=ui.blue,eT=ui.magenta,AT=ui.cyan,mc=ui.white,ET=ui.gray,my=ui.bgRed,By=ui.bgYellow,Bc=ui.bold,TT=ui.dim,YT=ui.italic,mT=ui.underline,BT=ui.reset,cf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},gy={debug:"\uD83D\uDD0D",info:Yy("ℹ"),success:Ty("✓"),warning:By(mc(Bc(" WARN "))),error:my(mc(Bc(" ERROR ")))},CT=new Tf("stacks"),ei=new Tf("bunfig",{showTags:!0}),sT=mi(_r.cwd(),"config"),RT=mi(_r.cwd(),"src/generated"),Cy=hf.env.CLARITY_LOG_DIR||vA(DE(),"logs"),$f={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Fc=await bE(),ni={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},z=ni,UT=ni.red,sy=ni.green,jT=ni.yellow,Ry=ni.blue,ST=ni.magenta,aT=ni.cyan,Cc=ni.white,NT=ni.gray,Uy=ni.bgRed,jy=ni.bgYellow,FT=ni.bgGray,sc=ni.bold,XT=ni.dim,WT=ni.italic,JT=ni.underline,_T=ni.strikethrough,IT=ni.reset,wf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xy={debug:"\uD83D\uDD0D",info:Ry("ℹ"),success:sy("✓"),warning:jy(Cc(sc(" WARN "))),error:Uy(Cc(sc(" ERROR ")))},KT=new mf("stacks"),ai=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Bf=class extends ai{code="CONFIG_NOT_FOUND";constructor(t,r,n){let f=n?` or alias "${n}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Ir=class extends ai{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Xc=class extends ai{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Wc=class extends ai{code="CONFIG_MERGE_ERROR";constructor(t,r,n,f){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:f,originalError:n.name,originalMessage:n.message});this.cause=n}},Cf=class extends ai{code="ENV_VAR_ERROR";constructor(t,r,n,f){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:f})}},Jc=class extends ai{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},_c=class extends ai{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Kr=class extends ai{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ic=class extends ai{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,f){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:f})}},Kc=class extends ai{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Bt={configNotFound(i,t,r){return new Bf(i,t,r)},configLoad(i,t,r){return new Ir(i,t,r)},configValidation(i,t,r){return new Xc(i,t,r)},configMerge(i,t,r,n){return new Wc(i,t,r,n)},envVar(i,t,r,n){return new Cf(i,t,r,n)},fileSystem(i,t,r){return new Jc(i,t,r)},typeGeneration(i,t,r){return new _c(i,t,r)},schemaValidation(i,t,r){return new Kr(i,t,r)},browserConfig(i,t,r,n){return new Ic(i,t,r,n)},plugin(i,t,r){return new Kc(i,t,r)}},dy={replace:"replace",concat:"concat",smart:"smart"},ky=/^https?:\/\//,qi=new mf("bunfig",{showTags:!0}),yt=new xc,Vy=Bi(Jt.cwd(),"config"),Dy=Bi(Jt.cwd(),"src/generated")});function GT(i,t={}){let r=Af.cwd();while(r.includes("storage"))r=cy(r,"..");let n=cy(r,i||"");if(t?.relative)return RE(Af.cwd(),n);return n}var MT=Af.env.CLARITY_LOG_DIR||sE(GT(),"logs"),by={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:MT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sf={...by},uU=(async()=>{try{let{loadConfig:i}=await OT().then(()=>Jy),t=await i({name:"clarity",alias:"logging",defaultConfig:by,cwd:Af.cwd()});if(t)Object.assign(sf,t)}catch{}return sf})();function fi(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function HT(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof wt<"u"){let i=wt.type;if(i==="renderer"||i==="worker")return!1;return!!(wt.versions&&(wt.versions.node||wt.versions.bun))}return!1}class Qy{async format(i){let t=await HT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:hr.pid,hostname:t(),environment:hr.env.NODE_ENV||"development",platform:hr.platform,version:hr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hr.env.NODE_ENV||hr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},G=ci,eU=ci.red,qT=ci.green,AU=ci.yellow,LT=ci.blue,EU=ci.magenta,TU=ci.cyan,Sy=ci.white,YU=ci.gray,gT=ci.bgRed,xT=ci.bgYellow,mU=ci.bgGray,ay=ci.bold,BU=ci.dim,CU=ci.italic,sU=ci.underline,RU=ci.strikethrough,UU=ci.reset,Rc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dT={debug:"\uD83D\uDD0D",info:LT("ℹ"),success:qT("✓"),warning:xT(Sy(ay(" WARN "))),error:gT(Sy(ay(" ERROR ")))};class Nf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...sf},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Qy,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rc};return{...Rc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:sf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await NE(this.config.logDirectory,hy.F_OK|hy.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await FE(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ft.from(i);try{if(!vn(this.currentLogFile))await Yc(this.currentLogFile,"",{mode:420});if(f=yy(this.currentLogFile,"a",420),aE(f,w,{flag:"a"}),wy(f),f!==void 0)Tc(f),f=void 0;if((await wr(this.currentLogFile)).size===0){if(await Yc(this.currentLogFile,w,{flag:"w",mode:420}),(await wr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let h=y;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(l<c-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,u);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Tc(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(l===c-1){let h=w,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),w}l++;let y=$*2**(l-1);await new Promise((h)=>setTimeout(h,y))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return yr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,w])=>w.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return Ec(16).toString("hex")}generateKey(){return Ec(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Ec(16),n=UE("aes-256-gcm",t,r),f=ft.isBuffer(i)?i:ft.from(i,"utf8"),l=n.update(f),c=n.final(),$=l.length+c.length,w=n.getAuthTag(),y=ft.allocUnsafe(16+$+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),w.copy(y,16+$),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=ey(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(ft.from(ft.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await wr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Zn(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${r}.${c}`;if(await wr(r).catch(()=>null))try{if(await uy(r,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await on($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await Yc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await wr(r).catch(()=>null))await uy(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Zn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await on(yr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=$y(i),n=SE(t),f=ey();await JE(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),vn(this.currentLogFile))try{let i=yy(this.currentLogFile,"r+");wy(i),Tc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Zn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await on(yr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof I.env.NO_COLOR<"u",t=I.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=I.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${G.cyan(f)}`;if(!c)return y.trim();let h=$(y).trim().length,u=$(t).length,e=Math.max(1,w-2-h-u);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let $=t[n++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=G.underline(G.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>G.strikethrough(n)),t}supportsHyperlinks(){if(fi())return!1;let i=I.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=I.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(XE(t)||t.startsWith("./")||t.startsWith("../"))t=WE(t);else return null;return vn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,r);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":dT[i],e=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:G.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:G.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let m=$.split(`
|
|
111
|
-
`);for(let E of m)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!fi()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
112
|
-
`;if($)h+=`${$}
|
|
113
|
-
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:($,w)=>{},finish:($)=>{},interrupt:($,w)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!fi()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:($,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,$),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!fi()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:($)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,$)},interrupt:($,w="info")=>{if(!fi()&&I.stdout.isTTY)I.stdout.write(`
|
|
114
|
-
`);if(this[w==="warning"?"warn":w]($),this.activeProgressBar&&this.shouldStyleConsole()&&!fi()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:r,message:`${G.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
|
|
115
|
-
`,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":G.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!fi())console.error(y.trim());if(this.shouldWriteToFile())await this.writeToFile(y)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Nf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!vn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $y(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ft.isBuffer(i)?i:ft.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),$=jE("aes-256-gcm",r,f);$.setAuthTag(l);let w=$.update(c),y=$.final(),h=w.length+y.length,u=ft.allocUnsafe(h);return w.copy(u,0),y.copy(u,w.length),u.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 fi()}isServerMode(){return!fi()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
116
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,y=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:G.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(y),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(h),showTimestamp:!1}))}else if(!fi())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
|
|
117
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(fi())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();I.stdin.removeListener("data",r);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,y=0;if(r=i.replace(w,(h,u)=>{if(u==="%")return"%";if(y>=t.length)return h;let e=t[y++];switch(u){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return h}}),y<t.length)r+=` ${t.slice(y).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${y}${w} ${G.cyan(n)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
118
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=G.green("━".repeat(n)),c=G.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?G.green("✓"):G.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",e=`\r${h}${u} ${$} ${w}${y}`,A=I.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,I.stdout.write(i.lastRenderedLine),t)I.stdout.write(`
|
|
119
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=yr(this.config.logDirectory,n);if(i.before)try{if((await wr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}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 on(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var jU=new Nf("stacks");class Li extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Py extends Li{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class Rf extends Li{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class vy extends Li{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Zy extends Li{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class dc extends Li{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class oy extends Li{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class py extends Li{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Uf extends Li{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class ih extends Li{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class th extends Li{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var er={configNotFound(i,t,r){return new Py(i,t,r)},configLoad(i,t,r){return new Rf(i,t,r)},configValidation(i,t,r){return new vy(i,t,r)},configMerge(i,t,r,n){return new Zy(i,t,r,n)},envVar(i,t,r,n){return new dc(i,t,r,n)},fileSystem(i,t,r){return new oy(i,t,r)},typeGeneration(i,t,r){return new py(i,t,r)},schemaValidation(i,t,r){return new Uf(i,t,r)},browserConfig(i,t,r,n){return new ih(i,t,r,n)},plugin(i,t,r){return new th(i,t,r)}};async function kT(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=r;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class kc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Oc.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),w=`${r}_${$.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=tf.env[w]||(y?tf.env[y]:void 0);if(h!==void 0){if(n.verbose){let u=tf.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,w,n.customParsers,n.configName)}catch(u){if(u instanceof dc)throw u;throw er.envVar(w,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw er.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(tf.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${r}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
|
|
120
|
-
|
|
121
|
-
`;for(let n of i)r+=`${n.key}
|
|
122
|
-
`,r+=` Type: ${n.type}
|
|
123
|
-
`,r+=` Description: ${n.description}
|
|
124
|
-
`,r+=` Example: ${n.example}
|
|
125
|
-
|
|
126
|
-
`;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
|
|
127
|
-
|
|
128
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
129
|
-
`,r+=`|----------|------|-------------|----------|
|
|
130
|
-
`;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
131
|
-
`;return r}}function VT(i,t,r={}){return rh(i,t,r,new WeakMap)}function rh(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return nh(i,t,f,n);if(!Ii(t)||!Ii(i))return t;return PT(i,t,r,n)}function nh(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return DT(i,t);case"smart":return bT(i,t,n);default:return t}return t}function DT(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>zc(f,n)))r.push(n);return r}function bT(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return QT(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function QT(i,t,r){let n=[...t];for(let f of i){if(!Ii(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(n.find((y)=>Ii(y)&&($ in y)&&y[$]===f[$])){c=!0;break}}if(!c)n.push(f)}return n}function PT(i,t,r,n){let f=t;if(Ii(f)&&n.has(f))return n.get(f);let l={...i};if(Ii(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(r.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Ii($)&&Ii(w))l[c]=rh(w,$,r,n);else if(Array.isArray($)||Array.isArray(w))l[c]=nh(w,$,r.arrayMergeMode||"smart",n);else l[c]=$}return l}function fh(i,t,r="replace"){return VT(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function zc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!zc(i[r],t[r]))return!1;return!0}if(Ii(i)&&Ii(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zc(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class lh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=r;if(f){let y=yf.getWithFileCheck("file",i);if(y){if($)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!rf(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),u=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new Rf(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Rf(i,Error("Configuration must export a valid object"),"unknown");let Y={config:fh(t,u,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)yf.setWithFileCheck("file",Y,i,l);return Y}catch(y){throw y instanceof Error?er.configLoad(i,y):er.configLoad(i,Error(String(y)))}};if(c)return Oc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(Uc(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of n){if(!l)continue;if(r.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)r.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return r.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return kT(async()=>{return rf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!rf(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let $=Uc(i,`${l}${c}`);if(await this.checkFileAccess($))n.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=Uc(i,c);if(await this.checkFileAccess($))n.push($)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!rf(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var ZT=/^https?:\/\//;class ch{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=r,y=async()=>{let h=[],u=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:u}}};if($)return await Oc.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!vT(t))throw new Uf(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Uf(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(n.push({path:r,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(n.push({path:r?`${r}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let y=r?`${r}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:r?`${r}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(n.push(...$),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ZT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var lt=new Nf("bunfig",{showTags:!0});function oT(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class $h{fileLoader=new lh;envProcessor=new kc;validator=new ch;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,r)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw w;if(u&&(!y||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(r?.enabled&&$)this.cacheResult(c.name||"",$,r,c);if(n?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(w);if(n.slowThreshold&&w.duration>n.slowThreshold)lt.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){if($ instanceof Error&&$.name==="ConfigNotFoundError")throw $;let w=Date.now()-t;throw lt.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:y="replace",verbose:h=!1}=i,u=l||jf.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,u,c,$,y,h,w,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,u,c)),this.finalizeResult(A,e,w,n,h);let m=await this.loadHomeConfiguration(n,f,$,y,h,w);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,w,n,h);let E=await this.loadPackageJsonConfiguration(n,f,u,$,y,h,w);if(E)return e.push(Ji(u,"package.json")),this.finalizeResult(E,e,w,n,h);if(e.push(...this.getAllSearchPaths(n,f,u,c)),t)throw er.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,$,w,h),warnings:[`No configuration file found for "${n}"${oT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,$,w){let y=$?nf(i,f,c):f,h=this.getLocalDirectories(r,n);for(let u of h){if(c)lt.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)lt.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?nf(i,r,f):r,$=[Ji(ir(),".config",i),Ji(ir(),".config"),ir()];for(let w of $){if(f)lt.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)lt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let $=c?nf(i,n,l):n;try{let w=Ji(r,"package.json");if(!VA(w))return null;let y={};try{y=JSON.parse(DA(w,"utf8"))}catch(e){if(l)lt.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let h=y[i],u=i;if(!h&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(y[A]){h=y[A],u=A;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)lt.success(`Configuration loaded from package.json: ${u}`);return{config:fh($,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)lt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:nf(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw er.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return yf.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);yf.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ji(ir(),".config",i),Ji(ir(),".config"),ir()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var XU=new $h;function nf(i,t,r=!1){let n=new kc,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[y,h]of Object.entries(c)){let u=[...$,y],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let E of e)if(A=jf.env[E],A!==void 0){m=E;break}if(A!==void 0&&m)if(typeof h==="boolean")w[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let E=Number(A);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(h))try{w[y]=JSON.parse(A)}catch{w[y]=A.split(",").map((E)=>E.trim())}else w[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))w[y]=l(h,u)}return w}return l(t)}var WU=Ji(jf.cwd(),"config"),JU=Ji(jf.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",pT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Dc(Vc(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Dc(Vc(),".stacks","ssl","stacks.localhost.crt"),keyPath:Dc(Vc(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var wh=pT;import{execSync as Gr}from"node:child_process";import{homedir as nY}from"node:os";import{join as fY}from"node:path";function iY(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function _t(i){try{return xn(i)}catch{return null}}function bc(i){try{return ic(i)||null}catch{return null}}function Qc(i,t){try{return t.every((r)=>rc(i,r))}catch{return!1}}function tY(i,t,r=443){return tc(i,t,r)}function rY(i){let t=[];for(let r of i.split(`
|
|
132
|
-
`)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)t.push(n[1].toUpperCase())}return t}var Ct="-d -r trustRoot -p ssl -p basic",It="/Library/Keychains/System.keychain",Pc="rpx.localhost";function Mr(){return fY(nY(),"Library/Keychains/login.keychain-db")}function vc(){return[It,Mr()]}function yh(i,t=Pc){let r=Gr(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let f of r.split(`
|
|
133
|
-
`)){let l=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(l)n.push(l[1].toUpperCase())}return n}function Ff(i){if(process.platform!=="darwin")return;let t=_t(i.caPath);if(!t)return;let r=i.commonName??Pc,n=i.keychains??vc();for(let f of n)for(let l of yh(f,r)){if(l===t)continue;try{if(f.startsWith("/Library"))Or(`security delete-certificate -Z ${l} "${f}"`);else Gr(`security delete-certificate -Z ${l} "${f}"`,{stdio:"ignore"});T("ssl",`Removed stale Root CA ${l} from ${f}`,i.verbose)}catch{}}}function Hr(i,t,r){if(process.platform!=="darwin")return qr(i,r);try{let f=Gr(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return T("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,r?.verbose),f}catch{return!1}}function qr(i,t){let r=_t(i);if(!r)return!1;for(let n of vc())try{let f=Gr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let l of f.split(`
|
|
134
|
-
`))if(l.toUpperCase().includes("SHA-256")){if(l.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return T("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}function Zc(i,t){if(process.platform!=="darwin")return!1;let r=t.serverName;Ff({caPath:i,commonName:t.commonName,verbose:t.verbose});let n=Mr();try{Gr(`security add-trusted-cert ${Ct} -k "${n}" "${i}"`,{stdio:"ignore"})}catch{}try{Or(`security add-trusted-cert ${Ct} -k ${It} "${i}"`)}catch{return!1}return Hr(i,r,{verbose:t.verbose})||qr(i,{verbose:t.verbose})}var st=null,t0=b(Ar(),".stacks","ssl","rpx.localhost.crt");function Yh(i,t){return[...new Set(i.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function mh(i,t,r){let n=b(Ar(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:t0,keyPath:b(n,"rpx.localhost.key"),caCertPath:b(n,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:f.map((l)=>({from:"localhost:1",to:l,cleanUrls:!1}))}}var lY="rpx-root-ca.crt",cY="rpx-root-ca.key";function r0(i){return{caCertPath:b(i,lY),caKeyPath:b(i,cY)}}function nj(i){return{certPath:b(i,"rpx.localhost.crt"),keyPath:b(i,"rpx.localhost.key"),caCertPath:b(i,"rpx.localhost.ca.crt"),rootCA:r0(i)}}async function $Y(i,t){try{let[r,n]=await Promise.all([v.readFile(i.caCertPath,"utf8"),v.readFile(i.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return T("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:n}}catch(r){return T("ssl",`No existing Root CA at ${i.caCertPath} (${r.code||r}), will create one`,t),null}}function hh(i){let t=new Set;t.add(i);let r=i.split(".");if(r.length>=2)t.add(`*.${r.slice(1).join(".")}`);return Array.from(t)}function Bh(i){let r=i0(i).replace(/\*/g,"wildcard"),n=b(Ar(),".stacks","ssl"),f=n;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:n,{caCertPath:i.https.caCertPath||b(f,`${r}.ca.crt`),certPath:i.https.certPath||b(f,`${r}.crt`),keyPath:i.https.keyPath||b(f,`${r}.key`)};return{caCertPath:b(f,`${r}.ca.crt`),certPath:b(f,`${r}.crt`),keyPath:b(f,`${r}.key`)}}function uh(i){let t=new Set;if(Xf(i))i.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";hh(n).forEach((f)=>t.add(f))});else if(Ah(i)){let r=i.to||"rpx.localhost";hh(r).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function fj(i){T("ssl","Loading SSL configuration",i.verbose);let t={...wh,...i};if(i.https=l0(t),!i.https?.keyPath&&!i.https?.certPath)return T("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let r=!i.https?.keyPath?"keyPath":"certPath";throw T("ssl",`Invalid SSL configuration - missing ${r}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{T("ssl","Reading SSL certificate files",i.verbose);let r=await v.readFile(i.https?.keyPath,"utf8"),n=await v.readFile(i.https?.certPath,"utf8");return T("ssl","SSL configuration loaded successfully",i.verbose),{key:r,cert:n}}catch(r){return T("ssl",`Failed to read certificates: ${r}`,i.verbose),null}}catch(r){throw T("ssl",`SSL configuration error: ${r}`,i.verbose),r}}async function lj(i,t){if(gi.platform==="darwin")return wY(i,t);if(gi.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)n(!0);else r(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(l)=>{n(!l)})})})}catch{return!1}return!1}async function wY(i,t){if(gi.platform!=="darwin")return!1;let r=t?.serverName??"rpx.localhost",n=t?.verbose??!1;try{if(Hr(i,r,{verbose:n}))return T("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return T("ssl","Trusting Root CA for browsers (login + system keychains)",n),Zc(i,{serverName:r,verbose:n})}catch{return!1}}async function Ch(i){if(st&&!i.forceRegenerate){T("ssl","Using cached SSL configuration",i.verbose);return}n0();let t=Xf(i)?i.proxies.map((h)=>h.to):[i.to];T("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let r=l0(i,i.verbose),n=r.basePath||b(Ar(),".stacks","ssl");await v.mkdir(n,{recursive:!0});let f=r0(n),l=await $Y(f,i.verbose),c=!1;if(!l){if(i.verbose)X.info("Generating Root CA certificate (one-time)...");l=await ol(r);try{await Promise.all([v.writeFile(f.caCertPath,l.certificate),v.writeFile(f.caKeyPath,l.privateKey,{mode:384})]),c=!0,T("ssl",`Persisted Root CA at ${f.caCertPath}`,i.verbose)}catch(h){throw T("ssl",`Error saving Root CA files: ${h}`,i.verbose),Error(`Failed to save Root CA files: ${h}`)}}else T("ssl",`Reusing existing Root CA from ${f.caCertPath}`,i.verbose);if(i.verbose)X.info(`Generating host certificate for: ${t.join(", ")}`);let $=await pl({...r,rootCA:{certificate:l.certificate,privateKey:l.privateKey}});try{await Promise.all([v.writeFile(r.certPath,$.certificate),v.writeFile(r.keyPath,$.privateKey),v.writeFile(r.caCertPath,l.certificate)]),T("ssl","Certificate files saved successfully",i.verbose)}catch(h){throw T("ssl",`Error saving certificate files: ${h}`,i.verbose),Error(`Failed to save certificate files: ${h}`)}if(c?!1:await sh(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(T("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)X.success("Root CA is already trusted in system trust store");if(st={key:$.privateKey,cert:$.certificate,ca:l.certificate},i.verbose)X.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)X.info("Adding certificate to system trust store (may require sudo permission)...");let y=!1;if(gi.platform==="darwin")try{Ff({caPath:f.caCertPath,verbose:i.verbose});let h=Mr();try{oc(`security add-trusted-cert ${Ct} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Or(`security add-trusted-cert ${Ct} -k ${It} "${f.caCertPath}"`),i.verbose)X.success("Successfully added Root CA to system trust store");y=!0;let u=b(n,"trust-rpx-cert.sh"),e=`#!/bin/bash
|
|
135
|
-
echo "Trusting RPX Root CA"
|
|
136
|
-
sudo security add-trusted-cert ${Ct} -k ${It} "${f.caCertPath}"
|
|
137
|
-
echo "Root CA trusted! Please restart your browser."
|
|
138
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
139
|
-
`;await v.writeFile(u,e,{mode:493})}catch(h){if(i.verbose)X.warn(`Could not add Root CA to trust store automatically: ${h}`);let u=b(n,"trust-rpx-cert.sh"),e=`#!/bin/bash
|
|
140
|
-
echo "Trusting RPX Root CA"
|
|
141
|
-
sudo security add-trusted-cert ${Ct} -k ${It} "${f.caCertPath}"
|
|
142
|
-
echo "Root CA trusted! Please restart your browser."
|
|
143
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
144
|
-
`;if(await v.writeFile(u,e,{mode:493}),i.verbose)X.info(`Created a trust helper script at: ${u}`),X.info(`If you're still having certificate issues, run: sh ${u}`)}else if(gi.platform==="linux")try{let{exec:h}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",e=`
|
|
145
|
-
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
146
|
-
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
147
|
-
update-ca-certificates
|
|
148
|
-
echo "RPX Root CA installed. Please restart your browser."
|
|
149
|
-
`,A=b(pc.tmpdir(),`rpx-trust-${Date.now()}.sh`);await v.writeFile(A,e,{mode:493}),await new Promise((m)=>{h(`sudo bash "${A}"`,(E)=>{if(E){if(i.verbose)X.warn(`Could not trust certificates: ${E}`);m(!1)}else{if(i.verbose)X.success("Successfully added certificates to system trust store");m(!0)}})}),await v.unlink(A).catch(()=>{}),y=!0}catch(h){if(i.verbose)X.warn(`Failed to trust certificates: ${h}`)}else if(gi.platform==="win32")try{let h=`
|
|
150
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
151
|
-
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
152
|
-
$store.Open("ReadWrite")
|
|
153
|
-
$store.Add($cert)
|
|
154
|
-
$store.Close()
|
|
155
|
-
Write-Host "Root CA trusted successfully!"
|
|
156
|
-
`,u=b(pc.tmpdir(),"rpx-trust.ps1");if(await v.writeFile(u,h),oc(`powershell -ExecutionPolicy Bypass -File "${u}"`),i.verbose)X.success("Successfully added certificate to Windows trust store");y=!0}catch(h){if(i.verbose)X.warn(`Could not trust certificate: ${h}`)}else try{await nc($,l.certificate,r),y=!0}catch(h){if(i.verbose)X.warn(`Could not add certificate to trust store: ${h}`)}if(st={key:$.privateKey,cert:$.certificate,ca:l.certificate},i.verbose)X.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!y&&i.verbose)X.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),X.warn("This will bypass the warning and you should only need to do it once")}function n0(){st=null}async function f0(i){if(!i)return null;if(st)return st;let t=l0(i);try{let[r,n,f]=await Promise.all([v.access(t.keyPath).then(()=>!0).catch(()=>!1),v.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?v.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return T("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let l="regenerateUntrustedCerts"in i,c=i.regenerateUntrustedCerts,$=l?c!==!1:!0;T("ssl",`Trust check: hasFlag=${l}, flagValue=${c}, shouldCheckTrust=${$}`,i.verbose);let w=t.basePath||b(Ar(),".stacks","ssl"),y=r0(w);if(!($?await sh(y.caCertPath,i):!0))return T("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[u,e,A]=await Promise.all([v.readFile(t.keyPath,"utf8"),v.readFile(t.certPath,"utf8"),f&&t.caCertPath?v.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(A&&!A.includes("-----BEGIN CERTIFICATE-----"))return T("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(Xf(i))try{let{X509Certificate:m}=await import("node:crypto"),Y=new m(e).subjectAltName||"",C=i.proxies.map((a)=>a.to).filter((a)=>!Y.includes(`DNS:${a}`));if(C.length>0)return T("ssl",`Certificate missing SANs for: ${C.join(", ")}, will regenerate`,i.verbose),null}catch(m){T("ssl",`Could not verify cert SANs: ${m}`,i.verbose)}return T("ssl","Successfully loaded existing certificates",i.verbose),st={key:u,cert:e,ca:A},st}catch(r){return T("ssl",`Error checking existing certificates: ${r}`,i.verbose),null}}function l0(i,t){let r=i0(i);T("ssl",`Primary domain: ${r}`,t);let n=Bh(i),f=b(Ar(),".stacks","ssl");if(typeof i.https==="object"){let l=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,c={domain:r,hostCertCN:r,basePath:l,caCertPath:i.https.caCertPath||n.caCertPath,certPath:i.https.certPath||n.certPath,keyPath:i.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||r,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(uh(i)).map(($)=>({type:2,value:$}))};if(eh(i.https.rootCA))c.rootCA=i.https.rootCA;return c}return{domain:r,hostCertCN:r,basePath:f,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(uh(i)).map((l)=>({type:2,value:l}))}}async function cj(i,t){let r=Bh({to:i,verbose:t}),n=[r.caCertPath,r.certPath,r.keyPath];T("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((f)=>Eh(f,t)))}async function sh(i,t){try{if(T("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),gi.platform==="darwin"){if(t?.serverName)return Hr(i,t.serverName,{verbose:t?.verbose});return qr(i,{verbose:t?.verbose})}else if(gi.platform==="win32")try{let r=bc(i)||"";if(!r)return T("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(oc(n).toString().includes(r))return T("ssl","Certificate found in trusted root store",t?.verbose),!0;return T("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return T("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(gi.platform==="linux")try{let r=_t(i);if(!r)return T("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of n){let l;try{l=await v.readdir(f)}catch{continue}for(let c of l){let $=_t(Th.join(f,c));if($&&$===r)return T("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return T("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return T("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return T("ssl",`Platform ${gi.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return T("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}function yY(i){return{enabled:i?.enabled??!1,path:i?.path??"/",interval:i?.interval??1e4,timeout:i?.timeout??2000,healthyThreshold:i?.healthyThreshold??2,unhealthyThreshold:i?.unhealthyThreshold??3}}function hY(i){return(Array.isArray(i)?i:[i]).map((r)=>{let n=typeof r==="string"?{url:r}:r;return{url:n.url,weight:n.weight&&n.weight>0?n.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Rh(i){if(!i)return"localhost:5173";let t=Array.isArray(i)?i[0]:i;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function Uh(i,t){return{upstreams:hY(i),strategy:t?.strategy??"round-robin",healthCheck:yY(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function uY(i){let t=i.upstreams.filter((r)=>r.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function eY(i,t){let r=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[r]}function AY(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((f,l)=>f+l.weight,0),n=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[n])n=f;return i.wrrCurrentWeights[n]-=r,t[n]}function EY(i){let t=i[0];for(let r=1;r<i.length;r++)if(i[r].activeConnections<t.activeConnections)t=i[r];return t}function jh(i){let t=uY(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return AY(i,t);case"least-connections":return EY(t);case"round-robin":default:return eY(i,t)}}function Wf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function Lr(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function TY(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let r=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(r)?r:80}}async function YY(i,t){let{hostname:r,port:n}=TY(t.url),f=new AbortController,l=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${r}:${n}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Wf(i,t)}catch{Lr(i,t)}finally{clearTimeout(l)}}function Sh(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let r of i.upstreams)YY(i,r)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function ah(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as Fh,timingSafeEqual as Nh}from"node:crypto";import{readFileSync as mY}from"node:fs";var BY="/.well-known/acme-challenge/";function gr(i,t){let r=Buffer.from(i,"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return Nh(r,r),!1;return Nh(r,n)}function CY(i,t){let r=(e)=>Fh("md5").update(e).digest(),n=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),l=r(Buffer.concat([n,f,n])),c=[n,Buffer.from("$apr1$","utf8"),f];for(let e=n.length;e>0;e-=16)c.push(l.subarray(0,Math.min(e,16)));for(let e=n.length;e>0;e>>=1)c.push(e&1?Buffer.from([0]):n.subarray(0,1));let $=r(Buffer.concat(c));for(let e=0;e<1000;e++){let A=[];if(A.push(e&1?n:$.subarray(0,16)),e%3)A.push(f);if(e%7)A.push(n);A.push(e&1?$.subarray(0,16):n),$=r(Buffer.concat(A))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",y=(e,A)=>{let m="",E=e;for(let Y=0;Y<A;Y++)m+=w[E&63],E>>=6;return m},h=$,u="";return u+=y(h[0]<<16|h[6]<<8|h[12],4),u+=y(h[1]<<16|h[7]<<8|h[13],4),u+=y(h[2]<<16|h[8]<<8|h[14],4),u+=y(h[3]<<16|h[9]<<8|h[15],4),u+=y(h[4]<<16|h[10]<<8|h[5],4),u+=y(h[11],2),`$apr1$${t}$${u}`}function sY(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let n=t.split("$")[2]??"";return gr(CY(i,n),t)}if(t.startsWith("{SHA}")){let r=Fh("sha1").update(i,"utf8").digest("base64");return gr(`{SHA}${r}`,t)}return gr(i,t)}function RY(i){let t=new Map;for(let r of i.split(`
|
|
157
|
-
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let f=n.indexOf(":");if(f<=0)continue;t.set(n.slice(0,f),n.slice(f+1))}return t}function Xh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",r=[];if(i.username)r.push({username:i.username,password:i.password??""});for(let l of i.users??[])if(l?.username)r.push({username:l.username,password:l.password??""});let n;if(i.htpasswdFile)try{n=RY(mY(i.htpasswdFile,"utf8"))}catch{n=void 0}if(r.length===0&&(!n||n.size===0))return;return{realm:t,verify:(l,c)=>{let $=!1;for(let w of r)if(gr(l,w.username)&&gr(c,w.password))$=!0;if(n){let w=n.get(l);if(w&&sY(c,w))$=!0}return $}}}function Wh(i,t,r){if(t.startsWith(BY))return;let n=i.headers.get("authorization")??"",f=n.indexOf(" "),l=f===-1?n:n.slice(0,f),c=f===-1?"":n.slice(f+1).trim();if(l.toLowerCase()==="basic"&&c){let w="";try{w=Buffer.from(c,"base64").toString("utf8")}catch{w=""}let y=w.indexOf(":");if(y>=0&&r.verify(w.slice(0,y),w.slice(y+1)))return}let $=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${$}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:UY}=Bun,xr=Symbol("rpx.pool.fallback"),Jf=Symbol("rpx.pool.stale");var jY=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function SY(i){return jY.has(i.toUpperCase())}var $0=Symbol("rpx.pool.timeout"),Kt=Symbol("rpx.pool.busy");function aY(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function NY(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function FY(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function XY(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var _h=1048576;function WY(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var c0=30000,JY=16384,Ih=262144,_Y=2097152,IY=524288,KY=8192,zY=4096,OY=new TextEncoder,Kh=new TextDecoder,GY=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class zh{socket=null;buf=new Uint8Array(JY);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,r=t.write(i);while(r<i.length){if(this.closed)throw Jf;await new Promise((n)=>{this.drainWaiter=n}),r+=t.write(i.subarray(r))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>_Y)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=IY)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Oh{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=aY();maxWaiters;checkoutIdleMs=FY();inUse=new Set;constructor(i,t,r,n=""){this.host=i;this.port=t;this.maxTotal=r;this.key=n;this.maxWaiters=NY(r)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new zh;return UY({hostname:this.host,port:this.port,socket:{data:(t,r)=>i.push(r),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let n=XY();if(n>0)r.timeout?.(n);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Kt;let i=await this.waitForSlot();if(i===Kt)throw Kt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,r=(l)=>{if(t)return;t=!0,clearTimeout(f),i(l)},n=(l)=>r(l),f=setTimeout(()=>{let l=this.waiters.indexOf(n);if(l!==-1)this.waiters.splice(l,1);r(Kt)},this.queueWaitMs);f.unref?.(),this.waiters.push(n)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min(c0,this.checkoutIdleMs):c0;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-c0;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=i-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=r)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&_f.get(this.key)===this)_f.delete(this.key)}}}var _f=new Map;function MY(i,t){let r=_f.get(i);if(!r){let n=i.lastIndexOf(":"),f=n===-1?i:i.slice(0,n),l=n===-1?80:Number(i.slice(n+1));r=new Oh(f,l,t,i),_f.set(i,r)}return r}function Jh(i,t,r){for(let n=r+3;n<t;n++)if(i[n]===10&&i[n-1]===13&&i[n-2]===10&&i[n-3]===13)return n-3;return-1}function HY(i,t,r){let n=Kh.decode(i.subarray(t,r)),f=n.indexOf(`\r
|
|
158
|
-
`),l=f===-1?n:n.slice(0,f),c=l.indexOf(" "),$=Number.parseInt(l.slice(c+1,c+5),10),w=l.startsWith("HTTP/1.0"),y=[],h=-1,u=!1,e=w,A=!1,m=!1,E=f===-1?n.length:f+2;while(E<n.length){let Y=n.indexOf(`\r
|
|
159
|
-
`,E);if(Y===-1)Y=n.length;let B=n.slice(E,Y);if(E=Y+2,B==="")continue;let C=B.indexOf(":");if(C===-1)continue;let a=B.slice(0,C),N=B.slice(C+1).trim(),j=a.charCodeAt(0)|32;if(j===99||j===116||j===107){let F=a.toLowerCase();if(F==="content-length"){let M=/^\d+$/.test(N)?Number(N):Number.NaN;if(!Number.isSafeInteger(M)||h>=0&&h!==M)m=!0;else h=M;continue}if(F==="transfer-encoding"){if(N.toLowerCase().includes("chunked"))u=!0;continue}if(F==="connection"){let M=N.toLowerCase();if(M.includes("close"))e=!0;if(M.includes("keep-alive"))A=!0;continue}if(F==="keep-alive")continue}y.push([a,N])}if(w&&A)e=!1;if(u&&h>=0)h=-1;return{status:$,headerEnd:r,headers:y,contentLength:h,chunked:u,closeConn:e,malformed:m}}function qY(i,t){return t||i===204||i===304}async function Gh(i){let{hostPort:t,method:r,path:n,reqHeaders:f,forwardedHost:l,originOverride:c,body:$}=i,w=r==="HEAD";if(f.get("expect")||f.get("upgrade"))throw xr;let y=null;if($){let A=f.get("content-length"),m=A?Number.parseInt(A,10):Number.NaN;if(Number.isNaN(m)||m>_h)throw xr;if(y=await DY($),y===null)throw xr}let h=VY(r,n,f,t,l,c,y),u=h;if(y&&y.length)u=new Uint8Array(h.length+y.length),u.set(h),u.set(y,h.length);let e=MY(t,i.maxPerHost??WY());for(let A=0;;A++){if(A>0)await new Promise((E)=>{setTimeout(E,A)});let m;try{m=e.acquireIdleSync()??await e.acquireOrDial()}catch(E){if(E!==Kt&&A<4)continue;throw E}try{let E=m.socket.write(u);if(E<u.length)await m.writeAll(u.subarray(E));return await gY(e,m,w)}catch(E){let Y=E===Jf&&A<4&&(m.fresh||SY(r));if(e.destroy(m),Y)continue;if(E===Jf)throw Error("upstream closed connection");throw E}}}async function LY(i){let t=Jh(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw $0;if(i.len===i.pos)throw Jf;throw Error("upstream closed mid-header")}if(i.len-i.pos>Ih)throw Error("upstream header block too large");await i.waitForData(i.len),t=Jh(i.buf,i.len,i.pos)}return t}async function gY(i,t,r){let n;for(;;){let l=await LY(t);if(n=HY(t.buf,t.pos,l),t.pos=l+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=n.headers;if(qY(n.status,r))return Mh(i,t,n.closeConn),new Response(null,{status:n.status,headers:f});if(n.chunked)return new Response(kY(i,t,n.closeConn),{status:n.status,headers:f});if(n.contentLength>=0){if(t.len-t.pos>=n.contentLength){let c=t.pos+n.contentLength,$=t.len>c,w=null;if(n.contentLength>=KY)w=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(zY);else if(n.contentLength>0)w=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,n.closeConn||$)i.destroy(t);else i.release(t);return new Response(w,{status:n.status,headers:f})}return new Response(xY(i,t,n.contentLength,n.closeConn),{status:n.status,headers:f})}return new Response(dY(t),{status:n.status,headers:f})}function Mh(i,t,r){if(r||t.pos!==t.len)i.destroy(t);else i.release(t)}function xY(i,t,r,n){let f=t.len-t.pos,l=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-f,t.queuedBytes=0,t.streamingBody=!0;let c=($)=>{if(t.bodyQueue=null,n||t.len>0)i.destroy(t);else i.release(t);$.close()};return new ReadableStream({start($){if(l)$.enqueue(l);if(t.bodyRemaining===0&&t.bodyQueue.length===0)c($)},async pull($){for(;;){let w=t.bodyQueue;if(w&&w.length>0){let y=w.shift();if(t.queuedBytes-=y.length,t.resumeIfDrained(),$.enqueue(y),t.bodyRemaining===0&&w.length===0)c($);return}if(t.bodyRemaining===0){if(t.bodyQueue)c($);return}if(t.closed){t.bodyQueue=null,i.destroy(t),$.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function dY(i){return i.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(i.len>i.pos){t.enqueue(i.buf.slice(i.pos,i.len)),i.pos=i.len,i.resumeIfDrained();return}if(i.closed){i.destroy(),t.close();return}await i.waitForData(i.len)}},cancel(){i.destroy()}})}function kY(i,t,r){t.streamingBody=!0;let n=0,f=!1;async function l(){for(;;){for(let c=t.pos;c+1<t.len;c++)if(t.buf[c]===13&&t.buf[c+1]===10){let $=Kh.decode(t.buf.subarray(t.pos,c));return t.pos=c+2,$}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>Ih)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(c){for(;;){if(n>0){if(t.len===t.pos){if(t.closed){i.destroy(t),c.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let h=Math.min(n,t.len-t.pos);if(c.enqueue(t.buf.slice(t.pos,t.pos+h)),t.pos+=h,n-=h,t.resumeIfDrained(),n===0)f=!0;return}if(f)await l(),f=!1;let $=await l(),w=$.indexOf(";"),y=Number.parseInt(w===-1?$:$.slice(0,w),16);if(!Number.isInteger(y)||y<0){i.destroy(t),c.error(Error("upstream sent malformed chunk size"));return}if(y===0){for(;;)if(await l()==="")break;Mh(i,t,r),c.close();return}n=y}},cancel(){i.destroy(t)}})}function VY(i,t,r,n,f,l,c){let $=`${i} ${t} HTTP/1.1\r
|
|
160
|
-
host: ${n}\r
|
|
161
|
-
x-forwarded-for: 127.0.0.1\r
|
|
162
|
-
x-forwarded-proto: https\r
|
|
163
|
-
x-forwarded-host: ${f}\r
|
|
164
|
-
`;if(l!==void 0)$+=`origin: ${l}\r
|
|
165
|
-
`;let w=!1;for(let[y,h]of r){let u=y.toLowerCase();if(GY.has(u))continue;if(l!==void 0&&u==="origin")continue;if(u==="content-length")w=!0;$+=`${y}: ${h}\r
|
|
166
|
-
`}if($+=`connection: keep-alive\r
|
|
167
|
-
`,c&&!w)$+=`content-length: ${c.length}\r
|
|
168
|
-
`;return $+=`\r
|
|
169
|
-
`,OY.encode($)}async function DY(i){let t=i.getReader(),r=[],n=0;for(;;){let{done:c,value:$}=await t.read();if(c)break;if($){if(n+=$.length,n>_h)return t.cancel().catch(()=>{}),null;r.push($)}}if(r.length===1)return r[0];let f=new Uint8Array(n),l=0;for(let c of r)f.set(c,l),l+=c.length;return f}function Tj(i){let t=typeof i==="string"?{to:i}:i,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function Hh(i,t,r){if(!i.preservePath)return i.to||"/";let n=`${t}${r}`;return n==="/"?`${i.to}/`:`${i.to}${n}`}import*as Ki from"node:path";function qh(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var bY={".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 QY(i){let t=Ki.extname(i).toLowerCase();return bY[t]??"application/octet-stream"}function PY(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ki.posix.normalize(`/${t}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function vY(i,t){let r=PY(i);if(r===null)return null;let n=Ki.posix.extname(r);if(t.cleanUrls&&n===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ki.join(t.dir,r),redirectTo:f||"/"}}if(r===""||i.endsWith("/"))return{filePath:Ki.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Ki.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ki.join(t.dir,`${r}.html`)};return{filePath:Ki.join(t.dir,r,"index.html")}}async function Lh(i,t){let r=vY(i,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(r.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":QY(r.filePath),"Cache-Control":n}});if(t.spa){let l=Ki.join(t.dir,"index.html"),c=Bun.file(l);if(await c.exists())return new Response(c,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}function ZY(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var oY=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function pY(i){let t=i.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function kh(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let r=i.slice(t.length);return r===""?"/":r}return i}function gh(i){if(i.upstreamPool)return jh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function xh(i,t,r,n){let f=r?.url??t.sourceHost??"",c=t.stripBasePathPrefix??!1?kh(i,t.basePath):i,$=dh(c,t.pathRewrites);if($)f=$.targetHost,c=$.targetPath,T("request",`Path rewrite: ${i} → ${f}${c}`,n);return{targetHost:f,targetPath:c}}function im(i){let t=i.indexOf("://"),r=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=i.indexOf("?",r);if(n===-1)return{pathname:i.slice(r),search:""};return{pathname:i.slice(r,n),search:i.slice(n)}}function w0(i,t,r){let n=async(f,l)=>{let{pathname:c,search:$}=im(f.url),w=pY(f),y=i(w,c);if(!y&&r){let Y=await r(w,c,f);if(Y instanceof Response)return Y;if(Y&&Y.retry)y=i(w,c)}if(!y)return T("request",`No route found for host: ${w}`,t),new Response(`No proxy configured for ${w}`,{status:404});if(y.auth){let Y=Wh(f,c,y.auth);if(Y)return T("request",`401 challenge for ${w}${c}`,t),Y}if(y.redirect){let Y=Hh(y.redirect,c,$);return T("request",`${y.redirect.status} redirect ${w}${c} → ${Y}`,t),new Response(null,{status:y.redirect.status,headers:{location:Y}})}if(y.static){let B=y.stripBasePathPrefix??!0?kh(c,y.basePath):c;return Lh(B,y.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let Y=gh(y);if(!l||!Y)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:B,targetPath:C}=xh(c,y,Y,t),a=`ws://${B}${C}${$}`,N={};for(let[M,o]of f.headers)if(!oY.has(M.toLowerCase())&&M.toLowerCase()!=="host")N[M]=o;N.host=B,N["x-forwarded-for"]="127.0.0.1",N["x-forwarded-proto"]="https",N["x-forwarded-host"]=w;let j={targetUrl:a,forwardHeaders:N};if(l.upgrade(f,{data:j})){T("ws",`upgraded ${w}${C} → ${a}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=gh(y);if(!h)return new Response(`No upstream configured for ${w}`,{status:502});if(y.cleanUrls&&c.endsWith(".html")){let Y=c.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:Y}})}let{targetHost:u,targetPath:e}=xh(c,y,h,t),A=y.changeOrigin?`http://${u}`:void 0,m=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=y.upstreamPool;if(E)h.activeConnections++;try{let Y=await Gh({hostPort:u,method:f.method,path:`${e}${$}`,reqHeaders:f.headers,forwardedHost:w,originOverride:A,body:f.body});if(E)Wf(E,h);return Y}catch(Y){if(Y===$0){if(T("request",`Upstream timeout for ${w}`,t),E)Lr(E,h);return new Response("Gateway Timeout",{status:504})}if(Y===Kt)return T("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(Y===xr||!m)try{let B=new Headers(f.headers);if(B.set("host",u),B.set("x-forwarded-for","127.0.0.1"),B.set("x-forwarded-proto","https"),B.set("x-forwarded-host",w),A!==void 0)B.set("origin",A);let C=await fetch(`http://${u}${e}${$}`,{method:f.method,headers:B,body:f.body,redirect:"manual"});if(E)Wf(E,h);return C}catch(B){if(T("request",`Proxy error for ${w}: ${B}`,t),E)Lr(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}if(T("request",`Proxy error for ${w}: ${Y}`,t),E)Lr(E,h);return new Response(`Proxy Error: ${Y}`,{status:502})}finally{if(E)h.activeConnections--}};return async(f,l)=>{try{return await n(f,l)}catch(c){return T("request",`Unhandled proxy handler error: ${c}`,t),new Response("Bad Gateway",{status:502})}}}function y0(i){let t=new WeakMap,r=ZY();return{open(n){let{targetUrl:f,forwardHeaders:l}=n.data,c;try{c=new WebSocket(f,{headers:l})}catch(w){T("ws",`failed to open upstream ${f}: ${w}`,i),n.close(1011,"upstream connect failed");return}c.binaryType="arraybuffer";let $={upstream:c,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,$),c.addEventListener("open",()=>{$.upstreamOpen=!0;for(let w of $.pending)c.send(w);$.pending=[],$.pendingBytes=0}),c.addEventListener("message",(w)=>{n.send(w.data)}),c.addEventListener("close",(w)=>{try{n.close(w.code||1000,w.reason||"")}catch{}}),c.addEventListener("error",()=>{T("ws",`upstream error for ${f}`,i);try{n.close(1011,"upstream error")}catch{}})},message(n,f){let l=t.get(n);if(!l)return;let c=typeof f==="string"?f:new Uint8Array(f);if(l.upstreamOpen){l.upstream.send(c);return}let $=typeof c==="string"?Buffer.byteLength(c):c.byteLength;if(l.pendingBytes+$>r){T("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,i);try{n.close(1009,"buffer limit")}catch{}try{l.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}l.pending.push(c),l.pendingBytes+=$},close(n,f,l){let c=t.get(n);if(!c)return;t.delete(n);try{c.upstream.close(f||1000,l||"")}catch{}}}}import*as Dh from"node:fs";import*as bh from"node:path";var Vh="/.well-known/acme-challenge/";function Qh(i,t){if(!i||!t.startsWith(Vh))return null;let r=t.slice(Vh.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return Dh.readFileSync(bh.join(i,r),"utf8")}catch{return null}}function If(i){return i.startsWith("*.")}function h0(i,t){if(!If(t))return!1;let r=t.slice(1);return i.length>r.length&&i.endsWith(r)}function Ph(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[l,c]of i){if(!If(l))continue;if(h0(t,l)){let $=l.length-1;if($>f)f=$,n=c}}return n}function zt(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function tm(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function u0(i){let t=new Map;for(let n of i){let f=zt(n.path),l=t.get(n.host);if(!l)l=new Map,t.set(n.host,l);l.set(f,n.route)}let r=new Map;for(let[n,f]of t){let l=[];for(let[c,$]of f)l.push({path:c,route:$});l.sort((c,$)=>$.path.length-c.path.length),r.set(n,l)}return r}function e0(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[l,c]of i){if(!If(l))continue;if(h0(t,l)){let $=l.length-1;if($>f)f=$,n=c}}return n}function A0(i,t,r){let n=e0(i,t);if(!n)return;for(let f of n)if(tm(r,f.path))return f.route;return}import*as dr from"node:fs/promises";import*as E0 from"node:path";function rm(i){if(!i.endsWith(".crt"))return null;let t=i.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function nm(i,t,r,n){try{let[f,l]=await Promise.all([dr.readFile(t,"utf8"),dr.readFile(r,"utf8")]);return{serverName:i,cert:f,key:l}}catch(f){return T("sni",`skipping ${i}: ${f.message}`,n),null}}async function T0(i,t){let r=new Map;if(i.certsDir){let f=[];try{f=await dr.readdir(i.certsDir)}catch(l){T("sni",`certsDir read failed (${i.certsDir}): ${l.message}`,t)}for(let l of f){let c=rm(l);if(!c)continue;let $=l.slice(0,-4);r.set(c,{certPath:E0.join(i.certsDir,l),keyPath:E0.join(i.certsDir,`${$}.key`)})}}if(i.domains)for(let[f,l]of Object.entries(i.domains))r.set(f,l);let n=[];for(let[f,l]of r){let c=await nm(f,l.certPath,l.keyPath,t);if(c)n.push(c)}return n}import*as Rt from"node:fs/promises";import*as Y0 from"node:path";var fm=60000,vh=4096;function lm(i,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return i===n||i.endsWith(`.${n}`)})}function Zh(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class Kf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??On,this.issuer=i.issuer??Hl,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??fm;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!Zh(i))return!1;if(lm(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return T("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!Zh(i))return!1;let t=this.inFlight.get(i);if(t)return t;let r=this.negativeCache.get(i);if(r!==void 0&&Date.now()<r)return T("on-demand",`${i} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,n),n}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return T("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{T("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let r={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,r),this.negativeCache.delete(i),T("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),T("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=vh){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=vh){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:r}=this.pathsFor(i);try{let[n,f]=await Promise.all([Rt.readFile(t,"utf8"),Rt.readFile(r,"utf8")]),l={serverName:i,cert:n,key:f};return this.certs.set(i,l),T("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:Y0.join(this.certsDir,`${i}.crt`),keyPath:Y0.join(this.certsDir,`${i}.key`)}}async persist(i,t,r){await Rt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:f}=this.pathsFor(i);await Promise.all([Rt.writeFile(n,t,"utf8"),Rt.writeFile(f,r,{encoding:"utf8",mode:384})])}}import{existsSync as cm,readdirSync as $m,readFileSync as wm,statSync as ym}from"node:fs";import{homedir as iu}from"node:os";import{isAbsolute as hm,join as Er}from"node:path";var tu=["~/Code"],ru=["localhost","test"],um=1800000,m0={dirExists:(i)=>{try{return ym(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return cm(i)}catch{return!1}},readText:(i)=>{try{return wm(i,"utf8")}catch{return null}}};function B0(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Er(t,i.slice(2));return i}function em(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function oh(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function Am(i,t){for(let r of t){let n=`.${r}`;if(i.endsWith(n)){let f=i.slice(0,-n.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function Em(i,t){let r=t.readText(Er(i,"rpx.site.json"));if(r)try{let f=JSON.parse(r);if(f&&typeof f==="object")return f}catch{}let n=t.readText(Er(i,"package.json"));if(n)try{let f=JSON.parse(n);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function Tm(i){let t=i.selfRegisters??!1;return{command:i.command,env:i.env,urlEnv:i.urlEnv,selfRegisters:t,routes:i.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function Ym(i,t){let r=Em(i,t);if(r?.command)return Tm(r);let n=t.fileExists(Er(i,"buddy")),f=t.readText(Er(i,"package.json")),l=null;if(f)try{l=JSON.parse(f)}catch{l=null}let c={...l?.dependencies??{},...l?.devDependencies??{}};if(n||Object.keys(c).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(l?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function C0(i,t={}){let r={dirExists:t.dirExists??m0.dirExists,fileExists:t.fileExists??m0.fileExists,readText:t.readText??m0.readText},n=t.detect??Ym,f=t.homeDir??iu(),l=i.tlds??ru,c=(i.roots??tu).map((e)=>B0(e,f)),$=i.idleTimeoutMs??um,w=new Map;for(let e of i.sites??[])w.set(e.to,e);let y=(e)=>e.idleTimeoutMs??$;function h(e){let A=Ph(w,e);if(!A)return null;let m=hm(A.dir)?A.dir:B0(A.dir,f),E=A.selfRegisters??!1,Y=A.routes??[];if(!E&&Y.length===0)Y=n(m,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let B=ph({...A.env??{}},void 0,e);return{host:e,id:oh(e),dir:m,command:A.command,env:B,routes:Y,selfRegisters:E,idleTimeoutMs:y(A),source:"config"}}function u(e){let A=Am(e,l);if(!A)return null;for(let m of c){let E=Er(m,A);if(!r.dirExists(E))continue;let Y=n(E,r);if(!Y)continue;let B=Y.selfRegisters??!1;return{host:e,id:oh(e),dir:E,command:Y.command,env:ph({...Y.env??{}},Y.urlEnv,e),routes:B?[]:Y.routes??[],selfRegisters:B,idleTimeoutMs:$,source:"discovered"}}return null}return{resolve(e){let A=em(e);if(!A)return null;return h(A)??u(A)}}}function mm(i){try{return $m(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function Hj(i,t={}){let r=t.homeDir??iu(),n=i.tlds??ru,f=(i.roots??tu).map((u)=>B0(u,r)),l=t.readdir??mm,c=C0(i,t),$=[],w=new Set,y=(u)=>{if(u&&!w.has(u.host))w.add(u.host),$.push(u)};for(let u of i.sites??[])if(!u.to.includes("*"))y(c.resolve(u.to));let h=n[0]??"localhost";for(let u of f)for(let e of l(u))y(c.resolve(`${e}.${h}`));return $}function ph(i,t,r){if(!t)return i;let n=`https://${r}`;for(let f of t)if(i[f]===void 0)i[f]=n;return i}import{closeSync as wu,openSync as Um,readFileSync as jm}from"node:fs";import*as yu from"node:fs/promises";import{spawn as Sm}from"node:child_process";import{homedir as am}from"node:os";import*as Vr from"node:path";import*as di from"node:process";import*as zf from"node:net";function fu(i,t,r){return T("port",`Checking if port ${i} is in use on ${t}`,r),new Promise((n)=>{let f=zf.createServer(),l=setTimeout(()=>{T("port",`Checking port ${i} timed out, assuming it's in use`,r),f.close(),n(!0)},3000);f.once("error",(c)=>{if(clearTimeout(l),c.code==="EADDRINUSE")T("port",`Port ${i} is in use`,r),n(!0);else T("port",`Error checking port ${i}: ${c.message}`,r),n(!0)}),f.once("listening",()=>{clearTimeout(l),T("port",`Port ${i} is available`,r),f.close(),n(!1)});try{f.listen(i,t)}catch(c){clearTimeout(l),T("port",`Exception checking port ${i}: ${c}`,r),n(!0)}})}async function s0(i,t,r,n=50){T("port",`Finding available port starting from ${i} (max attempts: ${n})`,r);let f=i,l=0;while(l<n){if(l++,!await fu(f,t,r))return T("port",`Found available port: ${f} after ${l} attempts`,r),f;T("port",`Port ${f} is in use, trying ${f+1} (attempt ${l}/${n})`,r),f++}throw Error(`Unable to find available port after ${n} attempts starting from ${i}`)}function nu(i,t,r=5000,n){return T("port",`Testing connection to ${t}:${i}`,n),new Promise((f)=>{let l=zf.connect({host:t,port:i,timeout:r});l.once("connect",()=>{T("port",`Successfully connected to ${t}:${i}`,n),l.end(),f(!0)}),l.once("timeout",()=>{T("port",`Connection to ${t}:${i} timed out`,n),l.destroy(),f(!1)}),l.once("error",(c)=>{T("port",`Failed to connect to ${t}:${i}: ${c.message}`,n),l.destroy(),f(!1)})})}class lu{usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,r=50){this.hostname=i,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await fu(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await nu(i,this.hostname,3000,this.verbose))return T("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let r=await s0(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await nu(r,this.hostname,3000,this.verbose))if(r<i+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(i){T("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var gj=new lu;import*as Of from"node:fs";import*as Ci from"node:fs/promises";import{homedir as Bm}from"node:os";import*as R0 from"node:path";import*as Gf from"node:process";var Cm=/^[a-zA-Z0-9._-]+$/;function Ut(){return R0.join(Bm(),".stacks","rpx","registry.d")}function U0(i){return typeof i==="string"&&i.length>0&&i.length<=128&&Cm.test(i)}function j0(i,t){if(!U0(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return R0.join(i,`${t}.json`)}function xi(i){if(!Number.isInteger(i)||i<=0)return!1;try{return Gf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function cu(i){if(!i||typeof i!=="object")return!1;let t=i,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",l=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&U0(t.id)&&(n||f)&&typeof t.to==="string"&&t.to.length>0&&l&&r&&typeof t.createdAt==="string"}async function sm(i){await Ci.mkdir(i,{recursive:!0})}async function $u(i,t=Ut(),r){if(!cu(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await sm(t);let n=j0(t,i.id),f=`${n}.tmp.${Gf.pid}.${Date.now()}`,l=JSON.stringify(i,null,2);try{await Ci.writeFile(f,l,{encoding:"utf8",mode:420}),await Ci.rename(f,n),T("registry",`wrote entry ${i.id} → ${n}`,r)}catch(c){throw await Ci.unlink(f).catch(()=>{}),c}}async function S0(i,t=Ut(),r){let n=j0(t,i);try{await Ci.unlink(n),T("registry",`removed entry ${i}`,r)}catch(f){if(f.code!=="ENOENT")throw f}}async function Rm(i,t=Ut(),r){let n=j0(t,i);try{let f=await Ci.readFile(n,"utf8"),l=JSON.parse(f);if(!cu(l))return T("registry",`entry ${i} failed validation, removing`,r),await Ci.unlink(n).catch(()=>{}),null;return l}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return T("registry",`entry ${i} has invalid JSON, removing`,r),await Ci.unlink(n).catch(()=>{}),null;throw f}}async function ht(i=Ut(),t){let r;try{r=await Ci.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let n=[];for(let f of r){if(!f.endsWith(".json"))continue;let l=f.slice(0,-5);if(!U0(l))continue;let c=await Rm(l,i,t);if(c)n.push(c)}return n}async function kr(i=Ut(),t){let r=await ht(i,t),n=0;for(let f of r){if(f.pid===void 0)continue;if(!xi(f.pid))T("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await S0(f.id,i,t).catch(()=>{}),n++}return n}function Mf(i,t={}){let r=t.dir??Ut(),n=t.debounceMs??100,f=t.pollMs??Math.max(n*2,250),l=t.verbose;Of.mkdirSync(r,{recursive:!0});let c=null,$=!1,w=null,y=!1,h=(Y)=>{return JSON.stringify(Y.map((B)=>({id:B.id,from:B.from,to:B.to,path:B.path,pid:B.pid,pathRewrites:B.pathRewrites,cleanUrls:B.cleanUrls,changeOrigin:B.changeOrigin,static:B.static,loadBalancer:B.loadBalancer})).sort((B,C)=>B.id.localeCompare(C.id)))},u=()=>{if(c=null,$)return;ht(r,l).then((Y)=>{return w=h(Y),i(Y)}).catch((Y)=>{T("registry",`watcher onChange failed: ${Y}`,l)})},e=()=>{if($)return;if(c)clearTimeout(c);c=setTimeout(u,n)},m=setInterval(()=>{if($||y)return;y=!0,ht(r,l).then((Y)=>{if(h(Y)!==w)e()}).catch((Y)=>{T("registry",`watcher poll failed: ${Y}`,l)}).finally(()=>{y=!1})},f),E=Of.watch(r,{persistent:!0},(Y,B)=>{if(B&&/\.tmp\.\d+\.\d+$/.test(B))return;e()});return E.on("error",(Y)=>{T("registry",`watcher error: ${Y}`,l)}),e(),{close:()=>{if($=!0,c)clearTimeout(c);clearInterval(m),E.close()}}}var Nm=120000,Fm=200,Xm=30000,Wm=3000,Jm=4000;class N0{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??Ut(),this.rpxDir=i.rpxDir??Vr.join(am(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??Nm,this.pollIntervalMs=i.pollIntervalMs??Fm,this.restartDelayMs=i.restartDelayMs??Wm,this.killGraceMs=i.killGraceMs??Jm,this.launch=i.launcher??Im(this.verbose),this.probePort=i.probePort??_m,this.pickPort=i.pickPort??((r)=>s0(r,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??$u,this.removeEntry=i.removeEntry??S0;let t=i.reapIntervalMs??Xm;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let r=this.resolver.resolve(i);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let $ of i.routes){if(t.has($.portEnv))continue;let w=await this.pickPort($.defaultPort??3000);t.set($.portEnv,w)}let r=Vr.join(this.rpxDir,"sites",`${i.id}.log`);await yu.mkdir(Vr.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(i,t),f=null,l;try{f=this.launch({command:i.command,cwd:i.dir,env:n,logPath:r})}catch($){l=`failed to spawn: ${$.message}`}let c={site:i,status:l?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:l?this.now():0,error:l,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,c),l)return X.warn(`rpx: site ${i.host} ${l}`),c;return X.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then(($)=>this.onProcessExit(c,$)).catch(()=>{}),c.ready=this.driveReadiness(c).catch(($)=>{T("sites",`readiness loop for ${i.host} threw: ${$}`,this.verbose)}),c}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){X.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let r of i.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<r&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await n()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",X.success(`rpx: ${t.host} ready`);return}await a0(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let r=i.routes.filter((f)=>f.readyGate??zt(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let f of n)if(!await this.probePort(f))return!1;return n.length>0}}async publishRoutes(i){let{site:t,ports:r}=i;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((w)=>zt(w.path)==="/")??t.routes[0],f=r.get(n.portEnv);if(f===void 0)return;let l=[];for(let w of t.routes){if(w===n)continue;let y=r.get(w.portEnv);if(y===void 0)continue;l.push({from:zt(w.path),to:`localhost:${y}`,stripPrefix:w.stripPrefix??!1})}let c={id:t.id,from:`localhost:${f}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:l.length>0?l:void 0,pid:i.handle?.pid};await this.writeEntry(c,this.registryDir,this.verbose),i.routeIds=[t.id];let $=this.now()+2000;while(this.now()<$&&!this.isHostRoutable(t.host))await a0(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),X.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let r={};for(let[n,f]of Object.entries(di.env))if(typeof f==="string")r[n]=f;Object.assign(r,i.env);for(let[n,f]of t)r[n]=String(f);return r.RPX_SITE_HOST=i.host,r.RPX_SITE_URL=`https://${i.host}`,r}readLogTail(i,t=40){try{return jm(i.logPath,"utf8").split(`
|
|
170
|
-
`).slice(-t).join(`
|
|
171
|
-
`).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),X.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),a0(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,r]of this.sites){let n=r.site.idleTimeoutMs;if(n<=0)continue;let f=i-r.lastAccess;if((r.status==="ready"||i-r.startedAt>this.startupTimeoutMs)&&f>n)T("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function a0(i){return new Promise((t)=>setTimeout(t,i))}async function _m(i){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function Im(i){let t=Km();return({command:r,cwd:n,env:f,logPath:l})=>{let c=Um(l,"a");try{let $=Sm("sh",["-c",r],{cwd:n,env:f,detached:!0,stdio:["ignore",c,c],...t?{uid:t.uid,gid:t.gid}:{}}),w=$.pid;if(w===void 0)throw Error("spawn returned no pid");let y=new Promise((h)=>{$.once("exit",(u)=>{h(u)}),$.once("error",()=>{h(null)})}).finally(()=>{try{wu(c)}catch{}});return T("sites",`spawned pid ${w}: sh -c ${r} (cwd ${n})`,i),{pid:w,exited:y,stop:(h="SIGTERM")=>{try{di.kill(-w,h)}catch{try{$.kill(h)}catch{}}}}}catch($){try{wu(c)}catch{}throw $}}}function Km(){if(di.platform==="win32")return null;if(!(typeof di.getuid==="function"&&di.getuid()===0))return null;let t=Number.parseInt(di.env.SUDO_UID??"",10),r=Number.parseInt(di.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}function Tr(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var zm=`
|
|
172
|
-
:root { color-scheme: light dark }
|
|
173
|
-
* { box-sizing: border-box }
|
|
174
|
-
body {
|
|
175
|
-
margin: 0; min-height: 100vh; display: grid; place-items: center;
|
|
176
|
-
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
177
|
-
background: #0b0c0f; color: #e7e9ee;
|
|
178
|
-
}
|
|
179
|
-
.card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
|
|
180
|
-
.row { display: flex; align-items: center; gap: .75rem; }
|
|
181
|
-
h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
|
|
182
|
-
p { margin: .5rem 0 0; color: #9aa1ad }
|
|
183
|
-
code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
|
|
184
|
-
pre {
|
|
185
|
-
margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
|
|
186
|
-
background: #16181d; border: 1px solid #23262d; border-radius: 8px;
|
|
187
|
-
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
|
|
188
|
-
white-space: pre-wrap; word-break: break-word;
|
|
189
|
-
}
|
|
190
|
-
.spinner {
|
|
191
|
-
width: 16px; height: 16px; border-radius: 50%;
|
|
192
|
-
border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
|
|
193
|
-
animation: spin .8s linear infinite;
|
|
194
|
-
}
|
|
195
|
-
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
196
|
-
@keyframes spin { to { transform: rotate(360deg) } }
|
|
197
|
-
`;function hu(i,t,r){return`<!doctype html>
|
|
198
|
-
<html lang="en">
|
|
199
|
-
<head>
|
|
200
|
-
<meta charset="utf-8">
|
|
201
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
202
|
-
${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
|
|
203
|
-
<title>${Tr(i)}</title>
|
|
204
|
-
<style>${zm}</style>
|
|
205
|
-
</head>
|
|
206
|
-
<body><main class="card">${t}</main></body>
|
|
207
|
-
</html>`}function uu(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),r=i.logTail?`<pre>${Tr(i.logTail)}</pre>`:"",n=`
|
|
208
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${Tr(i.host)}…</h1></div>
|
|
209
|
-
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
210
|
-
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
211
|
-
<p>Booting for ${t}s.</p>
|
|
212
|
-
${r}`;return new Response(hu(`Starting ${i.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function eu(i){let t=i.logTail?`<pre>${Tr(i.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
|
|
213
|
-
<div class="row"><div class="dot"></div><h1>${Tr(i.host)} failed to start</h1></div>
|
|
214
|
-
<p>${Tr(i.error)}</p>
|
|
215
|
-
${t}
|
|
216
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(hu(`${i.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var Om=5000;function si(){return bi.join(Bu(),".stacks","rpx")}function gf(i=si()){return bi.join(i,"daemon.pid")}async function mr(i=si()){try{let t=await Ai.readFile(gf(i),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Gm(i=si()){let t=await mr(i);return t!==null&&xi(t)}async function Cu(i=si()){await Ai.mkdir(i,{recursive:!0});let t=gf(i);while(!0){try{let n=await Ai.open(t,"wx");try{await n.write(`${s.pid}
|
|
217
|
-
`)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await mr(i);if(r!==null&&xi(r))throw Error(`rpx daemon already running (pid=${r})`);await Ai.unlink(t).catch(()=>{})}}async function Yr(i=si()){await Ai.unlink(gf(i)).catch(()=>{})}var qf=new Map;function Lf(i){for(let[t,r]of qf)if(!i.has(t))ah(r),qf.delete(t)}function su(i){let t=i.cleanUrls??!1,r=zt(i.path),n=Xh(i.auth);if(i.static)return{static:qh(i.static,t),cleanUrls:t,basePath:r,auth:n};let f=i.from??"localhost:1",l=Rh(f),c=new URL(l.startsWith("http")?l:`http://${l}`),$=qf.get(i.id);if(!$)$=Uh(f,i.loadBalancer),Sh($),qf.set(i.id,$);return{sourceHost:c.host,upstreamPool:$,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:r,auth:n}}function Mm(i){return i.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??i[0]??"rpx.localhost"}async function Hf(i,t,r=[],n=!1){let f=await ht(t,i.verbose),l=[...new Set([...f.map((h)=>h.to).filter(Boolean),...r])],c=Mm(l),$=[...new Set([c,...l,"rpx.localhost"])],w=mh(l,c,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let y=await f0(w);if(y&&(n||!Qc(t0,$)))T("daemon",`regenerating shared cert for host(s): ${$.join(", ")}`,i.verbose),n0(),y=null;if(!y)T("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Ch({...w,forceRegenerate:!0}),y=await f0(w);if(!y)throw Error("failed to bootstrap TLS for rpx daemon");return y}async function Hm(i,t,r,n){let f=s.env.SUDO_PASSWORD,l=s.env.HOME??Bu(),c=[s.execPath,...s.argv.slice(1)],$=[`HOME=${l}`,`PATH=${s.env.PATH??""}`];if(n)$.push("RPX_VERBOSE=1");for(let[m,E]of Object.entries(s.env))if(E!==void 0&&m!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(m))$.push(`${m}=${E}`);let w=f?["-S","-p","","env",...$,...c]:["-n","env",...$,...c];T("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,n);let y=mu("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,u=null;if(y.once("error",(m)=>{h=m}),y.once("exit",(m)=>{u=m??0}),f&&y.stdin)y.stdin.write(`${f}
|
|
218
|
-
`),y.stdin.end();y.unref();let e=gf(i),A=Date.now()+15000;while(Date.now()<A){if(h)throw h;let m=await mr(i);if(m!==null&&xi(m)){if(n)X.success(`rpx daemon elevated to root (pid=${m}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:e,done:Promise.resolve(),stop:async()=>{try{s.kill(m,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(u!==null&&u!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${u}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((E)=>setTimeout(E,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var Au=!1;function F0(){if(Au)return;Au=!0,s.on("uncaughtException",(i)=>{X.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),s.on("unhandledRejection",(i)=>{X.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function Ru(i,t,r){let n;try{n=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??n.hostname).split(":")[0];if(n.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let l=t.challengeStore.handlePath(n.pathname);if(l!==void 0)return new Response(l,{status:200,headers:{"content-type":"text/plain"}})}if(r){let l=Qh(r,n.pathname);if(l!=null)return new Response(l,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${n.pathname}${n.search}`}})}async function RS(i={}){F0();let t=i.verbose??!1,r=i.rpxDir??si(),n=i.registryDir??bi.join(r,"registry.d"),f=i.httpsPort??443,l=i.httpPort??80,c=i.hostname??"0.0.0.0",$=i.gcIntervalMs??Om;if(s.env.RPX_DAEMON_WORKER==="1")return gm({rpxDir:s.env.RPX_WORKER_RPXDIR??r,registryDir:s.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(s.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:s.env.RPX_WORKER_HOSTNAME??c,verbose:s.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||l>0&&l<1024,y=typeof s.getuid==="function"&&s.getuid()===0;if(s.platform!=="win32"&&w&&!y)return Hm(r,f,l,t);let h=Math.max(1,i.workers??(Number.parseInt(s.env.RPX_WORKERS??"",10)||1));if(h>1){if(i.onDemandSites?.enabled)X.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return xm(i,{rpxDir:r,registryDir:n,httpsPort:f,httpPort:l,hostname:c,verbose:t,gcIntervalMs:$,workers:h})}let u=await Cu(r),e=new Map,A=(R,W)=>A0(e,R,W);function m(R){e=u0(R.map((Di)=>({host:Di.to,path:Di.path,route:su(Di)}))),Lf(new Set(R.map((Di)=>Di.id)));let W=Array.from(e.keys());T("daemon",`routing table now covers ${W.length} host(s): ${W.join(", ")||"<empty>"}`,t)}await kr(n,t).catch((R)=>{T("daemon",`initial gc failed: ${R}`,t)});let E=await ht(n,t);m(E),await Cr({rpxDir:r,verbose:t}).catch((R)=>{T("daemon",`DNS reconcile on start failed: ${R}`,t)}),await Dr(E,{rpxDir:r,verbose:t,ownerPid:s.pid}).catch((R)=>{T("daemon",`DNS setup on start failed: ${R}`,t)});let Y=[];if(i.productionCerts){if(Y=await T0(i.productionCerts,t),t&&Y.length>0)X.info(`SNI: serving ${Y.length} real cert(s): ${Y.map((R)=>R.serverName).join(", ")}`)}let B=new Set,C=null,a;if(i.onDemandSites?.enabled){if(C=new N0({resolver:C0(i.onDemandSites),registryDir:n,rpxDir:r,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(R)=>e0(e,R)!==void 0,onSiteActivating:(R)=>{Ft(R)}}),a=async(R)=>{let W=await C.onRequest(R);switch(W.kind){case"ready":return{retry:!0};case"starting":return uu({host:W.host,sinceMs:W.sinceMs,logTail:W.logTail});case"failed":return eu({host:W.host,error:W.error,logTail:W.logTail});case"unknown":default:return}},t)X.info("rpx: on-demand sites enabled")}let N=w0(A,t,a),j=y0(t),F=null;if(Y.length===0)F=await Hf(i,n);let M=i.onDemandTls,o=M?.enabled?new Kf({config:M,certsDir:M.certsDir??i.productionCerts?.certsDir??bi.join(r,"on-demand-certs"),initial:Y,verbose:t,onCertAdded:(R)=>{Gt(R)}}):null;function ki(R){if(R.length>0)return R.map((W)=>({serverName:W.serverName,cert:W.cert,key:W.key}));return{key:F.key,cert:F.cert,ca:F.ca,requestCert:!1,rejectUnauthorized:!1}}function Pr(R){return Bun.serve({port:f,hostname:c,reusePort:Yu(),tls:ki(R),fetch(W,Di){return N(W,Di)},websocket:j,error(W){return T("daemon",`https server error: ${W}`,t),new Response(`Server Error: ${W.message}`,{status:500})}})}let St=(R)=>[...new Set(R.map((W)=>W.to).filter(Boolean))],Ot=(R)=>{if(!F)return Y;return Yh([...St(R),...B,"rpx.localhost"],F)},et=Pr(o?o.sniEntries():Y.length>0?Y:Ot(E)),at=null,Nt=!1;async function Gt(R){if(Vi)return;if(at=R,Nt)return;Nt=!0;try{while(!Vi&&at){let W=at;at=null,T("daemon",`rebuilding :443 with ${W.length} SNI cert(s)`,t),et.stop(!1);let Di,Qf=!1,M0=60,Gu=500;for(let Pf=0;!Vi&&!Qf;Pf++)try{et=Pr(W),Qf=!0;break}catch(Mu){if(Di=Mu,Pf>=M0)break;await new Promise((Hu)=>setTimeout(Hu,Math.min(25*2**Math.min(Pf,4),Gu)))}if(!Qf)X.error(`rpx: CRITICAL — could not rebind :443 after ${M0} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Di?.message}`)}}finally{Nt=!1}}let Qi=null;if(l>0)Qi=Bun.serve({port:l,hostname:c,fetch(R){return Ru(R,o,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)X.success(`rpx daemon listening on https://${c}:${f}${Qi?` (http→https on :${l})`:""}`),X.info(`pid file: ${u}`),X.info(`registry: ${n}`);async function J(R){if(Vi||Y.length>0||o||!F)return;try{F=await Hf(i,n,[...B]),await Gt(Ot(R))}catch(W){T("daemon",`TLS sync on registry change failed: ${W}`,t)}}async function Ft(R){if(Vi||Y.length>0||o||!F||!R)return;if(B.has(R))return;B.add(R);try{F=await Hf(i,n,[...B],!0);let W=await ht(n,t);await Gt(Ot(W))}catch(W){T("daemon",`dev cert refresh for ${R} failed: ${W}`,t)}}let Df=Mf((R)=>{m(R),J(R),Dr(R,{rpxDir:r,verbose:t,ownerPid:s.pid}).catch((W)=>{T("daemon",`DNS sync on registry change failed: ${W}`,t)})},{dir:n,verbose:t}),Mt=setInterval(()=>{kr(n,t).then((R)=>{if(R>0)T("daemon",`gc reaped ${R} stale entries`,t)}).catch((R)=>{T("daemon",`periodic gc failed: ${R}`,t)})},$);if(typeof Mt.unref==="function")Mt.unref();let Vi=!1,sr,Ht=new Promise((R)=>{sr=R});async function bf(){if(Vi)return Ht;if(Vi=!0,clearInterval(Mt),Df.close(),await C?.stopAll().catch((R)=>{T("daemon",`site supervisor stopAll failed: ${R}`,t)}),et.stop(!1),Qi?.stop(!1),await Br({rpxDir:r,verbose:t}).catch((R)=>{T("daemon",`DNS teardown failed: ${R}`,t)}),Lf(new Set),await Yr(r),t)X.info("rpx daemon stopped");return sr(),Ht}let G0=(R)=>{T("daemon",`received ${R}, shutting down`,t),bf().catch(()=>{})};return s.once("SIGINT",G0),s.once("SIGTERM",G0),{stop:bf,done:Ht,httpsPort:typeof et.port==="number"?et.port:f,httpPort:Qi&&typeof Qi.port==="number"?Qi.port:l,pidPath:u,ensureCert:(R)=>o?o.ensureCert(R):Promise.resolve(!1),listSites:()=>C?.list()??[]}}function X0(i){return bi.join(i,"cluster-sni.json")}async function Eu(i,t,r){let n=X0(i),f=`${n}.${s.pid}.tmp`;await Ai.writeFile(f,JSON.stringify({sni:t,dev:r}),"utf8"),await Ai.rename(f,n)}async function Tu(i){try{return JSON.parse(await Ai.readFile(X0(i),"utf8"))}catch{return{sni:[],dev:null}}}function qm(i){if(i.sni.length>0)return i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));if(i.dev)return{key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function Lm(){let i=s.execPath,t=s.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let r=bi.basename(i).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&s.argv[1])return[i,s.argv[1],"daemon:start"];return[i,"daemon:start"]}async function gm(i){F0();let{rpxDir:t,registryDir:r,httpsPort:n,hostname:f,verbose:l}=i,c=new Map,$=(j,F)=>A0(c,j,F),w=(j)=>{c=u0(j.map((F)=>({host:F.to,path:F.path,route:su(F)}))),Lf(new Set(j.map((F)=>F.id)))};w(await ht(r,l));let y=w0($,l),h=y0(l),u=!1,e=(j)=>Bun.serve({port:n,hostname:f,reusePort:!0,tls:qm(j),fetch(F,M){return y(F,M)},websocket:h,error(F){return T("daemon",`worker https error: ${F}`,l),new Response(`Server Error: ${F.message}`,{status:500})}}),A=e(await Tu(t));async function m(){if(u)return;let j=await Tu(t),F=null;for(let o=0;o<20&&!u;o++)try{F=e(j);break}catch{await new Promise((ki)=>setTimeout(ki,25))}if(!F){T("daemon","worker reloadTls: could not bind new listener; keeping current",l);return}let M=A;A=F,M.stop(!1)}let E=Mf((j)=>w(j),{dir:r,verbose:l}),Y=()=>{m().catch(()=>{})};s.on("SIGHUP",Y);let B,C=new Promise((j)=>{B=j});async function a(){if(u)return C;return u=!0,s.off("SIGHUP",Y),E.close(),A.stop(!1),Lf(new Set),B(),C}let N=()=>{a().then(()=>s.exit(0)).catch(()=>s.exit(0))};if(s.once("SIGTERM",N),s.once("SIGINT",N),l)X.success(`rpx worker (pid ${s.pid}) serving :${n}`);return{stop:a,done:C,httpsPort:typeof A.port==="number"?A.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function xm(i,t){F0();let{rpxDir:r,registryDir:n,httpsPort:f,httpPort:l,hostname:c,verbose:$,gcIntervalMs:w,workers:y}=t,h=await Cu(r),u=[];if(i.productionCerts)u=await T0(i.productionCerts,$);let e=null;if(u.length===0)e=await Hf(i,n);let A=e?{key:e.key,cert:e.cert,ca:Array.isArray(e.ca)?e.ca.join(`
|
|
219
|
-
`):e.ca}:null,m=!1,E=[];function Y(J){for(let Ft of E)try{Ft.kill(J)}catch{}}async function B(J){await Eu(r,J,A),Y("SIGHUP")}let C=i.onDemandTls,a=C?.enabled?new Kf({config:C,certsDir:C.certsDir??i.productionCerts?.certsDir??bi.join(r,"on-demand-certs"),initial:u,verbose:$,onCertAdded:(J)=>{B(J)}}):null;await Eu(r,a?a.sniEntries():u,A);let N=await ht(n,$);await Cr({rpxDir:r,verbose:$}).catch((J)=>{T("daemon",`DNS reconcile on start failed: ${J}`,$)}),await Dr(N,{rpxDir:r,verbose:$,ownerPid:s.pid}).catch((J)=>{T("daemon",`DNS setup on start failed: ${J}`,$)}),await kr(n,$).catch(()=>{});let j=Mf((J)=>{Dr(J,{rpxDir:r,verbose:$,ownerPid:s.pid}).catch((Ft)=>{T("daemon",`DNS sync on registry change failed: ${Ft}`,$)})},{dir:n,verbose:$}),F=setInterval(()=>{kr(n,$).catch(()=>{})},w);F.unref?.();let M=null;if(l>0)M=Bun.serve({port:l,hostname:c,fetch(J){return Ru(J,a,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let o=10,ki=60000,Pr=30000,St=0,Ot=Date.now();function et(){if(m)return;let J={...s.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:c,RPX_WORKER_VERBOSE:$?"1":"0"},Ft=Bun.spawn(Lm(),{env:J,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(Df,Mt){if(m)return;let Vi=E.indexOf(Df);if(Vi!==-1)E.splice(Vi,1);let sr=Date.now();if(sr-Ot>ki)Ot=sr,St=0;if(St++,St>o){X.error(`rpx: worker keeps exiting (code ${Mt}); giving up after ${o} restarts in ${Math.round(ki/1000)}s`);return}let Ht=Math.min(Pr,100*2**Math.min(St,8));T("daemon",`worker exited (code ${Mt}); respawning in ${Ht}ms (restart ${St}/${o})`,$),setTimeout(et,Ht).unref?.()}});E.push(Ft)}for(let J=0;J<y;J++)et();if($)X.success(`rpx coordinator listening on https://${c}:${f} via ${y} worker(s)${M?` (http→https on :${l})`:""}`),X.info(`pid file: ${h}`);let at,Nt=new Promise((J)=>{at=J});async function Gt(){if(m)return Nt;if(m=!0,clearInterval(F),j.close(),M?.stop(!1),Y("SIGTERM"),await Promise.race([Promise.all(E.map((J)=>J.exited)),new Promise((J)=>setTimeout(J,3000))]),Y("SIGKILL"),await Br({rpxDir:r,verbose:$}).catch((J)=>{T("daemon",`DNS teardown failed: ${J}`,$)}),await Yr(r),await Ai.unlink(X0(r)).catch(()=>{}),$)X.info("rpx coordinator stopped");return at(),Nt}let Qi=(J)=>{T("daemon",`coordinator received ${J}, shutting down`,$),Gt().catch(()=>{})};return s.once("SIGINT",Qi),s.once("SIGTERM",Qi),{stop:Gt,done:Nt,httpsPort:f,httpPort:l,pidPath:h,ensureCert:(J)=>a?a.ensureCert(J):Promise.resolve(!1),listSites:()=>[]}}function dm(){let i=s.execPath,t=bi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&s.argv[1])return[i,s.argv[1],"daemon:start"];return[i,"daemon:start"]}async function US(i={}){let t=i.rpxDir??si(),r=i.verbose??!1;await Cr({rpxDir:t,verbose:r}).catch((h)=>{T("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,r)});let n=await mr(t);if(n!==null&&xi(n))return T("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)T("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await Yr(t);await Ai.mkdir(t,{recursive:!0});let f=i.spawnCommand??dm();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");T("daemon",`spawning daemon: ${f.join(" ")}`,r);let l=mu(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??s.cwd(),env:i.spawnEnv?{...s.env,...i.spawnEnv}:s.env});l.unref();let c=null;l.once("error",(h)=>{c=h});let $=i.startupTimeoutMs??5000,w=i.pollIntervalMs??50,y=Date.now()+$;while(Date.now()<y){if(c)throw c;let h=await mr(t);if(h!==null&&xi(h))return T("daemon",`daemon registered with pid=${h}`,r),{pid:h,spawned:!0};await new Promise((u)=>setTimeout(u,w))}if(c)throw c;throw Error(`rpx daemon failed to start within ${$}ms (rpxDir=${t})`)}async function jS(i={}){let t=i.rpxDir??si(),r=i.verbose??!1,n=i.timeoutMs??5000,f=i.pollIntervalMs??50,l=i.forceAfterTimeout??!0,c=await mr(t);if(c===null||!xi(c)){if(c!==null)await Yr(t);return await Cr({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:c,forced:!1}}try{s.kill(c,"SIGTERM")}catch(w){if(w.code==="ESRCH")return await Yr(t),{stopped:!1,pid:c,forced:!1};throw w}let $=Date.now()+n;while(Date.now()<$){if(!xi(c))return T("daemon",`daemon pid=${c} stopped cleanly`,r),{stopped:!0,pid:c,forced:!1};await new Promise((w)=>setTimeout(w,f))}if(!l)throw Error(`rpx daemon (pid=${c}) did not exit within ${n}ms`);T("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,r);try{s.kill(c,"SIGKILL")}catch(w){if(w.code!=="ESRCH")throw w}return await Yr(t),await Br({rpxDir:t,verbose:r}).catch((w)=>{T("daemon",`DNS teardown after SIGKILL: ${w}`,r)}),{stopped:!0,pid:c,forced:!0}}async function SS(i={}){let t=i.rpxDir??si();if(await Gm(t))return;await Cr({rpxDir:t,verbose:i.verbose})}import*as jt from"node:fs/promises";import{homedir as km}from"node:os";import*as W0 from"node:path";var xf=1,Vm="dns-state.json",Uu=["com","test","dev","app","page","local","localhost","example","invalid"];function ju(){return W0.join(km(),".stacks","rpx")}function J0(i=ju()){return W0.join(i,Vm)}async function df(i=ju()){try{let t=await jt.readFile(J0(i),"utf8"),r=JSON.parse(t);if(r.version!==xf||!Array.isArray(r.resolvers))return null;return{version:xf,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Su(i,t){await jt.mkdir(i,{recursive:!0}),await jt.writeFile(J0(i),`${JSON.stringify(t,null,2)}
|
|
220
|
-
`,"utf8")}async function _0(i){await jt.rm(J0(i),{force:!0})}function au(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function Dm(i){let t=au(i);if(!t)return null;let r=t.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function I0(i){let t=new Set;for(let r of i){let n=Dm(r);if(n)t.add(n)}return Array.from(t).sort()}function K0(i){let t=new Set;for(let r of i){let n=au(r);if(n)t.add(n)}return Array.from(t).sort()}var Vf=15353,bm="# managed-by: rpx",Wu="/etc/resolver",Ri=null,kf=new Set;function Ju(i){return{id:i.readUInt16BE(0),flags:i.readUInt16BE(2),qdcount:i.readUInt16BE(4),ancount:i.readUInt16BE(6),nscount:i.readUInt16BE(8),arcount:i.readUInt16BE(10)}}function _u(i,t,r=0){let n=[],f=t,l=0;while(!0){if(f>=i.length||++l>128)break;let c=i[f];if(c===0){f++;break}if((c&192)===192){if(f+1>=i.length||r>=10)break;let $=i.readUInt16BE(f)&16383,{name:w}=_u(i,$,r+1);if(w)n.push(w);f+=2;break}if(f++,f+c>i.length)break;n.push(i.subarray(f,f+c).toString("ascii")),f+=c}return{name:n.join("."),newOffset:f}}function Qm(i,t){let{name:r,newOffset:n}=_u(i,t),f=i.readUInt16BE(n),l=i.readUInt16BE(n+2);return{question:{name:r,type:f,class:l},newOffset:n+4}}function br(i){let t=i.split("."),r=[];for(let n of t)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function Pm(i,t,r){let n=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),n.push(f),n.push(br(t.name));let l=Buffer.alloc(4);l.writeUInt16BE(t.type,0),l.writeUInt16BE(t.class,2),n.push(l),n.push(br(t.name));let c=Buffer.alloc(10);if(c.writeUInt16BE(t.type,0),c.writeUInt16BE(1,2),c.writeUInt32BE(300,4),t.type===1){c.writeUInt16BE(4,8),n.push(c);let $=r.split(".").map((w)=>Number.parseInt(w,10));n.push(Buffer.from($))}else if(t.type===28)c.writeUInt16BE(16,8),n.push(c),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,br(t.name),l]);return Buffer.concat(n)}function vm(i,t){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(i,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(br(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),r.push(f),Buffer.concat(r)}async function Zm(i,t){if(ut.platform!=="darwin")return!1;let r=K0(i);if(r.length===0)return!1;if(Ri){for(let n of r)kf.add(n);return T("dns","DNS server already running — merged domains",t),!0}return kf=new Set(r),new Promise((n)=>{Ri=Nu.createSocket("udp4"),Ri.on("error",(f)=>{T("dns",`DNS server error: ${f.message}`,t),Ri?.close(),Ri=null,n(!1)}),Ri.on("message",(f,l)=>{try{let c=Ju(f),{question:$}=Qm(f,12);T("dns",`Query for ${$.name} type ${$.type} from ${l.address}`,t);let w=$.name.toLowerCase(),y=!1;for(let u of kf)if(w===u||w.endsWith(`.${u}`)){y=!0;break}let h;if(y&&($.type===1||$.type===28))h=Pm(c.id,$,"127.0.0.1"),T("dns",`Responding with localhost for ${$.name}`,t);else h=vm(c.id,$),T("dns",`NXDOMAIN for ${$.name}`,t);Ri?.send(h,l.port,l.address)}catch(c){T("dns",`Error processing DNS query: ${c}`,t)}}),Ri.on("listening",()=>{let f=Ri?.address();T("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),n(!0)});try{Ri.bind(Vf,"127.0.0.1")}catch(f){T("dns",`Failed to bind DNS server: ${f}`,t),n(!1)}})}function Iu(i){if(Ri)T("dns","Stopping DNS server",i),Ri.close(),Ri=null,kf=new Set}function KS(){return Ri!==null}async function om(i,t=500){let r=i.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let f=Nu.createSocket("udp4"),l=setTimeout(()=>{f.close(),n(!1)},t);f.on("message",($)=>{clearTimeout(l),f.close();try{let w=Ju($);n(w.ancount>0)}catch{n(!1)}}),f.on("error",()=>{clearTimeout(l),f.close(),n(!1)});let c=pm(r,1);f.send(c,Vf,"127.0.0.1",($)=>{if($)clearTimeout(l),f.close(),n(!1)})})}function pm(i,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([br(i),Buffer.from([0,t,0,1])]);return Buffer.concat([r,n])}function iB(){return`${bm}
|
|
221
|
-
nameserver 127.0.0.1
|
|
222
|
-
port ${Vf}
|
|
223
|
-
`}function Qr(i){return Xu.join(Wu,i)}function tB(i){return i.includes("127.0.0.1")&&i.includes(String(Vf))}async function rB(i){try{return await Fu.readFile(Qr(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function z0(i){if(ut.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:n}=await import("./chunk-6nvjwawp.js");if(!n()&&!r()){T("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),T("dns","DNS cache flushed",i)}catch(f){T("dns",`Could not flush DNS cache: ${f}`,i)}}function Ku(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function nB(i,t){Ku(i);let{execSudoSync:r}=await import("./chunk-6nvjwawp.js"),n=iB().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${Wu} && printf "%b" "${n}" > ${Qr(i)}'`;r(f),T("dns",`Created ${Qr(i)}`,t)}async function fB(i,t){Ku(i);let{execSudoSync:r}=await import("./chunk-6nvjwawp.js");r(`rm -f ${Qr(i)}`),T("dns",`Removed ${Qr(i)}`,t)}async function zS(i,t){return Ou({domains:t??[],verbose:i})}async function lB(i,t){if(ut.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-6nvjwawp.js");if(!n()&&!r())return T("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await nB(f,t);return await z0(t),!0}catch(f){return T("dns",`Failed to create resolver file: ${f}`,t),!1}}async function O0(i,t){if(ut.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-6nvjwawp.js");if(!n()&&!r())return;try{for(let f of i)await fB(f,t);await z0(t)}catch(f){T("dns",`Failed to remove resolver files: ${f}`,t)}}async function zu(i){if(ut.platform!=="darwin")return[];let t=[];for(let r of Uu){let n=await rB(r);if(n&&tB(n))await O0([r],i),t.push(r)}return t}async function Ou(i){let t=i.rpxDir??si(),r=K0(i.domains);if(r.length===0)return!1;let n=I0(r),f=await Zm(r,i.verbose);if(!f){let $=r[0];if($&&await om($))f=!0;else T("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await lB(n,i.verbose))return!1;let c={version:xf,resolvers:n,domains:r,ownerPid:i.ownerPid??ut.pid,updatedAt:new Date().toISOString()};return await Su(t,c),!0}async function Dr(i,t={}){let r=i.map((w)=>w.to).filter(Boolean),n=t.rpxDir??si(),f=I0(r),$=((await df(n))?.resolvers??[]).filter((w)=>!f.includes(w));if($.length>0)await O0($,t.verbose);if(f.length===0){Iu(t.verbose),await _0(n);return}await Ou({domains:r,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??ut.pid})}async function Br(i={}){let t=i.rpxDir??si();Iu(i.verbose);let n=(await df(t))?.resolvers??[];await O0(n,i.verbose),await zu(i.verbose),await _0(t)}async function OS(i){await Br({verbose:i})}async function Cr(i={}){let t=i.rpxDir??si(),r=await df(t),n=r?.ownerPid!=null&&xi(r.ownerPid);if(r&&!n){T("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,i.verbose),await Br(i);return}let f=await zu(i.verbose);if(f.length>0)T("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await z0(i.verbose)}
|
|
224
|
-
export{X as a,wh as b,iY as c,_t as d,bc as e,Qc as f,tY as g,rY as h,Ct as i,It as j,Pc as k,Mr as l,vc as m,yh as n,Ff as o,Hr as p,qr as q,Zc as r,t0 as s,Yh as t,mh as u,r0 as v,nj as w,fj as x,lj as y,Ch as z,n0 as A,f0 as B,l0 as C,cj as D,sh as E,Rh as F,Uh as G,jh as H,Wf as I,Lr as J,Sh as K,ah as L,RY as M,Xh as N,Wh as O,Tj as P,Hh as Q,qh as R,QY as S,PY as T,vY as U,Lh as V,kh as W,w0 as X,y0 as Y,Vh as Z,Qh as _,If as $,h0 as aa,Ph as ba,zt as ca,tm as da,u0 as ea,e0 as fa,A0 as ga,rm as ha,T0 as ia,lm as ja,Zh as ka,Kf as la,B0 as ma,oh as na,Am as oa,Em as pa,Ym as qa,C0 as ra,Hj as sa,fu as ta,s0 as ua,lu as va,gj as wa,Ut as xa,U0 as ya,xi as za,$u as Aa,S0 as Ba,Rm as Ca,ht as Da,kr as Ea,Mf as Fa,N0 as Ga,Tr as Ha,uu as Ia,eu as Ja,xf as Ka,Uu as La,au as Ma,Dm as Na,I0 as Oa,K0 as Pa,Vf as Qa,bm as Ra,Zm as Sa,Iu as Ta,KS as Ua,om as Va,Qr as Wa,tB as Xa,zS as Ya,zu as Za,Ou as _a,Dr as $a,Br as ab,OS as bb,Cr as cb,si as db,gf as eb,mr as fb,Gm as gb,Cu as hb,Yr as ib,RS as jb,dm as kb,US as lb,jS as mb,SS as nb};
|