@stacksjs/rpx 0.11.29 → 0.11.31
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 +198 -198
- package/dist/chunk-9amtxw74.js +252 -0
- package/dist/{chunk-ws2cmbxh.js → chunk-axym4f9k.js} +1 -1
- package/dist/{chunk-z86swbd8.js → chunk-qfckr5a3.js} +11 -11
- package/dist/chunk-xbct09d3.js +1 -0
- package/dist/index.js +2 -2
- package/dist/start.d.ts +6 -1
- package/dist/utils.d.ts +12 -0
- package/package.json +2 -2
- package/dist/chunk-22h4jf2c.js +0 -1
- package/dist/chunk-9dh9jhc6.js +0 -252
package/dist/chunk-9dh9jhc6.js
DELETED
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
import{Ab as Jh,Bb as Nt,Cb as Y,Db as Oh,Hb as Xu,Ib as lc,Kb as Gf,Lb as Su,Nb as th,Ob as Fu,yb as g,zb as Mc}from"./chunk-z86swbd8.js";import sh from"node:dgram";import*as dh from"node:fs/promises";import*as Dh from"node:path";import*as Et from"node:process";import{spawn as Gh}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as Mh}from"node:os";import*as Pi from"node:path";import*as R from"node:process";var e={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 $c}from"node:child_process";import Z from"node:fs/promises";import*as cc from"node:os";import{homedir as Cn}from"node:os";import*as Ju from"node:path";import{join as Q}from"node:path";import*as ki from"node:process";import{createRequire as r1}from"node:module";import{Resolver as r0}from"node:dns/promises";import{createHash as $1,sign as c1}from"node:crypto";import{createHash as l1}from"node:crypto";import{sign as w1}from"node:crypto";import{generateKeyPairSync as iw,X509Certificate as C1}from"node:crypto";import f0 from"node:os";import $0 from"node:path";import{existsSync as vc,statSync as pc}from"fs";import{existsSync as j1,mkdirSync as kU,readdirSync as VU,readFileSync as m1,writeFileSync as sU}from"fs";import{homedir as kt}from"os";import{dirname as QU,resolve as ei}from"path";import Vr from"process";import{existsSync as oc,statSync as il}from"fs";import{existsSync as I0,mkdirSync as R1,readdirSync as N1,writeFileSync as W1}from"fs";import{homedir as Vt}from"os";import{dirname as tl,resolve as Yi}from"path";import zt from"process";import{join as X1,relative as S1,resolve as nl}from"path";import Fr from"process";import{existsSync as tw,mkdirSync as rj,readdirSync as fj,writeFileSync as $j}from"fs";import{homedir as c0}from"os";import{dirname as wj,resolve as Ei}from"path";import In from"process";import{join as F1,relative as J1,resolve as rl}from"path";import Jr from"process";import{existsSync as nw,mkdirSync as Tj,readdirSync as Ej,writeFileSync as Yj}from"fs";import{dirname as Cj,resolve as er}from"path";import _0 from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as e1,createDecipheriv as I1,randomBytes as l0}from"crypto";import{closeSync as w0,createReadStream as fl,createWriteStream as _1,existsSync as y0,fsyncSync as $l,openSync as cl,writeFileSync as K1}from"fs";import{access as z1,constants as ll,mkdir as a1,readdir as fr,rename as wl,stat as st,unlink as $r,writeFile as u0}from"fs/promises";import{join as dt}from"path";import li from"process";import{pipeline as O1}from"stream/promises";import{createGzip as yl}from"zlib";import Dt from"process";import it from"process";import{Buffer as vi}from"buffer";import{createCipheriv as G1,createDecipheriv as M1,randomBytes as h0}from"crypto";import{closeSync as A0,createReadStream as ul,createWriteStream as H1,existsSync as cr,fsyncSync as hl,openSync as Al,writeFileSync as q1}from"fs";import{access as L1,constants as Tl,mkdir as x1,readdir as lr,rename as El,stat as Qt,unlink as wr,writeFile as T0}from"fs/promises";import{isAbsolute as g1,join as bt,resolve as k1}from"path";import q from"process";import{pipeline as V1}from"stream/promises";import{createGzip as Yl}from"zlib";import Pt from"process";import tt from"process";import yr from"process";import{existsSync as ur}from"fs";import{resolve as E0}from"path";import{existsSync as s1}from"fs";import{existsSync as d1,readdirSync as D1}from"fs";import{extname as Y0,resolve as Bl}from"path";import Q1 from"process";import{join as b1,relative as P1,resolve as Cl}from"path";import Ir from"process";import{Buffer as pi}from"buffer";import{createCipheriv as Z1,createDecipheriv as v1,randomBytes as B0}from"crypto";import{closeSync as C0,createReadStream as Ul,createWriteStream as p1,existsSync as hr,fsyncSync as jl,openSync as ml,writeFileSync as o1}from"fs";import{access as iA,constants as Rl,mkdir as tA,readdir as Ar,rename as Nl,stat as Zt,unlink as Tr,writeFile as U0}from"fs/promises";import{isAbsolute as nA,join as vt,resolve as rA}from"path";import L from"process";import{pipeline as fA}from"stream/promises";import{createGzip as Wl}from"zlib";import pt from"process";import nt from"process";import Er from"process";import{existsSync as Yr}from"fs";import{resolve as j0}from"path";import{existsSync as $A}from"fs";import{exec as JT}from"node:child_process";import g0 from"node:fs";import eT from"node:os";import Gi from"node:path";import qw from"node:process";import{promisify as IT}from"node:util";import rn from"node:crypto";import rt from"node:fs";import s0 from"node:path";import pT from"node:crypto";import oT from"node:fs";import iE from"node:tls";import{execSync as rE}from"node:child_process";import gr from"node:os";var f1=r1(import.meta.url);async function gl(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,$=i.split(".").slice(-2).join("."),c;try{let y=new r0,u=await y.resolveNs($),h=(await Promise.all(u.map((A)=>y.resolve4(A).catch(()=>[])))).flat();if(h.length>0)c=new r0,c.setServers(h)}catch{}let l=Date.now()+r,w=c??new r0;for(;;){try{if((await w.resolveTxt(i)).some((y)=>y.join("")===t))return!0}catch{}if(Date.now()>=l)return!1;await new Promise((y)=>setTimeout(y,f))}}class en{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(en.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+en.PATH_PREFIX.length);return this.get(n)}}var kr=new en;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function S0(i){return Buffer.from(i,"base64url")}function kl(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 Vl(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return $1("sha256").update(t).digest("base64url")}function sl(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),$=n===""?"":Ur(JSON.stringify(n)),c=`${f}.${$}`,l=c1("sha256",Buffer.from(c),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:$,signature:Ur(l)}}var dl="https://acme-staging-v02.api.letsencrypt.org/directory",Dl="https://acme-v02.api.letsencrypt.org/directory";class Xr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class Sr{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=kl(i.accountPublicKey),this.thumbprint=Vl(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:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let $=sl({protectedHeader:f,payload:n,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(l)this.nonce=l;let w=c.headers.get("content-type")??"",y;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))y=await c.text();else{let u=await c.text();y=u?JSON.parse(u):{}}if(c.status>=400){let u=y??{};throw new Xr(`ACME request to ${t} failed (HTTP ${c.status}): ${u.type??""} ${u.detail??""}`.trim(),u,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(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return l1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let $=await this.getAuthorization(i);if($.status==="valid")return;if($.status==="invalid"){let c=$.challenges.find((l)=>l.status==="invalid");throw new Xr(`Authorization for ${$.identifier.value} became invalid: ${c?.error?.detail??"unknown reason"}`,c?.error??{},0)}await Zc(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let $=await this.getOrder(i);if($.status==="valid"){if(!$.certificate)throw Error("ACME order is valid but has no certificate URL");return $.certificate}if($.status==="invalid")throw Error(`ACME order ${i} became invalid`);await Zc(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Ql(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
|
|
2
|
-
`,chainPem:""};let r=`${n.trim()}
|
|
3
|
-
`,f=t.slice(1).map(($)=>$.trim()).join(`
|
|
4
|
-
`);return{certPem:r,chainPem:f?`${f}
|
|
5
|
-
`:""}}function bl(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function Zc(i){return new Promise((t)=>setTimeout(t,i))}function y1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function jt(i,t){return Buffer.concat([Buffer.from([i]),y1(t.length),t])}function Pl(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return jt(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],$=[f&127];f=Math.floor(f/128);while(f>0)$.unshift(f&127|128),f=Math.floor(f/128);n.push(...$)}return jt(6,Buffer.from(n))}function Ji(...i){return jt(48,Buffer.concat(i))}function F0(...i){return jt(49,Buffer.concat(i))}function J0(i){return jt(3,Buffer.concat([Buffer.from([0]),i]))}function Zl(i){return jt(4,i)}function vl(i){return jt(12,Buffer.from(i,"utf8"))}function e0(i,t,n){let r=128|(n?32:0)|i;return jt(r,t)}var u1="1.2.840.10045.2.1",h1="1.2.840.10045.3.1.7",A1="1.2.840.10045.4.3.2",T1="2.5.4.3",E1="1.2.840.113549.1.9.14",Y1="2.5.29.17";function B1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=S0(t.x),r=S0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function pl(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Ji(F0(Ji(Kt(T1),vl(t[0])))),$=Ji(Ji(Kt(u1),Kt(h1)),J0(B1(n))),c=t.map((E)=>e0(2,Buffer.from(E,"ascii"),!1)),l=Ji(...c),w=Ji(Kt(Y1),Zl(l)),y=Ji(w),u=Ji(Kt(E1),F0(y)),h=e0(0,u,!0),A=Ji(Pl(0),f,$,h),T=w1("sha256",A,r),C=Ji(Kt(A1));return Ji(A,C,J0(T))}function ol(i){return pl(i).toString("base64url")}function U1(i){if(i){let{createPrivateKey:f,createPublicKey:$}=f1("node:crypto"),c=f(i),l=$(c);return{privateKey:c,publicKey:l,pem:i}}let{privateKey:t,publicKey:n}=iw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function d0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((h)=>h.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Dl:dl),f=U1(i.accountKeyPem),$=new Sr({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey});await $.newAccount({email:i.email});let{order:c,orderUrl:l}=await $.newOrder(t),w=i.http01Store??kr,y=[],u=[];try{for(let W of c.authorizations){let J=await $.getAuthorization(W);if(J.status==="valid")continue;let H=Sr.selectChallenge(J,n);if(n==="dns-01"){let p=bl(J.identifier.value),si=$.dns01TxtValue(H.token);await i.dnsProvider.setTxt(p,si),y.push({name:p,value:si}),await gl(p,si,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(H.token,$.keyAuthorization(H.token)),u.push(H.token);await $.notifyChallengeReady(H.url),await $.pollAuthorization(W,{timeoutMs:i.timeoutMs})}let{privateKey:h,publicKey:A}=iw("ec",{namedCurve:"P-256"}),T=ol({domains:t,publicKey:A,privateKey:h});await $.finalizeOrder(c.finalize,T);let C=await $.pollOrder(l,{timeoutMs:i.timeoutMs}),E=await $.downloadCertificate(C),{certPem:B,chainPem:U}=Ql(E),m=U?`${B}${U}`:B,S=h.export({format:"pem",type:"pkcs8"}).toString(),F=new Date(new C1(B).validTo);return{certPem:B,keyPem:S,chainPem:U,fullChainPem:m,accountKeyPem:f.pem,notAfter:F}}finally{for(let{name:h,value:A}of y)await i.dnsProvider?.removeTxt(h,A).catch(()=>{});for(let h of u)w.remove(h)}}class rw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),$=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:$,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!vc(i))return!0;return pc(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=vc(n)?pc(n):null,$=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:$},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class fw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let $=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),$}catch($){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),$}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,$)=>f+$,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new rw,D0=new fw,cA=Object.defineProperty,lA=(i)=>i;function wA(i,t){this[i]=lA.bind(null,t)}var yA=(i,t)=>{for(var n in t)cA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:wA.bind(t,n)})},uA=(i,t)=>()=>(i&&(t=i(i=0)),t),$w={};yA($w,{withErrorRecovery:()=>ww,tryLoadConfig:()=>aA,loadConfigWithResult:()=>KA,loadConfig:()=>Tw,isRetryableError:()=>SA,isConfigNotFoundError:()=>XA,isBunfigError:()=>yw,globalPerformanceMonitor:()=>an,globalCache:()=>tn,getEnvOrDefault:()=>FA,generateConfigTypes:()=>OA,defaultGeneratedDir:()=>Rw,defaultConfigDir:()=>mw,deepMergeWithArrayStrategy:()=>v0,deepMerge:()=>uw,createLibraryConfig:()=>GA,config:()=>zA,bunfigPlugin:()=>MA,applyEnvVarsToConfig:()=>Fn,TypeGenerationError:()=>H0,SchemaValidationError:()=>Kn,PluginError:()=>L0,PerformanceMonitor:()=>b0,FileSystemError:()=>M0,ErrorFactory:()=>Ut,EnvVarError:()=>Mr,EnvProcessor:()=>sr,ConfigValidator:()=>p0,ConfigValidationError:()=>O0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>G0,ConfigLoader:()=>o0,ConfigLoadError:()=>_n,ConfigFileLoader:()=>dr,ConfigCache:()=>Q0,CacheUtils:()=>Yw,BunfigError:()=>Wi,BrowserConfigError:()=>q0,ArrayMergeStrategies:()=>Uw});class Q0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),$=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:$,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!oc(i))return!0;return il(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=oc(n)?il(n):null,$=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:$},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class b0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let $=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),$}catch($){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),$}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,$)=>f+$,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function hA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function AA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function TA(i){return i.getStats().size*2}function P0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&d(t[0])&&"id"in t[0]&&t[0].id===3&&d(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(d(t)&&d(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(d(i)&&"arr"in i&&Array.isArray(i.arr)&&d(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&d(t[0])&&d(i[0])){let r=[...t];for(let f of i)if(d(f)&&"name"in f){if(!r.find(($)=>d($)&&("name"in $)&&$.name===f.name))r.push(f)}else if(d(f)&&"path"in f){if(!r.find(($)=>d($)&&("path"in $)&&$.path===f.path))r.push(f)}else if(!r.some(($)=>Kr($,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!d(t)||!d(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(d(f)&&d(n[r]))n[r]=P0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&d(f[0])&&d(n[r][0])){let $=[...f];for(let c of n[r])if(d(c)&&"name"in c){if(!$.find((l)=>d(l)&&("name"in l)&&l.name===c.name))$.push(c)}else if(d(c)&&"path"in c){if(!$.find((l)=>d(l)&&("path"in l)&&l.path===c.path))$.push(c)}else if(!$.some((l)=>Kr(l,c)))$.push(c);n[r]=$}else if(f.every(($)=>typeof $==="string")&&n[r].every(($)=>typeof $==="string")){let $=[...f];for(let c of n[r])if(!$.includes(c))$.push(c);n[r]=$}else n[r]=f;else n[r]=f}return n}function Kr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Kr(i[n],t[n]))return!1;return!0}if(d(i)&&d(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Kr(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function EA(i,t){if(!nw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return P0(t,r)}catch{return null}}catch{return null}}async function YA({name:i="",cwd:t,defaultConfig:n}){let r=t||_0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],$=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of $)for(let l of f){let w=er(r,`${c}${l}`),y=await EA(w,n);if(y!==null)return y}try{let c=er(r,"package.json");if(nw(c)){let l=(await import(c))[i];if(l&&typeof l==="object"&&!Array.isArray(l))try{return P0(n,l)}catch{}}}catch{}return n}function BA(i,t={}){let n=Jr.cwd();while(n.includes("storage"))n=rl(n,"..");let r=rl(n,i||"");if(t?.relative)return J1(Jr.cwd(),r);return r}async function CA(){try{let i=await YA({name:"clarity",defaultConfig:mr,cwd:Jr.cwd(),endpoint:"",headers:{}});return{...mr,...i}}catch{return mr}}function b(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UA(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof it<"u"){let i=it.type;if(i==="renderer"||i==="worker")return!1;return!!(it.versions&&(it.versions.node||it.versions.bun))}return!1}class cw{async format(i){let t=await UA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...z0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new cw,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??li.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),$=this.generateKey();this.currentKeyId=f,this.keys.set(f,$),this.encryptionKeys.set(f,{key:$,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rr};return{...Rr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:z0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,$=3,c=1000;while(f<$)try{try{try{await z1(this.config.logDirectory,ll.F_OK|ll.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await a1(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 l=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Bt.from(i);try{if(!y0(this.currentLogFile))await u0(this.currentLogFile,"",{mode:420});if(r=cl(this.currentLogFile,"a",420),K1(r,l,{flag:"a"}),$l(r),r!==void 0)w0(r),r=void 0;if((await st(this.currentLogFile)).size===0){if(await u0(this.currentLogFile,l,{flag:"w",mode:420}),(await st(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<$-1){let u=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${$}:`,u);let h=c*2**f;await new Promise((A)=>setTimeout(A,h)),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(r!==void 0)try{w0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(l){if(f===$-1){let y=l,u=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let w=c*2**(f-1);await new Promise((y)=>setTimeout(y,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return dt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return dt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return dt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,$=Math.max(1,f);if(r.length>$)for(let[c]of r.slice($))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return l0(16).toString("hex")}generateKey(){return l0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=l0(16),r=e1("aes-256-gcm",t,n),f=Bt.concat([r.update(i,"utf8"),r.final()]),$=r.getAuthTag();return{encrypted:Bt.concat([n,f,$]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=yl(),f=[];r.on("data",($)=>f.push($)),r.on("end",()=>t(Bt.from(Bt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await st(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await fr(this.config.logDirectory),$=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let u=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),c=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await st(n).catch(()=>null))try{if(await wl(n,l),t.compress)try{let w=`${l}.gz`;await this.compressLogFile(l,w),await $r(l)}catch(w){console.error("Error compressing rotated file:",w)}if($.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await u0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),$=n.replace(/\.log$/,`-${f}.log`);if(await st(n).catch(()=>null))await wl(n,$)}if(this.currentLogFile=r,t.maxFiles){let f=(await fr(this.config.logDirectory)).filter(($)=>$.startsWith(this.name)).sort(($,c)=>c.localeCompare($));for(let $ of f.slice(t.maxFiles))await $r(dt(this.config.logDirectory,$))}}}async compressLogFile(i,t){let n=fl(i),r=_1(t),f=yl();await O1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),y0(this.currentLogFile))try{let i=cl(this.currentLogFile,"r+");$l(i),w0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await fr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await $r(dt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?V.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:$,showTimestamp:c=!0}=i,l=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(c)T.push(t);if($==="warning")T.push("WARN");else if($==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=li.stdout.columns||120,y="";if($==="warning"||$==="error")y=`${n} ${f}`;else if($==="info"||$==="success")y=`${n} ${r} ${f}`;else y=`${n} ${r} ${V.cyan(f)}`;if(!c)return y.trim();let u=l(y).trim().length,h=l(t).length,A=Math.max(1,w-2-u-h);return`${y.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,($,c)=>{let l=Number.parseInt(c,10);return l<t[0].length?String(t[0][l]):$});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,($,c)=>{if(c==="%")return"%";if(r>=t.length)return $;let l=t[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return $}});if(r<t.length)f+=` ${t.slice(r).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),$=this.formatFileTimestamp(r),c,l;if(t instanceof Error)c=t.message,l=t.stack;else c=this.formatMessage(t,n);if(this.fancy&&!b()){let y=Bw[i],u=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",h;switch(i){case"debug":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:V.gray(c),level:i}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:c,level:i}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:V.green(c),level:i}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:c,level:i}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:c,level:i}),console.error(h),l){let A=l.split(`
|
|
6
|
-
`);for(let T of A)if(T.trim()&&!T.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:V.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${$} ${this.environment}.${i.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(i))return;let w=`${$} ${this.environment}.${i.toUpperCase()}: ${c}
|
|
7
|
-
`;if(l)w+=`${l}
|
|
8
|
-
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!b()){let n=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:V.blue("◐"),tag:n,message:`${V.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),$=`${i} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${$}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
9
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let y=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:V.green("✓"),tag:y,message:`${$}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new zr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!y0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fl(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Bt.isBuffer(i)?i:Bt.from(i,"base64"),f=r.slice(0,16),$=r.slice(-16),c=r.slice(16,-16),l=I1("aes-256-gcm",n,f);return l.setAuthTag($),Bt.concat([l.update(c),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!b()){let $=i.split(`
|
|
10
|
-
`),c=Math.max(...$.map((u)=>u.length))+2,l=`┌${"─".repeat(c)}┐`,w=`└${"─".repeat(c)}┘`,y=$.map((u)=>{let h=" ".repeat(c-u.length-2);return`│ ${u}${h} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:V.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:V.cyan(l)})),y.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:V.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:V.cyan(w),showTimestamp:!1}))}else if(!b())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(b())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${V.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();li.stdin.removeListener("data",n);try{if(typeof li.stdin.setRawMode==="function")li.stdin.setRawMode(!1)}catch{}li.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof li.stdin.setRawMode==="function")li.stdin.setRawMode(!0)}catch{}li.stdin.resume(),li.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,$=0;if(n=i.replace(f,(c,l)=>{if(l==="%")return"%";if($>=t.length)return c;let w=t[$++];switch(l){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}}),$<t.length)n+=` ${t.slice($).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!b()){let f=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",$=V.blue("◐");console.error(`${$} ${f} ${V.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,r)),f!==void 0)this.activeProgressBar.message=f;let $=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,$)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;li.stdout.write(`${"\r".padEnd(li.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!li.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,$=V.green("━".repeat(r)),c=V.gray("━".repeat(f)),l=`[${$}${c}]`,w=`${n}%`.padStart(4),y=i.message?` ${i.message}`:"",u=t||n===100?V.green("✓"):V.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",A=`\r${u}${h} ${l} ${w}${y}`,T=li.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,li.stdout.write(i.lastRenderedLine),t)li.stdout.write(`
|
|
13
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!li.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await fr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=dt(this.config.logDirectory,r);if(i.before)try{if((await st(f)).mtime>=i.before)continue}catch($){console.error(`Failed to get stats for file ${f}:`,$);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await $r(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&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 r=[...t];for(let f of i)if(x(f)&&"name"in f){if(!r.find(($)=>x($)&&("name"in $)&&$.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find(($)=>x($)&&("path"in $)&&$.path===f.path))r.push(f)}else if(!r.some(($)=>ar($,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!x(t)||!x(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=jr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let $=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!$.find((l)=>x(l)&&("name"in l)&&l.name===c.name))$.push(c)}else if(x(c)&&"path"in c){if(!$.find((l)=>x(l)&&("path"in l)&&l.path===c.path))$.push(c)}else if(!$.some((l)=>ar(l,c)))$.push(c);n[r]=$}else if(f.every(($)=>typeof $==="string")&&n[r].every(($)=>typeof $==="string")){let $=[...f];for(let c of n[r])if(!$.includes(c))$.push(c);n[r]=$}else n[r]=f;else n[r]=f}return n}function Z0(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:jr(i,t);if(Array.isArray(i))return n==="replace"?t:jr(i,t);if(!x(t)||!x(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let $=t[f],c=r[f];if($===null||$===void 0)continue;if(Array.isArray($)||Array.isArray(c))if(n==="replace")r[f]=$;else r[f]=jr(c,$);else if(x($)&&x(c))r[f]=Z0(c,$,n);else r[f]=$}return r}function ar(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!ar(i[n],t[n]))return!1;return!0}if(x(i)&&x(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!ar(i[f],t[f]))return!1}return!0}return!1}function x(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Br(i,t,n="replace"){if(!tw(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Z0(t,f,n)}catch{return null}}catch{return null}}function jA(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function $(c,l=[]){let w={...c};for(let[y,u]of Object.entries(c)){let h=[...l,y],A=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${r}_${h.map(A).join("_")}`,C=`${r}_${h.map((E)=>E.toUpperCase()).join("_")}`;if(n)yi.info(`Checking environment variable ${T} for config ${i}.${h.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))w[y]=$(u,h);else{let E=In.env[T]||In.env[C];if(E!==void 0){if(n)yi.info(`Using environment variable ${E?T:C} for config ${i}.${h.join(".")}`);if(typeof u==="number")w[y]=Number(E);else if(typeof u==="boolean")w[y]=E.toLowerCase()==="true";else if(Array.isArray(u))try{let B=JSON.parse(E);if(Array.isArray(B))w[y]=B;else w[y]=E.split(",").map((U)=>U.trim())}catch{w[y]=E.split(",").map((B)=>B.trim())}else w[y]=E}}}return w}return $(f)}async function mA({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:$=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let w=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?jA(i,f,$):f,y=n||In.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if($)yi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${y}`);let h=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([y,Ei(y,"config"),Ei(y,".config"),r?Ei(y,r):void 0].filter(Boolean)));for(let B of E){if($)yi.info(`Searching for configuration in: ${B}`);let U=[Ei(y,"config"),Ei(y,".config")].concat(r?[Ei(y,r)]:[]).includes(B)?[...h,...A,...T,...C]:[...A,...h,...C,...T];for(let m of U)for(let S of u){let F=Ei(B,`${m}${S}`),W=await Br(F,w,l);if(W!==null){if($)yi.success(`Configuration loaded from: ${F}`);return W}}}if(i){let B=Ei(c0(),".config",i),U=["config",`${i}.config`];if(t)U.push(`${t}.config`);if($)yi.info(`Checking user config directory: ${B}`);for(let m of U)for(let S of u){let F=Ei(B,`${m}${S}`),W=await Br(F,w,l);if(W!==null){if($)yi.success(`Configuration loaded from user config directory: ${F}`);return W}}}if(i){let B=Ei(c0(),".config"),U=[`.${i}.config`];if(t)U.push(`.${t}.config`);if($)yi.info(`Checking user config directory for dotfile configs: ${B}`);for(let m of U)for(let S of u){let F=Ei(B,`${m}${S}`),W=await Br(F,w,l);if(W!==null){if($)yi.success(`Configuration loaded from user config directory dotfile: ${F}`);return W}}}if(i){let B=c0(),U=[`.${i}.config`,`.${i}`];if(t)U.push(`.${t}.config`),U.push(`.${t}`);if($)yi.info(`Checking user home directory for dotfile configs: ${B}`);for(let m of U)for(let S of u){let F=Ei(B,`${m}${S}`),W=await Br(F,w,l);if(W!==null){if($)yi.success(`Configuration loaded from user home directory: ${F}`);return W}}}try{let B=Ei(y,"package.json");if(tw(B)){let U=await import(B),m=U[i];if(!m&&t){if(m=U[t],m&&$)yi.success(`Using alias "${t}" configuration from package.json`)}if(m&&typeof m==="object"&&!Array.isArray(m))try{if($)yi.success(`Configuration loaded from package.json: ${m===U[i]?i:t}`);return Z0(w,m,l)}catch(S){if($)yi.warn("Failed to merge package.json config:",S)}}}catch(B){if($)yi.warn("Failed to load package.json:",B)}if($)yi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function RA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=nl(n,"..");let r=nl(n,i||"");if(t?.relative)return S1(Fr.cwd(),r);return r}async function NA(){try{let i=await mA({name:"clarity",alias:"logging",defaultConfig:Nr,cwd:Fr.cwd()});return{...Nr,...i||{}}}catch{return Nr}}function o(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function WA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class lw{async format(i){let t=await WA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Pt.pid,hostname:t(),environment:Pt.env.NODE_ENV||"development",platform:Pt.platform,version:Pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pt.env.NODE_ENV||Pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Or{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...a0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new lw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),$=this.generateKey();this.currentKeyId=f,this.keys.set(f,$),this.encryptionKeys.set(f,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Wr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Wr};return{...Wr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:a0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!o()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,$=3,c=1000;while(f<$)try{try{try{await L1(this.config.logDirectory,Tl.F_OK|Tl.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await x1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let l=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:vi.from(i);try{if(!cr(this.currentLogFile))await T0(this.currentLogFile,"",{mode:420});if(r=Al(this.currentLogFile,"a",420),q1(r,l,{flag:"a"}),hl(r),r!==void 0)A0(r),r=void 0;if((await Qt(this.currentLogFile)).size===0){if(await T0(this.currentLogFile,l,{flag:"w",mode:420}),(await Qt(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<$-1){let u=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${$}:`,u);let h=c*2**f;await new Promise((A)=>setTimeout(A,h)),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(r!==void 0)try{A0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(l){if(f===$-1){let y=l,u=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let w=c*2**(f-1);await new Promise((y)=>setTimeout(y,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return bt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return bt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return bt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(o())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,$=Math.max(1,f);if(r.length>$)for(let[c]of r.slice($))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return h0(16).toString("hex")}generateKey(){return h0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=h0(16),r=G1("aes-256-gcm",t,n),f=vi.isBuffer(i)?i:vi.from(i,"utf8"),$=r.update(f),c=r.final(),l=$.length+c.length,w=r.getAuthTag(),y=vi.allocUnsafe(16+l+16);return n.copy(y,0),$.copy(y,16),c.copy(y,16+$.length),w.copy(y,16+l),{encrypted:y,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Yl(),f=[];r.on("data",($)=>f.push($)),r.on("end",()=>t(vi.from(vi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(o())return;if(!this.shouldWriteToFile())return;let i=await Qt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await lr(this.config.logDirectory),$=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let u=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),c=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Qt(n).catch(()=>null))try{if(await El(n,l),t.compress)try{let w=`${l}.gz`;await this.compressLogFile(l,w),await wr(l)}catch(w){console.error("Error compressing rotated file:",w)}if($.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await T0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),$=n.replace(/\.log$/,`-${f}.log`);if(await Qt(n).catch(()=>null))await El(n,$)}if(this.currentLogFile=r,t.maxFiles){let f=(await lr(this.config.logDirectory)).filter(($)=>$.startsWith(this.name)).sort(($,c)=>c.localeCompare($));for(let $ of f.slice(t.maxFiles))await wr(bt(this.config.logDirectory,$))}}}async compressLogFile(i,t){let n=ul(i),r=H1(t),f=Yl();await V1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),cr(this.currentLogFile))try{let i=Al(this.currentLogFile,"r+");hl(i),A0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await lr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await wr(bt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?a.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||o())return!1;let i=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:$,showTimestamp:c=!0}=i,l=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(c)T.push(t);if($==="warning")T.push("WARN");else if($==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,y="";if($==="warning"||$==="error")y=`${n} ${f}`;else if($==="info"||$==="success")y=`${n} ${r} ${f}`;else y=`${n} ${r} ${a.cyan(f)}`;if(!c)return y.trim();let u=l(y).trim().length,h=l(t).length,A=Math.max(1,w-2-u-h);return`${y.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,($,c)=>{let l=Number.parseInt(c,10);return l<t[0].length?String(t[0][l]):$});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,($,c)=>{if(c==="%")return"%";if(r>=t.length)return $;let l=t[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return $}});if(r<t.length)f+=` ${t.slice(r).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let $=a.underline(a.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${l}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),t=t.replace(/`([^`]+)`/g,(n,r)=>a.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>a.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>a.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>a.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>a.strikethrough(r)),t}supportsHyperlinks(){if(o())return!1;let i=q.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=q.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(g1(t)||t.startsWith("./")||t.startsWith("../"))t=k1(t);else return null;return cr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),$=this.formatFileTimestamp(r),c,l;if(t instanceof Error)c=t.message,l=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":Cw[i],A=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:a.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:a.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.error(T),l){let C=l.split(`
|
|
14
|
-
`);for(let E of C)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:a.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!o()){if(console.error(`${$} ${this.environment}.${i.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(i))return;let u=`${$} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
15
|
-
`;if(l)u+=`${l}
|
|
16
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(i,t=""){let n={update:(f,$)=>{},finish:(f)=>{},interrupt:(f,$)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!o()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,$)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),$!==void 0)this.activeProgressBar.message=$;if(this.shouldStyleConsole()&&!o()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,$="info")=>{if(!o()&&q.stdout.isTTY)q.stdout.write(`
|
|
17
|
-
`);if(this[$==="warning"?"warn":$](f),this.activeProgressBar&&this.shouldStyleConsole()&&!o()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":a.blue("◐"),tag:n,message:`${a.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),$=`${i} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${$}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
18
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":a.green("✓"),tag:y,message:`${$}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!o())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Or(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(o())throw Error("createReadStream is not supported in browser environments");if(!cr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ul(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=vi.isBuffer(i)?i:vi.from(i,"base64"),f=r.subarray(0,16),$=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=M1("aes-256-gcm",n,f);l.setAuthTag($);let w=l.update(c),y=l.final(),u=w.length+y.length,h=vi.allocUnsafe(u);return w.copy(h,0),y.copy(h,w.length),h.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return o()}isServerMode(){return!o()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:$}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let l=f.split(`
|
|
19
|
-
`),w=Math.max(...l.map((A)=>A.length))+2,y=`┌${"─".repeat(w)}┐`,u=`└${"─".repeat(w)}┘`,h=l.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:a.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:a.cyan(y),showTimestamp:!1})),h.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:a.cyan(u),showTimestamp:!1}))}else if(!o())console.error(`${r} ${this.environment}.INFO: [BOX] ${$}`);let c=`${r} ${this.environment}.INFO: [BOX] ${$}
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(o())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${a.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();q.stdin.removeListener("data",n);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(n=i.replace(c,(w,y)=>{if(y==="%")return"%";if(l>=t.length)return w;let u=t[l++];switch(y){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return w}}),l<t.length)n+=` ${t.slice(l).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${a.blue("◐")} `;console.error(`${l}${c} ${a.cyan(r)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,$=a.green("━".repeat(r)),c=a.gray("━".repeat(f)),l=`[${$}${c}]`,w=`${n}%`.padStart(4),y=i.message?` ${i.message}`:"",u=this.options.showIcons===!1?"":t||n===100?a.green("✓"):a.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",A=`\r${u}${h} ${l} ${w}${y}`,T=q.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
|
|
22
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||o()||!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(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await lr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=bt(this.config.logDirectory,r);if(i.before)try{if((await Qt(f)).mtime>=i.before)continue}catch($){console.error(`Failed to get stats for file ${f}:`,$);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await wr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function ww(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:$}=t,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),l===n||!f(c))break;if(r>0)await new Promise((y)=>setTimeout(y,r))}if($!==void 0)return $;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function yw(i){return i instanceof Wi}function XA(i){return i instanceof Gr}function SA(i){if(yw(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class sr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:$=!0,customParsers:c={},verbose:l=!1,trackPerformance:w=!0}=n,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(i),h={...t};return this.processObject(h,[],u,{useCamelCase:f,useBackwardCompatibility:$,customParsers:c,verbose:l,configName:i}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return an.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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=c.map((u)=>this.formatEnvKey(u,r.useCamelCase)),w=`${n}_${l.join("_")}`,y=r.useBackwardCompatibility?`${n}_${c.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,c,n,r);else{let u=yr.env[w]||(y?yr.env[y]:void 0);if(u!==void 0){if(r.verbose){let h=yr.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(u,typeof $,w,r.customParsers,r.configName)}catch(h){if(h instanceof Mr)throw h;throw Ut.envVar(w,u,typeof $,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[$,c]of Object.entries(r))try{return c(i)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(i,t))try{return $.parse(i)}catch{throw Ut.envVar(n,i,`${t} (via ${$.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(yr.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,$=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],$,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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,c,n,r);else r.push({key:l,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${c.join(".")}`,example:this.generateExample($)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
23
|
-
|
|
24
|
-
`;for(let r of i)n+=`${r.key}
|
|
25
|
-
`,n+=` Type: ${r.type}
|
|
26
|
-
`,n+=` Description: ${r.description}
|
|
27
|
-
`,n+=` Example: ${r.example}
|
|
28
|
-
|
|
29
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
30
|
-
|
|
31
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
32
|
-
`,n+=`|----------|------|-------------|----------|
|
|
33
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
34
|
-
`;return n}}function FA(i,t){let n=Ew("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function uw(i,t,n={}){return hw(i,t,n,new WeakMap)}function hw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:$=!1,customMerger:c}=n;if(t===null||t===void 0)return $?i:t;if(c){let l=c(i,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(i))return Aw(i,t,f,r);if(!Ii(t)||!Ii(i))return t;return _A(i,t,n,r)}function Aw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return JA(i,t);case"smart":return eA(i,t,r);default:return t}return t}function JA(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>K0(f,r)))n.push(r);return n}function eA(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return IA(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function IA(i,t,n){let r=[...t];for(let f of i){if(!Ii(f)){r.push(f);continue}let $=["id","name","key","path","type"],c=!1;for(let l of $)if(l in f){if(r.find((w)=>Ii(w)&&(l in w)&&w[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function _A(i,t,n,r){let f=t;if(Ii(f)&&r.has(f))return r.get(f);let $={...i};if(Ii(f))r.set(f,$);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],w=$[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){$[c]=l;continue}if(Ii(l)&&Ii(w))$[c]=hw(w,l,n,r);else if(Array.isArray(l)||Array.isArray(w))$[c]=Aw(w,l,n.arrayMergeMode||"smart",r);else $[c]=l}return $}function v0(i,t,n="replace"){return uw(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function K0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!K0(i[n],t[n]))return!1;return!0}if(Ii(i)&&Ii(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!K0(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class dr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:$,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let y=tn.getWithFileCheck("file",i);if(y){if(l)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!ur(i))return null;try{let y=`?t=${Date.now()}`,u=await import(i+y),h=u.default||u,A="default"in u,T=Object.keys(u).length>0;if(!A&&!T)throw new _n(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new _n(i,Error("Configuration must export a valid object"),"unknown");let C={config:v0(t,h,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)tn.setWithFileCheck("file",C,i,$);return C}catch(y){throw y instanceof Error?Ut.configLoad(i,y):Ut.configLoad(i,Error(String(y)))}};if(c)return an.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let $ of r)for(let c of this.extensions)f.push(E0(t,`${$}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return ww(async()=>{return ur(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!ur(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let $ of f)for(let c of this.extensions){let l=E0(i,`${$}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),$=f(i);for(let c of $)if(this.looksLikeConfigFile(c)){let l=E0(i,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!ur(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),$=f(i,"utf8");JSON.parse($)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class p0{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:$=!0,customRules:c=[],trackPerformance:l=!0,verbose:w=!1}=n,y=async()=>{let u=[],h=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:$,customRules:c,trackPerformance:l,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return u.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(l)return await an.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,n){try{if(!s1(t))throw new Kn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Kn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,$){if($.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),$.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),$.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,l,r,f,$),$.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if($.validateRequired&&t.required){for(let l of t.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(t.properties){for(let[l,w]of Object.entries(t.properties))if(l in c){let y=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],w,y,r,f,$),$.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!l.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let $ of t)try{let c=this.getValueByPath(i,$.path),l=this.validateWithRule(c,$,$.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:$.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,$,c]=r;t.push({path:f,required:!$,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:jw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class o0{fileLoader=new dr;envProcessor=new sr;validator=new p0;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:$,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;l={...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 u=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),h=!u&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(A||u))throw w;if(h&&(!y||!A))l={...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)l={...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 l={...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||$)await this.validateConfiguration(l.config,f,$,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Mi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);l.metrics=w}return l}catch(l){let w=Date.now()-t;throw Mi.error(`Configuration loading failed after ${w}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:$,configDir:c,defaultConfig:l,checkEnv:w=!0,arrayStrategy:y="replace",verbose:u=!1}=i,h=$||zt.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,h,c,l,y,u,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,h,c)),this.finalizeResult(T,A,w,r,u);let C=await this.loadHomeConfiguration(r,f,l,y,u,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,u);let E=await this.loadPackageJsonConfiguration(r,f,h,l,y,u,w);if(E)return A.push(Yi(h,"package.json")),this.finalizeResult(E,A,w,r,u);if(A.push(...this.getAllSearchPaths(r,f,h,c)),t)throw Ut.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,l,w,u),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,$,c,l,w){let y=l?Fn(i,f,c):f,u=this.getLocalDirectories(n,r);for(let h of u){if(c)Mi.info(`Searching for configuration in: ${h}`);let A=this.fileLoader.generateConfigPaths(i,h,t),T=await this.fileLoader.tryLoadFromPaths(A,y,{arrayStrategy:$,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(c)Mi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,$){if(!i)return null;let c=$?Fn(i,n,f):n,l=[Yi(Vt(),".config",i),Yi(Vt(),".config"),Vt()];for(let w of l){if(f)Mi.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),u=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:r,verbose:f});if(u){if(f)Mi.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,$,c){let l=c?Fn(i,r,$):r;try{let w=Yi(n,"package.json");if(!I0(w))return null;let y=await import(w),u=y[i],h=i;if(!u&&t)u=y[t],h=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if($)Mi.success(`Configuration loaded from package.json: ${h}`);return{config:v0(l,u,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if($)Mi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Fn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let $=n(i);if($)f.push(...$)}if(t){let $=await this.validator.validateConfiguration(i,t);if(!$.isValid)f.push(...$.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Ut.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return tn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);tn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Yi(i,"config"),Yi(i,".config"),t?Yi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Yi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),$=[];for(let c of f)$.push(...this.fileLoader.generateConfigPaths(i,c,t));return $}getHomeSearchPaths(i,t){if(!i)return[];let n=[Yi(Vt(),".config",i),Yi(Vt(),".config"),Vt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Xl(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||n}async function KA(i){return ft.loadConfig({...i,__strictErrorHandling:!0})}async function Tw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ft.loadConfig(i);else r=await ft.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",$=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||$.includes("config"))&&i.verbose)Mi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ft.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function zA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ft.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Xl(n)))return(await ft.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ft.loadConfig({...i,cwd:i.cwd||zt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Xl(t)))return(await ft.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function aA(i,t,n="replace"){let r=new dr;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Fn(i,t,n=!1){let r=new sr,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(c,l=[]){let w={...c};for(let[y,u]of Object.entries(c)){let h=[...l,y],A=[`${f}_${h.join("_").toUpperCase()}`,`${f}_${h.map((E)=>E.toUpperCase()).join("")}`,`${f}_${h.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=zt.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof u==="boolean")w[y]=["true","1","yes"].includes(T.toLowerCase());else if(typeof u==="number"){let E=Number(T);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(u))try{w[y]=JSON.parse(T)}catch{w[y]=T.split(",").map((E)=>E.trim())}else w[y]=T;else if(u&&typeof u==="object"&&!Array.isArray(u))w[y]=$(u,h)}return w}return $(t)}function OA(i){let t=Yi(zt.cwd(),i.configDir),n=Yi(zt.cwd(),i.generatedDir),r=Yi(n,"config-types.ts");if(!I0(tl(r)))R1(tl(r),{recursive:!0,mode:511});let f=I0(t)?N1(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],$=`// Generated by bunfig v${yT}
|
|
35
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
36
|
-
`;W1(r,$,{mode:438})}function GA(i){let t=null,n=null,r=()=>{if(!n)n=Tw(i).then(($)=>{return t=$,$},($)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)Mi.warn("Config loading failed, using defaults:",[$ instanceof Error?$:Error(String($))]);return c});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get($,c){if(t)return t[c];let l=f[c];return r(),l},has($,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor($,c){return Object.getOwnPropertyDescriptor(t||f,c)},set($,c,l){if(!t)t={...f};return t[c]=l,!0}})}function MA(i){let t=Bl(Q1.cwd(),i?.configDir||"./config");function n(){if(!d1(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),$=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=D1(t).filter((w)=>f.has(Y0(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),l=new Map;for(let{base:w,file:y}of c){let u=Y0(y).toLowerCase(),h=l.get(w);if(!h){l.set(w,y);continue}let A=Y0(h).toLowerCase();if($.indexOf(u)<$.indexOf(A))l.set(w,y)}return Array.from(l.entries()).map(([w,y])=>({base:w,file:y})).sort((w,y)=>w.base.localeCompare(y.base))}function r(){let f=n(),$=f.map((w)=>w.base),c=$.length?$.map((w)=>`'${w}'`).join(" | "):"string",l=f.length?`{
|
|
37
|
-
${f.map((w)=>{let y=Bl(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 = ${l}
|
|
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$/},($)=>{return{path:$.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Ew,tn,an,Yw,HA,qA,Sl,mr,z0,wi,V,LA,Fl,xA,Jl,gA,kA,m0,VA,el,Il,R0,sA,dA,DA,QA,Rr,Bw,bA,yi,PA,ZA,_l,Nr,a0,ii,a,vA,Kl,pA,zl,oA,iT,N0,tT,al,Ol,nT,W0,rT,fT,$T,cT,lT,Wr,Cw,wT,yT="0.15.6",Wi,Gr,_n,O0,G0,Mr,M0,H0,Kn,q0,L0,Ut,Uw,jw,Mi,ft,mw,Rw,uT=uA(async()=>{Ew=import.meta.require,tn=new Q0,an=new b0,Yw={createKey:hA,isEquivalent:AA,estimateMemoryUsage:TA},HA=er(_0.cwd(),"config"),qA=er(_0.cwd(),"src/generated"),Sl=Jr.env.CLARITY_LOG_DIR||F1(BA(),"logs"),mr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},z0=await CA(),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"},V=wi,LA=wi.red,Fl=wi.green,xA=wi.yellow,Jl=wi.blue,gA=wi.magenta,kA=wi.cyan,m0=wi.white,VA=wi.gray,el=wi.bgRed,Il=wi.bgYellow,R0=wi.bold,sA=wi.dim,dA=wi.italic,DA=wi.underline,QA=wi.reset,Rr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bw={debug:"\uD83D\uDD0D",info:Jl("ℹ"),success:Fl("✓"),warning:Il(m0(R0(" WARN "))),error:el(m0(R0(" ERROR ")))},bA=new zr("stacks"),yi=new zr("bunfig",{showTags:!0}),PA=Ei(In.cwd(),"config"),ZA=Ei(In.cwd(),"src/generated"),_l=Fr.env.CLARITY_LOG_DIR||X1(RA(),"logs"),Nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_l,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},a0=await NA(),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"},a=ii,vA=ii.red,Kl=ii.green,pA=ii.yellow,zl=ii.blue,oA=ii.magenta,iT=ii.cyan,N0=ii.white,tT=ii.gray,al=ii.bgRed,Ol=ii.bgYellow,nT=ii.bgGray,W0=ii.bold,rT=ii.dim,fT=ii.italic,$T=ii.underline,cT=ii.strikethrough,lT=ii.reset,Wr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Cw={debug:"\uD83D\uDD0D",info:zl("ℹ"),success:Kl("✓"),warning:Ol(N0(W0(" WARN "))),error:al(N0(W0(" ERROR ")))},wT=new Or("stacks"),Wi=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Gr=class extends Wi{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${i}"${r} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}},_n=class extends Wi{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}},O0=class extends Wi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}},G0=class extends Wi{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Mr=class extends Wi{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}},M0=class extends Wi{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}},H0=class extends Wi{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Kn=class extends Wi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}},q0=class extends Wi{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}},L0=class extends Wi{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Ut={configNotFound(i,t,n){return new Gr(i,t,n)},configLoad(i,t,n){return new _n(i,t,n)},configValidation(i,t,n){return new O0(i,t,n)},configMerge(i,t,n,r){return new G0(i,t,n,r)},envVar(i,t,n,r){return new Mr(i,t,n,r)},fileSystem(i,t,n){return new M0(i,t,n)},typeGeneration(i,t,n){return new H0(i,t,n)},schemaValidation(i,t,n){return new Kn(i,t,n)},browserConfig(i,t,n,r){return new q0(i,t,n,r)},plugin(i,t,n){return new L0(i,t,n)}},Uw={replace:"replace",concat:"concat",smart:"smart"},jw=/^https?:\/\//,Mi=new Or("bunfig",{showTags:!0}),ft=new o0,mw=Yi(zt.cwd(),"config"),Rw=Yi(zt.cwd(),"src/generated")});function hT(i,t={}){let n=Ir.cwd();while(n.includes("storage"))n=Cl(n,"..");let r=Cl(n,i||"");if(t?.relative)return P1(Ir.cwd(),r);return r}var AT=Ir.env.CLARITY_LOG_DIR||b1(hT(),"logs"),Nw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:AT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Hr={...Nw},wm=(async()=>{try{let{loadConfig:i}=await uT().then(()=>$w),t=await i({name:"clarity",alias:"logging",defaultConfig:Nw,cwd:Ir.cwd()});if(t)Object.assign(Hr,t)}catch{}return Hr})();function ti(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function TT(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nt<"u"){let i=nt.type;if(i==="renderer"||i==="worker")return!1;return!!(nt.versions&&(nt.versions.node||nt.versions.bun))}return!1}class Ww{async format(i){let t=await TT(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:pt.pid,hostname:t(),environment:pt.env.NODE_ENV||"development",platform:pt.platform,version:pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pt.env.NODE_ENV||pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var $i={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,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=$i,ym=$i.red,ET=$i.green,um=$i.yellow,YT=$i.blue,hm=$i.magenta,Am=$i.cyan,Gl=$i.white,Tm=$i.gray,BT=$i.bgRed,CT=$i.bgYellow,Em=$i.bgGray,Ml=$i.bold,Ym=$i.dim,Bm=$i.italic,Cm=$i.underline,Um=$i.strikethrough,jm=$i.reset,X0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},UT={debug:"\uD83D\uDD0D",info:YT("ℹ"),success:ET("✓"),warning:CT(Gl(Ml(" WARN "))),error:BT(Gl(Ml(" ERROR ")))};class Dr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Hr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ww,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),$=this.generateKey();this.currentKeyId=f,this.keys.set(f,$),this.encryptionKeys.set(f,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...X0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...X0};return{...X0,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Hr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,$=3,c=1000;while(f<$)try{try{try{await iA(this.config.logDirectory,Rl.F_OK|Rl.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await tA(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 l=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:pi.from(i);try{if(!hr(this.currentLogFile))await U0(this.currentLogFile,"",{mode:420});if(r=ml(this.currentLogFile,"a",420),o1(r,l,{flag:"a"}),jl(r),r!==void 0)C0(r),r=void 0;if((await Zt(this.currentLogFile)).size===0){if(await U0(this.currentLogFile,l,{flag:"w",mode:420}),(await Zt(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<$-1){let u=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${$}:`,u);let h=c*2**f;await new Promise((A)=>setTimeout(A,h)),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(r!==void 0)try{C0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(l){if(f===$-1){let y=l,u=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let w=c*2**(f-1);await new Promise((y)=>setTimeout(y,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,$=Math.max(1,f);if(r.length>$)for(let[c]of r.slice($))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return B0(16).toString("hex")}generateKey(){return B0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=B0(16),r=Z1("aes-256-gcm",t,n),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),$=r.update(f),c=r.final(),l=$.length+c.length,w=r.getAuthTag(),y=pi.allocUnsafe(16+l+16);return n.copy(y,0),$.copy(y,16),c.copy(y,16+$.length),w.copy(y,16+l),{encrypted:y,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Wl(),f=[];r.on("data",($)=>f.push($)),r.on("end",()=>t(pi.from(pi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await Zt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ar(this.config.logDirectory),$=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let u=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),c=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Zt(n).catch(()=>null))try{if(await Nl(n,l),t.compress)try{let w=`${l}.gz`;await this.compressLogFile(l,w),await Tr(l)}catch(w){console.error("Error compressing rotated file:",w)}if($.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await U0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),$=n.replace(/\.log$/,`-${f}.log`);if(await Zt(n).catch(()=>null))await Nl(n,$)}if(this.currentLogFile=r,t.maxFiles){let f=(await Ar(this.config.logDirectory)).filter(($)=>$.startsWith(this.name)).sort(($,c)=>c.localeCompare($));for(let $ of f.slice(t.maxFiles))await Tr(vt(this.config.logDirectory,$))}}}async compressLogFile(i,t){let n=Ul(i),r=p1(t),f=Wl();await fA(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),hr(this.currentLogFile))try{let i=ml(this.currentLogFile,"r+");jl(i),C0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Ar(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Tr(vt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof L.env.NO_COLOR<"u",t=L.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:$,showTimestamp:c=!0}=i,l=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(c)T.push(t);if($==="warning")T.push("WARN");else if($==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=L.stdout.columns||120,y="";if($==="warning"||$==="error")y=`${n} ${f}`;else if($==="info"||$==="success")y=`${n} ${r} ${f}`;else y=`${n} ${r} ${G.cyan(f)}`;if(!c)return y.trim();let u=l(y).trim().length,h=l(t).length,A=Math.max(1,w-2-u-h);return`${y.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,($,c)=>{let l=Number.parseInt(c,10);return l<t[0].length?String(t[0][l]):$});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,($,c)=>{if(c==="%")return"%";if(r>=t.length)return $;let l=t[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return $}});if(r<t.length)f+=` ${t.slice(r).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let $=G.underline(G.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${l}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),t=t.replace(/`([^`]+)`/g,(n,r)=>G.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>G.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>G.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>G.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>G.strikethrough(r)),t}supportsHyperlinks(){if(ti())return!1;let i=L.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=L.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(nA(t)||t.startsWith("./")||t.startsWith("../"))t=rA(t);else return null;return hr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),$=this.formatFileTimestamp(r),c,l;if(t instanceof Error)c=t.message,l=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":UT[i],A=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:G.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:G.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.error(T),l){let C=l.split(`
|
|
44
|
-
`);for(let E of C)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${$} ${this.environment}.${i.toUpperCase()}: ${c}`),l)console.error(l)}let u=`${$} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
45
|
-
`;if(l)u+=`${l}
|
|
46
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(i,t=""){let n={update:(f,$)=>{},finish:(f)=>{},interrupt:(f,$)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,$)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),$!==void 0)this.activeProgressBar.message=$;if(this.shouldStyleConsole()&&!ti()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,$="info")=>{if(!ti()&&L.stdout.isTTY)L.stdout.write(`
|
|
47
|
-
`);if(this[$==="warning"?"warn":$](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:n,message:`${G.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),$=`${i} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${$}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
48
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":G.green("✓"),tag:y,message:`${$}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ti())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Dr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!hr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ul(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=pi.isBuffer(i)?i:pi.from(i,"base64"),f=r.subarray(0,16),$=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=v1("aes-256-gcm",n,f);l.setAuthTag($);let w=l.update(c),y=l.final(),u=w.length+y.length,h=pi.allocUnsafe(u);return w.copy(h,0),y.copy(h,w.length),h.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ti()}isServerMode(){return!ti()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:$}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let l=f.split(`
|
|
49
|
-
`),w=Math.max(...l.map((A)=>A.length))+2,y=`┌${"─".repeat(w)}┐`,u=`└${"─".repeat(w)}┘`,h=l.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:G.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(y),showTimestamp:!1})),h.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(u),showTimestamp:!1}))}else if(!ti())console.error(`${r} ${this.environment}.INFO: [BOX] ${$}`);let c=`${r} ${this.environment}.INFO: [BOX] ${$}
|
|
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(`${G.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();L.stdin.removeListener("data",n);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(n=i.replace(c,(w,y)=>{if(y==="%")return"%";if(l>=t.length)return w;let u=t[l++];switch(y){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return w}}),l<t.length)n+=` ${t.slice(l).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${l}${c} ${G.cyan(r)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,$=G.green("━".repeat(r)),c=G.gray("━".repeat(f)),l=`[${$}${c}]`,w=`${n}%`.padStart(4),y=i.message?` ${i.message}`:"",u=this.options.showIcons===!1?"":t||n===100?G.green("✓"):G.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",A=`\r${u}${h} ${l} ${w}${y}`,T=L.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,L.stdout.write(i.lastRenderedLine),t)L.stdout.write(`
|
|
52
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ar(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=vt(this.config.logDirectory,r);if(i.before)try{if((await Zt(f)).mtime>=i.before)continue}catch($){console.error(`Failed to get stats for file ${f}:`,$);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Tr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var mm=new Dr("stacks");class Li extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Xw extends Li{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map(($)=>`"${$}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class qr extends Li{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class Sw extends Li{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Fw extends Li{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class i$ extends Li{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Jw extends Li{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class ew extends Li{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Lr extends Li{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Iw extends Li{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class _w extends Li{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var nn={configNotFound(i,t,n){return new Xw(i,t,n)},configLoad(i,t,n){return new qr(i,t,n)},configValidation(i,t,n){return new Sw(i,t,n)},configMerge(i,t,n,r){return new Fw(i,t,n,r)},envVar(i,t,n,r){return new i$(i,t,n,r)},fileSystem(i,t,n){return new Jw(i,t,n)},typeGeneration(i,t,n){return new ew(i,t,n)},schemaValidation(i,t,n){return new Lr(i,t,n)},browserConfig(i,t,n,r){return new Iw(i,t,n,r)},plugin(i,t,n){return new _w(i,t,n)}};async function jT(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:$}=t,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),l===n||!f(c))break;if(r>0)await new Promise((y)=>setTimeout(y,r))}if($!==void 0)return $;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class t${defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:$=!0,customParsers:c={},verbose:l=!1,trackPerformance:w=!0}=n,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(i),h={...t};return this.processObject(h,[],u,{useCamelCase:f,useBackwardCompatibility:$,customParsers:c,verbose:l,configName:i}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return D0.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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=c.map((u)=>this.formatEnvKey(u,r.useCamelCase)),w=`${n}_${l.join("_")}`,y=r.useBackwardCompatibility?`${n}_${c.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,c,n,r);else{let u=Er.env[w]||(y?Er.env[y]:void 0);if(u!==void 0){if(r.verbose){let h=Er.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(u,typeof $,w,r.customParsers,r.configName)}catch(h){if(h instanceof i$)throw h;throw nn.envVar(w,u,typeof $,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[$,c]of Object.entries(r))try{return c(i)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(i,t))try{return $.parse(i)}catch{throw nn.envVar(n,i,`${t} (via ${$.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(Er.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,$=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],$,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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,c,n,r);else r.push({key:l,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${c.join(".")}`,example:this.generateExample($)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
53
|
-
|
|
54
|
-
`;for(let r of i)n+=`${r.key}
|
|
55
|
-
`,n+=` Type: ${r.type}
|
|
56
|
-
`,n+=` Description: ${r.description}
|
|
57
|
-
`,n+=` Example: ${r.example}
|
|
58
|
-
|
|
59
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
60
|
-
|
|
61
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
62
|
-
`,n+=`|----------|------|-------------|----------|
|
|
63
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
64
|
-
`;return n}}function mT(i,t,n={}){return Kw(i,t,n,new WeakMap)}function Kw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:$=!1,customMerger:c}=n;if(t===null||t===void 0)return $?i:t;if(c){let l=c(i,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(i))return zw(i,t,f,r);if(!_i(t)||!_i(i))return t;return XT(i,t,n,r)}function zw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return RT(i,t);case"smart":return NT(i,t,r);default:return t}return t}function RT(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>x0(f,r)))n.push(r);return n}function NT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return WT(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function WT(i,t,n){let r=[...t];for(let f of i){if(!_i(f)){r.push(f);continue}let $=["id","name","key","path","type"],c=!1;for(let l of $)if(l in f){if(r.find((w)=>_i(w)&&(l in w)&&w[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function XT(i,t,n,r){let f=t;if(_i(f)&&r.has(f))return r.get(f);let $={...i};if(_i(f))r.set(f,$);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],w=$[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){$[c]=l;continue}if(_i(l)&&_i(w))$[c]=Kw(w,l,n,r);else if(Array.isArray(l)||Array.isArray(w))$[c]=zw(w,l,n.arrayMergeMode||"smart",r);else $[c]=l}return $}function aw(i,t,n="replace"){return mT(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function x0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!x0(i[n],t[n]))return!1;return!0}if(_i(i)&&_i(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!x0(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Ow{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:$,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let y=_r.getWithFileCheck("file",i);if(y){if(l)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!Yr(i))return null;try{let y=`?t=${Date.now()}`,u=await import(i+y),h=u.default||u,A="default"in u,T=Object.keys(u).length>0;if(!A&&!T)throw new qr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new qr(i,Error("Configuration must export a valid object"),"unknown");let C={config:aw(t,h,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)_r.setWithFileCheck("file",C,i,$);return C}catch(y){throw y instanceof Error?nn.configLoad(i,y):nn.configLoad(i,Error(String(y)))}};if(c)return D0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let $ of r)for(let c of this.extensions)f.push(j0(t,`${$}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let $ of r){if(!$)continue;if(n.push($,`.${$}.config`,`${$}.config`,`.${$}`),i)n.push(`${i}.${$}.config`,`.${i}.${$}.config`)}let f=new Set;return n.filter(($)=>{if(!$||f.has($))return!1;return f.add($),!0})}checkFileAccess(i){return jT(async()=>{return Yr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!Yr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let $ of f)for(let c of this.extensions){let l=j0(i,`${$}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),$=f(i);for(let c of $)if(this.looksLikeConfigFile(c)){let l=j0(i,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!Yr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),$=f(i,"utf8");JSON.parse($)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var ST=/^https?:\/\//;class Gw{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:$=!0,customRules:c=[],trackPerformance:l=!0,verbose:w=!1}=n,y=async()=>{let u=[],h=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:$,customRules:c,trackPerformance:l,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return u.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(l)return await D0.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,n){try{if(!$A(t))throw new Lr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Lr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,$){if($.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),$.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),$.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,l,r,f,$),$.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if($.validateRequired&&t.required){for(let l of t.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(t.properties){for(let[l,w]of Object.entries(t.properties))if(l in c){let y=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],w,y,r,f,$),$.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!l.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let $ of t)try{let c=this.getValueByPath(i,$.path),l=this.validateWithRule(c,$,$.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:$.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,$,c]=r;t.push({path:f,required:!$,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:ST},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var oi=new Dr("bunfig",{showTags:!0});function FT(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class Mw{fileLoader=new Ow;envProcessor=new t$;validator=new Gw;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:$,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;l={...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 u=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),h=!u&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(A||u))throw w;if(h&&(!y||!A))l={...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)l={...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 l={...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||$)await this.validateConfiguration(l.config,f,$,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)oi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);l.metrics=w}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let w=Date.now()-t;throw oi.error(`Configuration loading failed after ${w}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:$,configDir:c,defaultConfig:l,checkEnv:w=!0,arrayStrategy:y="replace",verbose:u=!1}=i,h=$||Vr.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,h,c,l,y,u,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,h,c)),this.finalizeResult(T,A,w,r,u);let C=await this.loadHomeConfiguration(r,f,l,y,u,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,u);let E=await this.loadPackageJsonConfiguration(r,f,h,l,y,u,w);if(E)return A.push(ei(h,"package.json")),this.finalizeResult(E,A,w,r,u);if(A.push(...this.getAllSearchPaths(r,f,h,c)),t)throw nn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,l,w,u),warnings:[`No configuration file found for "${r}"${FT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,$,c,l,w){let y=l?Cr(i,f,c):f,u=this.getLocalDirectories(n,r);for(let h of u){if(c)oi.info(`Searching for configuration in: ${h}`);let A=this.fileLoader.generateConfigPaths(i,h,t),T=await this.fileLoader.tryLoadFromPaths(A,y,{arrayStrategy:$,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(c)oi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,$){if(!i)return null;let c=$?Cr(i,n,f):n,l=[ei(kt(),".config",i),ei(kt(),".config"),kt()];for(let w of l){if(f)oi.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),u=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:r,verbose:f});if(u){if(f)oi.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,$,c){let l=c?Cr(i,r,$):r;try{let w=ei(n,"package.json");if(!j1(w))return null;let y={};try{y=JSON.parse(m1(w,"utf8"))}catch(A){if($)oi.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let u=y[i],h=i;if(!u&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(y[T]){u=y[T],h=T;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if($)oi.success(`Configuration loaded from package.json: ${h}`);return{config:aw(l,u,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if($)oi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let $=n(i);if($)f.push(...$)}if(t){let $=await this.validator.validateConfiguration(i,t);if(!$.isValid)f.push(...$.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw nn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return _r.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);_r.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,ei(i,"config"),ei(i,".config"),t?ei(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(ei(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),$=[];for(let c of f)$.push(...this.fileLoader.generateConfigPaths(i,c,t));return $}getHomeSearchPaths(i,t){if(!i)return[];let n=[ei(kt(),".config",i),ei(kt(),".config"),kt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var Rm=new Mw;function Cr(i,t,n=!1){let r=new t$,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(c,l=[]){let w={...c};for(let[y,u]of Object.entries(c)){let h=[...l,y],A=[`${f}_${h.join("_").toUpperCase()}`,`${f}_${h.map((E)=>E.toUpperCase()).join("")}`,`${f}_${h.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=Vr.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof u==="boolean")w[y]=["true","1","yes"].includes(T.toLowerCase());else if(typeof u==="number"){let E=Number(T);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(u))try{w[y]=JSON.parse(T)}catch{w[y]=T.split(",").map((E)=>E.trim())}else w[y]=T;else if(u&&typeof u==="object"&&!Array.isArray(u))w[y]=$(u,h)}return w}return $(t)}var Nm=ei(Vr.cwd(),"config"),Wm=ei(Vr.cwd(),"src/generated"),Hw={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:$0.join(f0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:$0.join(f0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:$0.join(f0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},v=Hw,Hi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var X={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},ot={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 Lw(i){return g0.readFileSync(i,"utf8")}function k0(i,t){let n=[];function r(f){let $;try{$=g0.readdirSync(f)}catch{return}for(let c of $){let l=Gi.join(f,c);try{if(g0.statSync(l).isDirectory())r(l);else if(c===t)n.push(f)}catch{continue}}}return r(i),n}function N(i,t,n){if(n||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var _T=IT(JT);function xw(){return qw.env.SUDO_PASSWORD}var Hl="[redacted]",KT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),zT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function aT(i){let t=i.toLowerCase();return KT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function xr(i){if(Array.isArray(i))return i.map((n)=>xr(n));if(typeof i==="string")return zT.test(i)?Hl:i;if(!i||typeof i!=="object")return i;let t={};for(let[n,r]of Object.entries(i)){if(aT(n)){t[n]=Hl;continue}t[n]=xr(r)}return t}function Qr(i){return JSON.stringify(xr(i))}function OT(i){let t=xw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let n=t.replace(/'/g,"'\\''"),r=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function Ct(i,t={}){let n=OT(i);try{let{stdout:r,stderr:f}=await _T(n,{cwd:t.cwd||qw.cwd(),timeout:t.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${i}
|
|
65
|
-
Error: ${r.message}`);throw f.stack=r.stack,f}}function gw(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 n$(i){let t=Gi.join(eT.homedir(),".stacks","ssl"),n=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,r=i.certPath?Gi.isAbsolute(i.certPath)?i.certPath:Gi.join(n,i.certPath):Gi.join(n,v.certPath),f=i.keyPath?Gi.isAbsolute(i.keyPath)?i.keyPath:Gi.join(n,i.keyPath):Gi.join(n,v.keyPath),$=i.caCertPath?Gi.isAbsolute(i.caCertPath)?i.caCertPath:Gi.join(n,i.caCertPath):Gi.join(n,v.caCertPath);return{certPath:r,keyPath:f,caCertPath:$,basePath:n}}function kw(i){let t=[],n=new Set;if(i.domain)n.add(i.domain);if(i.domains?.length)i.domains.forEach((r)=>n.add(r));for(let r of n)t.push({type:2,value:r});if(i.altNameIPs?.length)for(let r of i.altNameIPs)t.push({type:7,ip:r});if(i.altNameURIs?.length)for(let r of i.altNameURIs)t.push({type:6,value:r});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return N(X.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function r$(i){let t=i.notBeforeDays??Hi.DEFAULT_NOT_BEFORE_DAYS,n=i.validityDays??(i.validityYears?i.validityYears*365:Hi.DEFAULT_VALIDITY_DAYS);N(X.CERT,"Calculating certificate validity dates",i.verbose);let r=new Date(Date.now()-86400*t*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),N(X.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:r,notAfter:f}}var qi={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},Bi={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function Jn(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Si(i,t){let n=Jn(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function zn(i){let t=i.split(".").map(Number),n=[];n.push(40*t[0]+t[1]);for(let r=2;r<t.length;r++){let f=t[r],$=[];$.unshift(f&127),f>>=7;while(f>0)$.unshift(f&127|128),f>>=7;n.push(...$)}return Si(qi.OID,Buffer.from(n))}function V0(i){let t;if(typeof i==="bigint"){let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Si(qi.INTEGER,t)}function Vw(i,t=0){return Si(qi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function sw(i){return Si(qi.OCTET_STRING,i)}function Xi(...i){return Si(qi.SEQUENCE,Buffer.concat(i))}function GT(...i){return Si(qi.SET,Buffer.concat(i))}function MT(i){return Si(qi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function HT(i){return Si(qi.UTF8_STRING,Buffer.from(i,"utf8"))}function qT(){return Buffer.from([qi.NULL,0])}function ql(i,t,n=!0){let r=160|i|(n?0:0),f=Jn(t.length);return Buffer.concat([Buffer.from([r]),f,t])}function Ll(i){let t=i.getUTCFullYear();if(t>=2050){let n=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Si(qi.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(t%100).toString().padStart(2,"0"),r=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),$=i.getUTCHours().toString().padStart(2,"0"),c=i.getUTCMinutes().toString().padStart(2,"0"),l=i.getUTCSeconds().toString().padStart(2,"0"),w=`${n}${r}${f}${$}${c}${l}Z`;return Si(qi.UTC_TIME,Buffer.from(w,"ascii"))}}function LT(i,t){return Xi(Ll(i),Ll(t))}function xl(i){let t=[];for(let n of i){let r;switch(n.shortName){case"CN":r=Bi.COMMON_NAME;break;case"C":r=Bi.COUNTRY;break;case"L":r=Bi.LOCALITY;break;case"ST":r=Bi.STATE;break;case"O":r=Bi.ORGANIZATION;break;case"OU":r=Bi.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?MT(n.value):HT(n.value),$=Xi(zn(r),f);t.push(GT($))}return Xi(...t)}function dw(i){return Xi(zn(i),qT())}function xT(i){return i.export({type:"spki",format:"der"})}function gT(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),$=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],l=8-$.length-c.length,w=Array.from({length:l},()=>"0");t=[...$,...w,...c].join(":")}let n=t.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let $=Number.parseInt(n[f]||"0",16);r.writeUInt16BE($,f*2)}return r}else{let t=i.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(t)}}function kT(i){let t=[];for(let n of i)if(n.type===2&&n.value){let r=Jn(n.value.length);t.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=gT(n.ip),f=Jn(r.length);t.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=Jn(n.value.length);t.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return Xi(...t)}function VT(i,t){if(i){if(t!==void 0)return Xi(Si(1,Buffer.from([255])),V0(t));return Xi(Si(1,Buffer.from([255])))}return Xi()}function sT(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let n=0,r=t;while(r>0&&(r&1)===0)n++,r>>=1;if(t===0)n=7;return Vw(Buffer.from([t]),n)}function dT(i){let t=[];if(i.serverAuth)t.push(zn(Bi.SERVER_AUTH));if(i.clientAuth)t.push(zn(Bi.CLIENT_AUTH));return Xi(...t)}function Sn(i,t,n){let r=[zn(i)];if(t)r.push(Si(1,Buffer.from([255])));return r.push(sw(n)),Xi(...r)}function DT(i){let t=[];if(t.push(ql(0,V0(2))),t.push(V0(i.serialNumber)),t.push(dw(Bi.SHA256_WITH_RSA)),t.push(xl(i.issuer)),t.push(LT(i.notBefore,i.notAfter)),t.push(xl(i.subject)),t.push(xT(i.publicKey)),i.extensions){let n=[];if(i.extensions.basicConstraints)n.push(Sn(Bi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,VT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)n.push(Sn(Bi.KEY_USAGE,i.extensions.keyUsage.critical??!0,sT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)n.push(Sn(Bi.EXTENDED_KEY_USAGE,!1,dT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)n.push(Sn(Bi.SUBJECT_ALT_NAME,!1,kT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)n.push(Sn(Bi.SUBJECT_KEY_IDENTIFIER,!1,sw(i.extensions.subjectKeyIdentifier)));if(n.length>0)t.push(ql(3,Xi(...n)))}return Xi(...t)}function QT(i,t){let n=rn.createSign("SHA256");n.update(i);let r=n.sign(t);return Xi(i,dw(Bi.SHA256_WITH_RSA),Vw(r))}function bT(i,t){let n=i.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${t}-----
|
|
66
|
-
${r.join(`
|
|
67
|
-
`)}
|
|
68
|
-
-----END ${t}-----
|
|
69
|
-
`}function f$(){let i=rn.randomBytes(20);return i[0]=i[0]&127||1,i}function Dw(i=2048){let{privateKey:t,publicKey:n}=rn.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:n}}function PT(i){let t=i.export({type:"spki",format:"der"});return rn.createHash("sha1").update(t).digest()}function Qw(i){let t={serialNumber:i.serialNumber||f$(),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:PT(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let n=DT(t),r=QT(n,i.signingKey);return{certificate:bT(r,"CERTIFICATE"),certificateDer:r}}function bw(i){return i.export({type:"pkcs8",format:"pem"})}function ZT(i){return rn.createPrivateKey(i)}function vT(i){let t=new rn.X509Certificate(i),n=t.publicKey,r=[],f=t.subject.split(`
|
|
70
|
-
`);for(let $ of f){let[c,...l]=$.split("="),w=l.join("=");if(c&&w)r.push({shortName:c.trim(),value:w.trim()})}return{publicKey:n,subject:r}}async function $$(i={}){N("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Hi.DEFAULT_KEY_SIZE;N("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:n,publicKey:r}=Dw(t),f=[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:$,notAfter:c}=r$({validityYears:i.validityYears||Hi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:l}=Qw({serialNumber:f$(),notBefore:$,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:l,privateKey:bw(n),notBefore:$,notAfter:c}}async function c$(i){if(N("ca","Generating new certificate",i.verbose),N("ca",`Options: ${Qr(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}=vT(i.rootCA.certificate),n=ZT(i.rootCA.privateKey);N("ca",`Generating ${Hi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let r=Hi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:$}=Dw(r),c=i.commonName||gw(i),l=i.certificateAttributes||[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organizationName||v.organizationName},{shortName:"CN",value:c}],{notBefore:w,notAfter:y}=r$({validityDays:i.validityDays||Hi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),u=kw(i),h=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=Qw({serialNumber:f$(),notBefore:w,notAfter:y,subject:l,issuer:t,publicKey:$,signingKey:n,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:h,extendedKeyUsage:A,subjectAltName:u});return{certificate:T,privateKey:bw(f),notBefore:w,notAfter:y}}function Pw(i,t){N(X.STORAGE,`Storing certificate and private key with options: ${Qr(t)}`,t?.verbose);let{certPath:n,keyPath:r}=n$({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});N(X.STORAGE,`Certificate path: ${n}`,t?.verbose),N(X.STORAGE,`Private key path: ${r}`,t?.verbose);let f=s0.dirname(n);if(!rt.existsSync(f))N(X.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),rt.mkdirSync(f,{recursive:!0});N(X.STORAGE,"Writing certificate file",t?.verbose),rt.writeFileSync(n,i.certificate);let $=s0.dirname(r);if(!rt.existsSync($))N(X.STORAGE,`Creating private key directory: ${$}`,t?.verbose),rt.mkdirSync($,{recursive:!0});return N(X.STORAGE,"Writing private key file",t?.verbose),rt.writeFileSync(r,i.privateKey),N(X.STORAGE,"Certificate and private key stored successfully",t?.verbose),n}function Zw(i,t){N(X.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:n}=n$({basePath:t?.basePath,caCertPath:t?.caCertPath});N(X.STORAGE,`CA certificate path: ${n}`,t?.verbose);let r=s0.dirname(n);if(!rt.existsSync(r))N(X.STORAGE,`Creating CA certificate directory: ${r}`,t?.verbose),rt.mkdirSync(r,{recursive:!0});return N(X.STORAGE,"Writing CA certificate file",t?.verbose),rt.writeFileSync(n,i),N(X.STORAGE,"CA certificate stored successfully",t?.verbose),n}function br(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=Lw(i);return new pT.X509Certificate(t)}function Pr(i){return br(i).fingerprint256.replace(/:/g,"").toUpperCase()}function l$(i){return vw(br(i).subject)}function w$(i,t,n=443,r=4000){let f;try{f=t.includes("-----BEGIN")?t:oT.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise(($)=>{let c=!1,l=(y)=>{if(c)return;c=!0,$(y)},w=iE.connect({host:i,port:n,servername:i,ca:f,rejectUnauthorized:!0},()=>{l(w.authorized),w.end()});w.setTimeout(r,()=>{w.destroy(),l(!1)}),w.on("error",()=>l(!1))})}function tE(i){let t=[],n=i.split(`
|
|
71
|
-
`);for(let r of n){let[f,...$]=r.split("="),c=$.join("=");if(f&&c)t.push({shortName:f.trim(),value:c.trim()})}return t}function vw(i){return tE(i).find((t)=>t.shortName==="CN")?.value||""}function nE(i){let t=[],n=vw(i.subject);if(n&&!/^\d+\.\d+\.\d+\.\d+$/.test(n))t.push(n);let r=i.subjectAltName;if(r){let f=r.split(", ");for(let $ of f)if($.startsWith("DNS:"))t.push($.slice(4))}return[...new Set(t)]}function y$(i,t){let n=br(i),r=nE(n);for(let f of r){if(f===t)return!0;if(f.startsWith("*.")){let $=f.slice(2);if(t.endsWith($)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function fE(i,t){if(gr.platform()!=="darwin")return!1;try{let n=Pr(i);if(!n)return N(X.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(rE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
72
|
-
`).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return N(X.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return N(X.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return N(X.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var $E={platform:"darwin",async addCertificate(i,t){if(await fE(i,t?.verbose)){N(X.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),ot.success("Certificate is already trusted in system keychain");return}N(X.TRUST,"Adding certificate to macOS keychain",t?.verbose),await Ct(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await Ct(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(X.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw N(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},cE={platform:"win32",async addCertificate(i,t){N(X.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await Ct(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await Ct(`certutil -delstore -enterprise Root "${r}"`),N(X.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw N(X.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},lE={platform:"linux",async addCertificate(i,t){N(X.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=gr.homedir(),r=Hi.LINUX_CERT_DB_FILENAME,f=Hi.LINUX_TRUST_ARGS;N(X.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let $=k0(n,r);if($.length===0){ot.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of $){N(X.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{N(X.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await Ct(`certutil -d sql:${c} -D -n ${v.commonName}`)}catch(l){N(X.TRUST,`Warning: Error deleting existing cert: ${l}`,t?.verbose),console.warn(`Error deleting existing cert: ${l}`)}N(X.TRUST,`Adding new certificate to ${c}`,t?.verbose),await Ct(`certutil -d sql:${c} -A -t ${f} -n ${v.commonName} -i ${i}`),ot.info(`Cert added to ${c}`)}},async removeCertificate(i,t,n){let r=n||v.commonName;N(X.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=gr.homedir(),$=Hi.LINUX_CERT_DB_FILENAME;N(X.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let c=k0(f,$);if(c.length===0){ot.warn("No certificate databases found. Cannot remove certificate.");return}for(let l of c){N(X.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{await Ct(`certutil -d sql:${l} -D -n "${r}"`),ot.info(`Cert removed from ${l}`)}catch(w){N(X.TRUST,`Error removing cert from ${l}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${l}: ${w}`)}}}},wE={darwin:$E,win32:cE,linux:lE};async function u$(i,t,n){N(X.TRUST,`Adding certificate to system trust store with options: ${Qr(n)}`,n?.verbose),N(X.TRUST,"Storing certificate and private key",n?.verbose);let r=Pw(i,n);N(X.TRUST,"Storing CA certificate",n?.verbose);let f=Zw(t,n),$=gr.platform();N(X.TRUST,`Detected platform: ${$}`,n?.verbose);let c=wE[$];if(!c){let l=`Unsupported platform: ${$}`;throw N(X.TRUST,`Error: ${l}`,n?.verbose),Error(l)}return await c.addCertificate(f,n),N(X.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as p$}from"node:os";import{join as o$,resolve as cW}from"node:path";import{existsSync as pw,statSync as ow}from"fs";import{existsSync as yE,mkdirSync as mR,readdirSync as RR,readFileSync as uE,writeFileSync as NR}from"fs";import{homedir as fn}from"os";import{dirname as SR,resolve as Ki}from"path";import _f from"process";import{existsSync as iy,statSync as ty}from"fs";import{existsSync as _$,mkdirSync as hE,readdirSync as AE,writeFileSync as TE}from"fs";import{homedir as $n}from"os";import{dirname as ny,resolve as Ui}from"path";import at from"process";import{join as EE,relative as YE,resolve as ry}from"path";import Cf from"process";import{existsSync as xy,mkdirSync as GR,readdirSync as MR,writeFileSync as HR}from"fs";import{homedir as h$}from"os";import{dirname as xR,resolve as Ci}from"path";import Gn from"process";import{join as BE,relative as CE,resolve as fy}from"path";import Uf from"process";import{existsSync as gy,mkdirSync as dR,readdirSync as DR,writeFileSync as QR}from"fs";import{dirname as PR,resolve as jf}from"path";import K$ from"process";import{Buffer as mt}from"buffer";import{createCipheriv as UE,createDecipheriv as jE,randomBytes as A$}from"crypto";import{closeSync as T$,createReadStream as $y,createWriteStream as mE,existsSync as E$,fsyncSync as cy,openSync as ly,writeFileSync as RE}from"fs";import{access as NE,constants as wy,mkdir as WE,readdir as Zr,rename as yy,stat as cn,unlink as vr,writeFile as Y$}from"fs/promises";import{join as ln}from"path";import ui from"process";import{pipeline as XE}from"stream/promises";import{createGzip as uy}from"zlib";import wn from"process";import wt from"process";import{Buffer as $t}from"buffer";import{createCipheriv as SE,createDecipheriv as FE,randomBytes as B$}from"crypto";import{closeSync as C$,createReadStream as hy,createWriteStream as JE,existsSync as pr,fsyncSync as Ay,openSync as Ty,writeFileSync as eE}from"fs";import{access as IE,constants as Ey,mkdir as _E,readdir as or,rename as Yy,stat as yn,unlink as tf,writeFile as U$}from"fs/promises";import{isAbsolute as KE,join as un,resolve as zE}from"path";import K from"process";import{pipeline as aE}from"stream/promises";import{createGzip as By}from"zlib";import hn from"process";import yt from"process";import nf from"process";import{existsSync as rf}from"fs";import{resolve as j$}from"path";import{existsSync as OE}from"fs";import{existsSync as GE,readdirSync as ME}from"fs";import{extname as m$,resolve as Cy}from"path";import HE from"process";import{join as qE,relative as LE,resolve as Uy}from"path";import mf from"process";import{Buffer as ct}from"buffer";import{createCipheriv as xE,createDecipheriv as gE,randomBytes as R$}from"crypto";import{closeSync as N$,createReadStream as jy,createWriteStream as kE,existsSync as ff,fsyncSync as my,openSync as Ry,writeFileSync as VE}from"fs";import{access as sE,constants as Ny,mkdir as dE,readdir as $f,rename as Wy,stat as An,unlink as cf,writeFile as W$}from"fs/promises";import{isAbsolute as DE,join as Tn,resolve as QE}from"path";import z from"process";import{pipeline as bE}from"stream/promises";import{createGzip as Xy}from"zlib";import En from"process";import ut from"process";import wf from"process";import{existsSync as yf}from"fs";import{resolve as I$}from"path";import{existsSync as EB}from"fs";class qy{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),$=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:$,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!pw(i))return!0;return ow(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=pw(n)?ow(n):null,$=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:$},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Ly{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let $=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),$}catch($){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),$}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,$)=>f+$,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var Bf=new qy,k$=new Ly;var PE=Object.defineProperty,ZE=(i)=>i;function vE(i,t){this[i]=ZE.bind(null,t)}var pE=(i,t)=>{for(var n in t)PE(i,n,{get:t[n],enumerable:!0,configurable:!0,set:vE.bind(t,n)})},oE=(i,t)=>()=>(i&&(t=i(i=0)),t),ky={};pE(ky,{withErrorRecovery:()=>dy,tryLoadConfig:()=>NY,loadConfigWithResult:()=>mY,loadConfig:()=>Zy,isRetryableError:()=>EY,isConfigNotFoundError:()=>TY,isBunfigError:()=>Dy,globalPerformanceMonitor:()=>qn,globalCache:()=>Yn,getEnvOrDefault:()=>YY,generateConfigTypes:()=>WY,defaultGeneratedDir:()=>fu,defaultConfigDir:()=>ru,deepMergeWithArrayStrategy:()=>Q$,deepMerge:()=>Qy,createLibraryConfig:()=>XY,config:()=>RY,bunfigPlugin:()=>SY,applyEnvVarsToConfig:()=>On,TypeGenerationError:()=>q$,SchemaValidationError:()=>Hn,PluginError:()=>x$,PerformanceMonitor:()=>s$,FileSystemError:()=>H$,ErrorFactory:()=>Rt,EnvVarError:()=>Ff,EnvProcessor:()=>Kf,ConfigValidator:()=>b$,ConfigValidationError:()=>G$,ConfigNotFoundError:()=>Sf,ConfigMergeError:()=>M$,ConfigLoader:()=>P$,ConfigLoadError:()=>Mn,ConfigFileLoader:()=>zf,ConfigCache:()=>V$,CacheUtils:()=>py,BunfigError:()=>Fi,BrowserConfigError:()=>L$,ArrayMergeStrategies:()=>tu});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 n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),$=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:$,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!iy(i))return!0;return ty(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=iy(n)?ty(n):null,$=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:$},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class s${metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let $=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),$}catch($){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),$}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,$)=>f+$,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function iY(i,t={}){let r=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return r?`${i}:${r}`:i}function tY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function nY(i){return i.getStats().size*2}function d$(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&D(t[0])&&"id"in t[0]&&t[0].id===3&&D(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(D(t)&&D(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(D(i)&&"arr"in i&&Array.isArray(i.arr)&&D(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&D(t[0])&&D(i[0])){let r=[...t];for(let f of i)if(D(f)&&"name"in f){if(!r.find((c)=>D(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(D(f)&&"path"in f){if(!r.find((c)=>D(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some(($)=>Rf($,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!D(t)||!D(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(D(f)&&D(n[r]))n[r]=d$(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&D(f[0])&&D(n[r][0])){let $=[...f];for(let c of n[r])if(D(c)&&"name"in c){if(!$.find((w)=>D(w)&&("name"in w)&&w.name===c.name))$.push(c)}else if(D(c)&&"path"in c){if(!$.find((w)=>D(w)&&("path"in w)&&w.path===c.path))$.push(c)}else if(!$.some((l)=>Rf(l,c)))$.push(c);n[r]=$}else if(f.every(($)=>typeof $==="string")&&n[r].every(($)=>typeof $==="string")){let $=[...f];for(let c of n[r])if(!$.includes(c))$.push(c);n[r]=$}else n[r]=f;else n[r]=f}return n}function Rf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Rf(i[n],t[n]))return!1;return!0}if(D(i)&&D(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Rf(i[f],t[f]))return!1}return!0}return!1}function D(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function rY(i,t){if(!gy(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return d$(t,r)}catch{return null}}catch{return null}}async function fY({name:i="",cwd:t,defaultConfig:n}){let r=t||K$.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],$=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of $)for(let l of f){let w=jf(r,`${c}${l}`),y=await rY(w,n);if(y!==null)return y}try{let c=jf(r,"package.json");if(gy(c)){let w=(await import(c))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return d$(n,w)}catch{}}}catch{}return n}function $Y(i,t={}){let n=Uf.cwd();while(n.includes("storage"))n=fy(n,"..");let r=fy(n,i||"");if(t?.relative)return CE(Uf.cwd(),r);return r}async function cY(){try{let i=await fY({name:"clarity",defaultConfig:Af,cwd:Uf.cwd(),endpoint:"",headers:{}});return{...Af,...i}}catch{return Af}}function P(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lY(){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 Vy{async format(i){let t=await lY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:wn.pid,hostname:t(),environment:wn.env.NODE_ENV||"development",platform:wn.platform,version:wn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wn.env.NODE_ENV||wn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Nf{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={...a$},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Vy,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??ui.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),$=this.generateKey();this.currentKeyId=f,this.keys.set(f,$),this.encryptionKeys.set(f,{key:$,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Tf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Tf};return{...Tf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:a$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let n=(async()=>{let f,$=0,c=3,l=1000;while($<c)try{try{try{await NE(this.config.logDirectory,wy.F_OK|wy.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await WE(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(!E$(this.currentLogFile))await Y$(this.currentLogFile,"",{mode:420});if(f=ly(this.currentLogFile,"a",420),RE(f,w,{flag:"a"}),cy(f),f!==void 0)T$(f),f=void 0;if((await cn(this.currentLogFile)).size===0){if(await Y$(this.currentLogFile,w,{flag:"w",mode:420}),(await cn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let u=y;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if($<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${c}:`,h);let A=l*2**$;await new Promise((T)=>setTimeout(T,A)),$++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(f!==void 0)try{T$(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if($===c-1){let u=w,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),w}$++;let y=l*2**($-1);await new Promise((u)=>setTimeout(u,y))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ln(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 ln(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ln(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,w])=>w.createdAt.getTime()-l.createdAt.getTime()),$=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,$);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return A$(16).toString("hex")}generateKey(){return A$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=A$(16),r=UE("aes-256-gcm",t,n),f=mt.concat([r.update(i,"utf8"),r.final()]),$=r.getAuthTag();return{encrypted:mt.concat([n,f,$]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=uy(),f=[];r.on("data",($)=>f.push($)),r.on("end",()=>t(mt.from(mt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await cn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Zr(this.config.logDirectory),$=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let u=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),c=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await cn(n).catch(()=>null))try{if(await yy(n,l),t.compress)try{let w=`${l}.gz`;await this.compressLogFile(l,w),await vr(l)}catch(w){console.error("Error compressing rotated file:",w)}if($.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Y$(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,"-"),$=n.replace(/\.log$/,`-${f}.log`);if(await cn(n).catch(()=>null))await yy(n,$)}if(this.currentLogFile=r,t.maxFiles){let $=(await Zr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of $.slice(t.maxFiles))await vr(ln(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=$y(i),r=mE(t),f=uy();await XE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),E$(this.currentLogFile))try{let i=ly(this.currentLogFile,"r+");cy(i),T$(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 Zr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await vr(ln(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?s.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:$,showTimestamp:c=!0}=i,l=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(c)T.push(t);if($==="warning")T.push("WARN");else if($==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=ui.stdout.columns||120,y="";if($==="warning"||$==="error")y=`${n} ${f}`;else if($==="info"||$==="success")y=`${n} ${r} ${f}`;else y=`${n} ${r} ${s.cyan(f)}`;if(!c)return y.trim();let u=l(y).trim().length,h=l(t).length,A=Math.max(1,w-2-u-h);return`${y.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,($,c)=>{let l=Number.parseInt(c,10);return l<t[0].length?String(t[0][l]):$});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,($,c)=>{if(c==="%")return"%";if(r>=t.length)return $;let l=t[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return $}});if(r<t.length)f+=` ${t.slice(r).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),$=this.formatFileTimestamp(r),c,l;if(t instanceof Error)c=t.message,l=t.stack;else c=this.formatMessage(t,n);if(this.fancy&&!P()){let y=oy[i],u=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",h;switch(i){case"debug":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:s.gray(c),level:i}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:c,level:i}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:s.green(c),level:i}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:c,level:i}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:f,icon:y,tag:u,message:c,level:i}),console.error(h),l){let A=l.split(`
|
|
73
|
-
`);for(let T of A)if(T.trim()&&!T.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:s.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${$} ${this.environment}.${i.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(i))return;let w=`${$} ${this.environment}.${i.toUpperCase()}: ${c}
|
|
74
|
-
`;if(l)w+=`${l}
|
|
75
|
-
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!P()){let n=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:s.blue("◐"),tag:n,message:`${s.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),$=`${i} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${$}`;if(n)y+=` ${JSON.stringify(n)}`;if(y+=`
|
|
76
|
-
`,y=y.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let u=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:s.green("✓"),tag:u,message:`${$}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=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(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!E$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $y(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=mt.isBuffer(i)?i:mt.from(i,"base64"),f=r.slice(0,16),$=r.slice(-16),c=r.slice(16,-16),l=jE("aes-256-gcm",n,f);return l.setAuthTag($),mt.concat([l.update(c),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!P()){let $=i.split(`
|
|
77
|
-
`),c=Math.max(...$.map((u)=>u.length))+2,l=`┌${"─".repeat(c)}┐`,w=`└${"─".repeat(c)}┘`,y=$.map((u)=>{let h=" ".repeat(c-u.length-2);return`│ ${u}${h} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:s.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:s.cyan(l)})),y.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:s.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:s.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${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(`${s.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();ui.stdin.removeListener("data",n);try{if(typeof ui.stdin.setRawMode==="function")ui.stdin.setRawMode(!1)}catch{}ui.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof ui.stdin.setRawMode==="function")ui.stdin.setRawMode(!0)}catch{}ui.stdin.resume(),ui.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(n=i.replace(c,(w,y)=>{if(y==="%")return"%";if(l>=t.length)return w;let u=t[l++];switch(y){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return w}}),l<t.length)n+=` ${t.slice(l).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?s.gray(this.formatTag(this.name)):"",l=s.blue("◐");console.error(`${l} ${c} ${s.cyan(n)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
79
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}progress(i,t=""){if(!this.enabled||!this.fancy||P()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,c)),l!==void 0)this.activeProgressBar.message=l;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,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;ui.stdout.write(`${"\r".padEnd(ui.stdout.columns||80)}\r`),this.log(l,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!ui.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,$=s.green("━".repeat(r)),c=s.gray("━".repeat(f)),l=`[${$}${c}]`,w=`${n}%`.padStart(4),y=i.message?` ${i.message}`:"",u=t||n===100?s.green("✓"):s.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",A=`\r${u}${h} ${l} ${w}${y}`,T=ui.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,ui.stdout.write(i.lastRenderedLine),t)ui.stdout.write(`
|
|
80
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!ui.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 Zr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let $=ln(this.config.logDirectory,r);if(i.before)try{if((await cn($)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${$}:`,c);continue}n.push($)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await vr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function hf(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&k(t[0])&&"id"in t[0]&&t[0].id===3&&k(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(k(t)&&k(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(k(i)&&"arr"in i&&Array.isArray(i.arr)&&k(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&k(t[0])&&k(i[0])){let r=[...t];for(let f of i)if(k(f)&&"name"in f){if(!r.find((c)=>k(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(k(f)&&"path"in f){if(!r.find((c)=>k(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some(($)=>Wf($,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!k(t)||!k(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(k(f)&&k(n[r]))n[r]=hf(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&k(f[0])&&k(n[r][0])){let $=[...f];for(let c of n[r])if(k(c)&&"name"in c){if(!$.find((w)=>k(w)&&("name"in w)&&w.name===c.name))$.push(c)}else if(k(c)&&"path"in c){if(!$.find((w)=>k(w)&&("path"in w)&&w.path===c.path))$.push(c)}else if(!$.some((l)=>Wf(l,c)))$.push(c);n[r]=$}else if(f.every(($)=>typeof $==="string")&&n[r].every(($)=>typeof $==="string")){let $=[...f];for(let c of n[r])if(!$.includes(c))$.push(c);n[r]=$}else n[r]=f;else n[r]=f}return n}function D$(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:hf(i,t);if(Array.isArray(i))return n==="replace"?t:hf(i,t);if(!k(t)||!k(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let $=t[f],c=r[f];if($===null||$===void 0)continue;if(Array.isArray($)||Array.isArray(c))if(n==="replace")r[f]=$;else r[f]=hf(c,$);else if(k($)&&k(c))r[f]=D$(c,$,n);else r[f]=$}return r}function Wf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Wf(i[n],t[n]))return!1;return!0}if(k(i)&&k(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Wf(i[f],t[f]))return!1}return!0}return!1}function k(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function lf(i,t,n="replace"){if(!xy(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return D$(t,f,n)}catch{return null}}catch{return null}}function wY(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function $(c,l=[]){let w={...c};for(let[y,u]of Object.entries(c)){let h=[...l,y],A=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${r}_${h.map(A).join("_")}`,C=`${r}_${h.map((E)=>E.toUpperCase()).join("_")}`;if(n)Ai.info(`Checking environment variable ${T} for config ${i}.${h.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))w[y]=$(u,h);else{let E=Gn.env[T]||Gn.env[C];if(E!==void 0){if(n)Ai.info(`Using environment variable ${E?T:C} for config ${i}.${h.join(".")}`);if(typeof u==="number")w[y]=Number(E);else if(typeof u==="boolean")w[y]=E.toLowerCase()==="true";else if(Array.isArray(u))try{let B=JSON.parse(E);if(Array.isArray(B))w[y]=B;else w[y]=E.split(",").map((U)=>U.trim())}catch{w[y]=E.split(",").map((B)=>B.trim())}else w[y]=E}}}return w}return $(f)}async function yY({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:$=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let w=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?wY(i,f,$):f,y=n||Gn.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if($)Ai.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${y}`);let h=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([y,Ci(y,"config"),Ci(y,".config"),r?Ci(y,r):void 0].filter(Boolean)));for(let B of E){if($)Ai.info(`Searching for configuration in: ${B}`);let m=[Ci(y,"config"),Ci(y,".config")].concat(r?[Ci(y,r)]:[]).includes(B)?[...h,...A,...T,...C]:[...A,...h,...C,...T];for(let S of m)for(let F of u){let W=Ci(B,`${S}${F}`),J=await lf(W,w,l);if(J!==null){if($)Ai.success(`Configuration loaded from: ${W}`);return J}}}if(i){let B=Ci(h$(),".config",i),U=["config",`${i}.config`];if(t)U.push(`${t}.config`);if($)Ai.info(`Checking user config directory: ${B}`);for(let m of U)for(let S of u){let F=Ci(B,`${m}${S}`),W=await lf(F,w,l);if(W!==null){if($)Ai.success(`Configuration loaded from user config directory: ${F}`);return W}}}if(i){let B=Ci(h$(),".config"),U=[`.${i}.config`];if(t)U.push(`.${t}.config`);if($)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let m of U)for(let S of u){let F=Ci(B,`${m}${S}`),W=await lf(F,w,l);if(W!==null){if($)Ai.success(`Configuration loaded from user config directory dotfile: ${F}`);return W}}}if(i){let B=h$(),U=[`.${i}.config`,`.${i}`];if(t)U.push(`.${t}.config`),U.push(`.${t}`);if($)Ai.info(`Checking user home directory for dotfile configs: ${B}`);for(let m of U)for(let S of u){let F=Ci(B,`${m}${S}`),W=await lf(F,w,l);if(W!==null){if($)Ai.success(`Configuration loaded from user home directory: ${F}`);return W}}}try{let B=Ci(y,"package.json");if(xy(B)){let U=await import(B),m=U[i];if(!m&&t){if(m=U[t],m&&$)Ai.success(`Using alias "${t}" configuration from package.json`)}if(m&&typeof m==="object"&&!Array.isArray(m))try{if($)Ai.success(`Configuration loaded from package.json: ${m===U[i]?i:t}`);return D$(w,m,l)}catch(S){if($)Ai.warn("Failed to merge package.json config:",S)}}}catch(B){if($)Ai.warn("Failed to load package.json:",B)}if($)Ai.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function uY(i,t={}){let n=Cf.cwd();while(n.includes("storage"))n=ry(n,"..");let r=ry(n,i||"");if(t?.relative)return YE(Cf.cwd(),r);return r}async function hY(){try{let i=await yY({name:"clarity",alias:"logging",defaultConfig:Ef,cwd:Cf.cwd()});return{...Ef,...i||{}}}catch{return Ef}}function ni(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function AY(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof yt<"u"){let i=yt.type;if(i==="renderer"||i==="worker")return!1;return!!(yt.versions&&(yt.versions.node||yt.versions.bun))}return!1}class sy{async format(i){let t=await AY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:hn.pid,hostname:t(),environment:hn.env.NODE_ENV||"development",platform:hn.platform,version:hn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hn.env.NODE_ENV||hn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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={...O$},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new sy,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??K.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),$=this.generateKey();this.currentKeyId=f,this.keys.set(f,$),this.encryptionKeys.set(f,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Yf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Yf};return{...Yf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:O$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,$=0,c=3,l=1000;while($<c)try{try{try{await IE(this.config.logDirectory,Ey.F_OK|Ey.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await _E(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:$t.from(i);try{if(!pr(this.currentLogFile))await U$(this.currentLogFile,"",{mode:420});if(f=Ty(this.currentLogFile,"a",420),eE(f,w,{flag:"a"}),Ay(f),f!==void 0)C$(f),f=void 0;if((await yn(this.currentLogFile)).size===0){if(await U$(this.currentLogFile,w,{flag:"w",mode:420}),(await yn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let u=y;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if($<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${c}:`,h);let A=l*2**$;await new Promise((T)=>setTimeout(T,A)),$++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(f!==void 0)try{C$(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if($===c-1){let u=w,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),w}$++;let y=l*2**($-1);await new Promise((u)=>setTimeout(u,y))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return un(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 un(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return un(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,w])=>w.createdAt.getTime()-l.createdAt.getTime()),$=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,$);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return B$(16).toString("hex")}generateKey(){return B$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=B$(16),r=SE("aes-256-gcm",t,n),f=$t.isBuffer(i)?i:$t.from(i,"utf8"),$=r.update(f),c=r.final(),l=$.length+c.length,w=r.getAuthTag(),y=$t.allocUnsafe(16+l+16);return n.copy(y,0),$.copy(y,16),c.copy(y,16+$.length),w.copy(y,16+l),{encrypted:y,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=By(),f=[];r.on("data",($)=>f.push($)),r.on("end",()=>t($t.from($t.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await yn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await or(this.config.logDirectory),$=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let u=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),c=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await yn(n).catch(()=>null))try{if(await Yy(n,l),t.compress)try{let w=`${l}.gz`;await this.compressLogFile(l,w),await tf(l)}catch(w){console.error("Error compressing rotated file:",w)}if($.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await U$(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,"-"),$=n.replace(/\.log$/,`-${f}.log`);if(await yn(n).catch(()=>null))await Yy(n,$)}if(this.currentLogFile=r,t.maxFiles){let $=(await or(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of $.slice(t.maxFiles))await tf(un(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=hy(i),r=JE(t),f=By();await aE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pr(this.currentLogFile))try{let i=Ty(this.currentLogFile,"r+");Ay(i),C$(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await or(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await tf(un(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof K.env.NO_COLOR<"u",t=K.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof K.stderr<"u"&&K.stderr.isTTY||typeof K.stdout<"u"&&K.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:$,showTimestamp:c=!0}=i,l=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(c)T.push(t);if($==="warning")T.push("WARN");else if($==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=K.stdout.columns||120,y="";if($==="warning"||$==="error")y=`${n} ${f}`;else if($==="info"||$==="success")y=`${n} ${r} ${f}`;else y=`${n} ${r} ${O.cyan(f)}`;if(!c)return y.trim();let u=l(y).trim().length,h=l(t).length,A=Math.max(1,w-2-u-h);return`${y.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,($,c)=>{let l=Number.parseInt(c,10);return l<t[0].length?String(t[0][l]):$});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,($,c)=>{if(c==="%")return"%";if(r>=t.length)return $;let l=t[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return $}});if(r<t.length)f+=` ${t.slice(r).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let $=O.underline(O.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${l}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),t=t.replace(/`([^`]+)`/g,(n,r)=>O.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>O.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>O.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>O.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>O.strikethrough(r)),t}supportsHyperlinks(){if(ni())return!1;let i=K.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=K.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(KE(t)||t.startsWith("./")||t.startsWith("../"))t=zE(t);else return null;return pr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),$=this.formatFileTimestamp(r),c,l;if(t instanceof Error)c=t.message,l=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":iu[i],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:O.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:O.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.error(T),l){let C=l.split(`
|
|
81
|
-
`);for(let E of C)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${$} ${this.environment}.${i.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(i))return;let u=`${$} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
82
|
-
`;if(l)u+=`${l}
|
|
83
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(i,t=""){let n={update:(l,w)=>{},finish:(l)=>{},interrupt:(l,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ni()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,w="info")=>{if(!ni()&&K.stdout.isTTY)K.stdout.write(`
|
|
84
|
-
`);if(this[w==="warning"?"warn":w](l),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:n,message:`${O.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),$=`${i} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${$}`;if(n)y+=` ${JSON.stringify(n)}`;if(y+=`
|
|
85
|
-
`,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":O.green("✓"),tag:u,message:`${$}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ni())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}`,n=new Xf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!pr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return hy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=$t.isBuffer(i)?i:$t.from(i,"base64"),f=r.subarray(0,16),$=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=FE("aes-256-gcm",n,f);l.setAuthTag($);let w=l.update(c),y=l.final(),u=w.length+y.length,h=$t.allocUnsafe(u);return w.copy(h,0),y.copy(h,w.length),h.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ni()}isServerMode(){return!ni()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:$}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let l=f.split(`
|
|
86
|
-
`),w=Math.max(...l.map((A)=>A.length))+2,y=`┌${"─".repeat(w)}┐`,u=`└${"─".repeat(w)}┘`,h=l.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:O.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(y),showTimestamp:!1})),h.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(u),showTimestamp:!1}))}else if(!ni())console.error(`${r} ${this.environment}.INFO: [BOX] ${$}`);let c=`${r} ${this.environment}.INFO: [BOX] ${$}
|
|
87
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();K.stdin.removeListener("data",n);try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!1)}catch{}K.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!0)}catch{}K.stdin.resume(),K.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,y=0;if(n=i.replace(w,(u,h)=>{if(h==="%")return"%";if(y>=t.length)return u;let A=t[y++];switch(h){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return u}}),y<t.length)n+=` ${t.slice(y).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${y}${w} ${O.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
88
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!K.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,$=O.green("━".repeat(r)),c=O.gray("━".repeat(f)),l=`[${$}${c}]`,w=`${n}%`.padStart(4),y=i.message?` ${i.message}`:"",u=this.options.showIcons===!1?"":t||n===100?O.green("✓"):O.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",A=`\r${u}${h} ${l} ${w}${y}`,T=K.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,K.stdout.write(i.lastRenderedLine),t)K.stdout.write(`
|
|
89
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!K.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await or(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let $=un(this.config.logDirectory,r);if(i.before)try{if((await yn($)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${$}:`,c);continue}n.push($)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await tf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function dy(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:$}=t,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),l===n||!f(c))break;if(r>0)await new Promise((y)=>setTimeout(y,r))}if($!==void 0)return $;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function Dy(i){return i instanceof Fi}function TY(i){return i instanceof Sf}function EY(i){if(Dy(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>i.message.toLowerCase().includes(n.toLowerCase()))}class Kf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:$=!0,customParsers:c={},verbose:l=!1,trackPerformance:w=!0}=n,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(i),h={...t};return this.processObject(h,[],u,{useCamelCase:f,useBackwardCompatibility:$,customParsers:c,verbose:l,configName:i}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return qn.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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=c.map((u)=>this.formatEnvKey(u,r.useCamelCase)),w=`${n}_${l.join("_")}`,y=r.useBackwardCompatibility?`${n}_${c.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,c,n,r);else{let u=nf.env[w]||(y?nf.env[y]:void 0);if(u!==void 0){if(r.verbose){let h=nf.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(u,typeof $,w,r.customParsers,r.configName)}catch(h){if(h instanceof Ff)throw h;throw Rt.envVar(w,u,typeof $,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[$,c]of Object.entries(r))try{return c(i)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(i,t))try{return $.parse(i)}catch{throw Rt.envVar(n,i,`${t} (via ${$.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(nf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,$=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],$,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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,c,n,r);else r.push({key:l,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${c.join(".")}`,example:this.generateExample($)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
90
|
-
|
|
91
|
-
`;for(let r of i)n+=`${r.key}
|
|
92
|
-
`,n+=` Type: ${r.type}
|
|
93
|
-
`,n+=` Description: ${r.description}
|
|
94
|
-
`,n+=` Example: ${r.example}
|
|
95
|
-
|
|
96
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
97
|
-
|
|
98
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
99
|
-
`,n+=`|----------|------|-------------|----------|
|
|
100
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
101
|
-
`;return n}}function YY(i,t){let n=vy("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Qy(i,t,n={}){return by(i,t,n,new WeakMap)}function by(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:$=!1,customMerger:c}=n;if(t===null||t===void 0)return $?i:t;if(c){let l=c(i,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(i))return Py(i,t,f,r);if(!zi(t)||!zi(i))return t;return jY(i,t,n,r)}function Py(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return BY(i,t);case"smart":return CY(i,t,r);default:return t}return t}function BY(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>z$(f,r)))n.push(r);return n}function CY(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return UY(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function UY(i,t,n){let r=[...t];for(let f of i){if(!zi(f)){r.push(f);continue}let $=["id","name","key","path","type"],c=!1;for(let l of $)if(l in f){if(r.find((y)=>zi(y)&&(l in y)&&y[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function jY(i,t,n,r){let f=t;if(zi(f)&&r.has(f))return r.get(f);let $={...i};if(zi(f))r.set(f,$);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],w=$[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){$[c]=l;continue}if(zi(l)&&zi(w))$[c]=by(w,l,n,r);else if(Array.isArray(l)||Array.isArray(w))$[c]=Py(w,l,n.arrayMergeMode||"smart",r);else $[c]=l}return $}function Q$(i,t,n="replace"){return Qy(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function z$(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!z$(i[n],t[n]))return!1;return!0}if(zi(i)&&zi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!z$(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class zf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:$,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let y=Yn.getWithFileCheck("file",i);if(y){if(l)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!rf(i))return null;try{let y=`?t=${Date.now()}`,u=await import(i+y),h=u.default||u,A="default"in u,T=Object.keys(u).length>0;if(!A&&!T)throw new Mn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new Mn(i,Error("Configuration must export a valid object"),"unknown");let B={config:Q$(t,h,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Yn.setWithFileCheck("file",B,i,$);return B}catch(y){throw y instanceof Error?Rt.configLoad(i,y):Rt.configLoad(i,Error(String(y)))}};if(c)return qn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let $ of r)for(let c of this.extensions)f.push(j$(t,`${$}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return dy(async()=>{return rf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!rf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let $ of f)for(let c of this.extensions){let l=j$(i,`${$}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),$=f(i);for(let c of $)if(this.looksLikeConfigFile(c)){let l=j$(i,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!rf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),$=f(i,"utf8");JSON.parse($)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class b${async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:$=!0,customRules:c=[],trackPerformance:l=!0,verbose:w=!1}=n,y=async()=>{let u=[],h=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:$,customRules:c,trackPerformance:l,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return u.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(l)return await qn.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,n){try{if(!OE(t))throw new Hn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Hn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,$){if($.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),$.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),$.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,l,r,f,$),$.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if($.validateRequired&&t.required){for(let l of t.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(t.properties){for(let[l,w]of Object.entries(t.properties))if(l in c){let y=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],w,y,r,f,$),$.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!l.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let $ of t)try{let c=this.getValueByPath(i,$.path),l=this.validateWithRule(c,$,$.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:$.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,$,c]=r;t.push({path:f,required:!$,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:nu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class P${fileLoader=new zf;envProcessor=new Kf;validator=new b$;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:$,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;l={...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 u=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),h=!u&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(A||u))throw w;if(h&&(!y||!A))l={...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)l={...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 l={...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||$)await this.validateConfiguration(l.config,f,$,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)xi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);l.metrics=w}return l}catch(l){let w=Date.now()-t;throw xi.error(`Configuration loading failed after ${w}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:$,configDir:c,defaultConfig:l,checkEnv:w=!0,arrayStrategy:y="replace",verbose:u=!1}=i,h=$||at.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,h,c,l,y,u,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,h,c)),this.finalizeResult(T,A,w,r,u);let C=await this.loadHomeConfiguration(r,f,l,y,u,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,u);let E=await this.loadPackageJsonConfiguration(r,f,h,l,y,u,w);if(E)return A.push(Ui(h,"package.json")),this.finalizeResult(E,A,w,r,u);if(A.push(...this.getAllSearchPaths(r,f,h,c)),t)throw Rt.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,l,w,u),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,$,c,l,w){let y=l?On(i,f,c):f,u=this.getLocalDirectories(n,r);for(let h of u){if(c)xi.info(`Searching for configuration in: ${h}`);let A=this.fileLoader.generateConfigPaths(i,h,t),T=await this.fileLoader.tryLoadFromPaths(A,y,{arrayStrategy:$,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(c)xi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,$){if(!i)return null;let c=$?On(i,n,f):n,l=[Ui($n(),".config",i),Ui($n(),".config"),$n()];for(let w of l){if(f)xi.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),u=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:r,verbose:f});if(u){if(f)xi.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,$,c){let l=c?On(i,r,$):r;try{let w=Ui(n,"package.json");if(!_$(w))return null;let y=await import(w),u=y[i],h=i;if(!u&&t)u=y[t],h=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if($)xi.success(`Configuration loaded from package.json: ${h}`);return{config:Q$(l,u,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if($)xi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:On(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let $=n(i);if($)f.push(...$)}if(t){let $=await this.validator.validateConfiguration(i,t);if(!$.isValid)f.push(...$.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Rt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Yn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Yn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ui(i,"config"),Ui(i,".config"),t?Ui(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ui(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),$=[];for(let c of f)$.push(...this.fileLoader.generateConfigPaths(i,c,t));return $}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ui($n(),".config",i),Ui($n(),".config"),$n()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Sy(i){let n=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return n||r}async function mY(i){return ht.loadConfig({...i,__strictErrorHandling:!0})}async function Zy(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ht.loadConfig(i);else r=await ht.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",$=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||$.includes("config"))&&i.verbose)xi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ht.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function RY(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ht.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Sy(n)))return(await ht.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ht.loadConfig({...i,cwd:i.cwd||at.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Sy(t)))return(await ht.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function NY(i,t,n="replace"){let r=new zf;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function On(i,t,n=!1){let r=new Kf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(c,l=[]){let w={...c};for(let[y,u]of Object.entries(c)){let h=[...l,y],A=[`${f}_${h.join("_").toUpperCase()}`,`${f}_${h.map((E)=>E.toUpperCase()).join("")}`,`${f}_${h.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=at.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof u==="boolean")w[y]=["true","1","yes"].includes(T.toLowerCase());else if(typeof u==="number"){let E=Number(T);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(u))try{w[y]=JSON.parse(T)}catch{w[y]=T.split(",").map((E)=>E.trim())}else w[y]=T;else if(u&&typeof u==="object"&&!Array.isArray(u))w[y]=$(u,h)}return w}return $(t)}function WY(i){let t=Ui(at.cwd(),i.configDir),n=Ui(at.cwd(),i.generatedDir),r=Ui(n,"config-types.ts");if(!_$(ny(r)))hE(ny(r),{recursive:!0,mode:511});let f=_$(t)?AE(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],$=`// Generated by bunfig v${pY}
|
|
102
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
103
|
-
`;TE(r,$,{mode:438})}function XY(i){let t=null,n=null,r=()=>{if(!n)n=Zy(i).then(($)=>{return t=$,$},($)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)xi.warn("Config loading failed, using defaults:",[$ instanceof Error?$:Error(String($))]);return c});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get($,c){if(t)return t[c];let l=f[c];return r(),l},has($,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor($,c){return Object.getOwnPropertyDescriptor(t||f,c)},set($,c,l){if(!t)t={...f};return t[c]=l,!0}})}function SY(i){let t=Cy(HE.cwd(),i?.configDir||"./config");function n(){if(!GE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),$=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=ME(t).filter((w)=>f.has(m$(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),l=new Map;for(let{base:w,file:y}of c){let u=m$(y).toLowerCase(),h=l.get(w);if(!h){l.set(w,y);continue}let A=m$(h).toLowerCase();if($.indexOf(u)<$.indexOf(A))l.set(w,y)}return Array.from(l.entries()).map(([w,y])=>({base:w,file:y})).sort((w,y)=>w.base.localeCompare(y.base))}function r(){let f=n(),$=f.map((y)=>y.base),c=$.length?$.map((y)=>`'${y}'`).join(" | "):"string",l=f.length?`{
|
|
104
|
-
${f.map((y)=>{let u=Cy(t,y.file).replace(/\\/g,"/");return` '${y.base}': typeof import('${u}').default`}).join(`,
|
|
105
|
-
`)}
|
|
106
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
107
|
-
export type ConfigByName = ${l}
|
|
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$/},($)=>{return{path:$.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var vy,Yn,qn,py,FY,JY,Fy,Af,a$,hi,s,eY,Jy,IY,ey,_Y,KY,X$,zY,Iy,_y,S$,aY,OY,GY,MY,Tf,oy,HY,Ai,qY,LY,Ky,Ef,O$,ri,O,xY,zy,gY,ay,kY,VY,F$,sY,Oy,Gy,dY,J$,DY,QY,bY,PY,ZY,Yf,iu,vY,pY="0.15.6",Fi,Sf,Mn,G$,M$,Ff,H$,q$,Hn,L$,x$,Rt,tu,nu,xi,ht,ru,fu,oY=oE(async()=>{vy=import.meta.require,Yn=new V$,qn=new s$,py={createKey:iY,isEquivalent:tY,estimateMemoryUsage:nY},FY=jf(K$.cwd(),"config"),JY=jf(K$.cwd(),"src/generated"),Fy=Uf.env.CLARITY_LOG_DIR||BE($Y(),"logs"),Af={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},a$=await cY(),hi={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"},s=hi,eY=hi.red,Jy=hi.green,IY=hi.yellow,ey=hi.blue,_Y=hi.magenta,KY=hi.cyan,X$=hi.white,zY=hi.gray,Iy=hi.bgRed,_y=hi.bgYellow,S$=hi.bold,aY=hi.dim,OY=hi.italic,GY=hi.underline,MY=hi.reset,Tf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oy={debug:"\uD83D\uDD0D",info:ey("ℹ"),success:Jy("✓"),warning:_y(X$(S$(" WARN "))),error:Iy(X$(S$(" ERROR ")))},HY=new Nf("stacks"),Ai=new Nf("bunfig",{showTags:!0}),qY=Ci(Gn.cwd(),"config"),LY=Ci(Gn.cwd(),"src/generated"),Ky=Cf.env.CLARITY_LOG_DIR||EE(uY(),"logs"),Ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ky,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},O$=await hY(),ri={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=ri,xY=ri.red,zy=ri.green,gY=ri.yellow,ay=ri.blue,kY=ri.magenta,VY=ri.cyan,F$=ri.white,sY=ri.gray,Oy=ri.bgRed,Gy=ri.bgYellow,dY=ri.bgGray,J$=ri.bold,DY=ri.dim,QY=ri.italic,bY=ri.underline,PY=ri.strikethrough,ZY=ri.reset,Yf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},iu={debug:"\uD83D\uDD0D",info:ay("ℹ"),success:zy("✓"),warning:Gy(F$(J$(" WARN "))),error:Oy(F$(J$(" ERROR ")))},vY=new Xf("stacks"),Fi=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Sf=class extends Fi{code="CONFIG_NOT_FOUND";constructor(t,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},Mn=class extends Fi{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},G$=class extends Fi{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},M$=class extends Fi{code="CONFIG_MERGE_ERROR";constructor(t,n,r,f){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},Ff=class extends Fi{code="ENV_VAR_ERROR";constructor(t,n,r,f){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:f})}},H$=class extends Fi{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},q$=class extends Fi{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Hn=class extends Fi{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},L$=class extends Fi{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,f){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:f})}},x$=class extends Fi{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Rt={configNotFound(i,t,n){return new Sf(i,t,n)},configLoad(i,t,n){return new Mn(i,t,n)},configValidation(i,t,n){return new G$(i,t,n)},configMerge(i,t,n,r){return new M$(i,t,n,r)},envVar(i,t,n,r){return new Ff(i,t,n,r)},fileSystem(i,t,n){return new H$(i,t,n)},typeGeneration(i,t,n){return new q$(i,t,n)},schemaValidation(i,t,n){return new Hn(i,t,n)},browserConfig(i,t,n,r){return new L$(i,t,n,r)},plugin(i,t,n){return new x$(i,t,n)}},tu={replace:"replace",concat:"concat",smart:"smart"},nu=/^https?:\/\//,xi=new Xf("bunfig",{showTags:!0}),ht=new P$,ru=Ui(at.cwd(),"config"),fu=Ui(at.cwd(),"src/generated")});function iB(i,t={}){let n=mf.cwd();while(n.includes("storage"))n=Uy(n,"..");let r=Uy(n,i||"");if(t?.relative)return LE(mf.cwd(),r);return r}var tB=mf.env.CLARITY_LOG_DIR||qE(iB(),"logs"),$u={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jf={...$u},MN=(async()=>{try{let{loadConfig:i}=await oY().then(()=>ky),t=await i({name:"clarity",alias:"logging",defaultConfig:$u,cwd:mf.cwd()});if(t)Object.assign(Jf,t)}catch{}return Jf})();function fi(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nB(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let i=ut.type;if(i==="renderer"||i==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class cu{async format(i){let t=await nB(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:En.pid,hostname:t(),environment:En.env.NODE_ENV||"development",platform:En.platform,version:En.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:En.env.NODE_ENV||En.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},M=ci,HN=ci.red,rB=ci.green,qN=ci.yellow,fB=ci.blue,LN=ci.magenta,xN=ci.cyan,My=ci.white,gN=ci.gray,$B=ci.bgRed,cB=ci.bgYellow,kN=ci.bgGray,Hy=ci.bold,VN=ci.dim,sN=ci.italic,dN=ci.underline,DN=ci.strikethrough,QN=ci.reset,e$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lB={debug:"\uD83D\uDD0D",info:fB("ℹ"),success:rB("✓"),warning:cB(My(Hy(" WARN "))),error:$B(My(Hy(" ERROR ")))};class af{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Jf},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new cu,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),$=this.generateKey();this.currentKeyId=f,this.keys.set(f,$),this.encryptionKeys.set(f,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...e$,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...e$};return{...e$,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Jf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,$=0,c=3,l=1000;while($<c)try{try{try{await sE(this.config.logDirectory,Ny.F_OK|Ny.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await dE(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:ct.from(i);try{if(!ff(this.currentLogFile))await W$(this.currentLogFile,"",{mode:420});if(f=Ry(this.currentLogFile,"a",420),VE(f,w,{flag:"a"}),my(f),f!==void 0)N$(f),f=void 0;if((await An(this.currentLogFile)).size===0){if(await W$(this.currentLogFile,w,{flag:"w",mode:420}),(await An(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let u=y;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if($<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${c}:`,h);let A=l*2**$;await new Promise((T)=>setTimeout(T,A)),$++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(f!==void 0)try{N$(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if($===c-1){let u=w,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),w}$++;let y=l*2**($-1);await new Promise((u)=>setTimeout(u,y))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Tn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Tn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Tn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,w])=>w.createdAt.getTime()-l.createdAt.getTime()),$=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,$);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return R$(16).toString("hex")}generateKey(){return R$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=R$(16),r=xE("aes-256-gcm",t,n),f=ct.isBuffer(i)?i:ct.from(i,"utf8"),$=r.update(f),c=r.final(),l=$.length+c.length,w=r.getAuthTag(),y=ct.allocUnsafe(16+l+16);return n.copy(y,0),$.copy(y,16),c.copy(y,16+$.length),w.copy(y,16+l),{encrypted:y,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Xy(),f=[];r.on("data",($)=>f.push($)),r.on("end",()=>t(ct.from(ct.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await An(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await $f(this.config.logDirectory),$=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let u=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),c=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await An(n).catch(()=>null))try{if(await Wy(n,l),t.compress)try{let w=`${l}.gz`;await this.compressLogFile(l,w),await cf(l)}catch(w){console.error("Error compressing rotated file:",w)}if($.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await W$(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,"-"),$=n.replace(/\.log$/,`-${f}.log`);if(await An(n).catch(()=>null))await Wy(n,$)}if(this.currentLogFile=r,t.maxFiles){let $=(await $f(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of $.slice(t.maxFiles))await cf(Tn(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=jy(i),r=kE(t),f=Xy();await bE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ff(this.currentLogFile))try{let i=Ry(this.currentLogFile,"r+");my(i),N$(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 $f(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await cf(Tn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof z.env.NO_COLOR<"u",t=z.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof z.stderr<"u"&&z.stderr.isTTY||typeof z.stdout<"u"&&z.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:$,showTimestamp:c=!0}=i,l=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(c)T.push(t);if($==="warning")T.push("WARN");else if($==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=z.stdout.columns||120,y="";if($==="warning"||$==="error")y=`${n} ${f}`;else if($==="info"||$==="success")y=`${n} ${r} ${f}`;else y=`${n} ${r} ${M.cyan(f)}`;if(!c)return y.trim();let u=l(y).trim().length,h=l(t).length,A=Math.max(1,w-2-u-h);return`${y.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,($,c)=>{let l=Number.parseInt(c,10);return l<t[0].length?String(t[0][l]):$});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,($,c)=>{if(c==="%")return"%";if(r>=t.length)return $;let l=t[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return $}});if(r<t.length)f+=` ${t.slice(r).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let $=M.underline(M.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,w="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${l}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),t=t.replace(/`([^`]+)`/g,(n,r)=>M.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>M.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>M.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>M.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>M.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=z.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=z.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(DE(t)||t.startsWith("./")||t.startsWith("../"))t=QE(t);else return null;return ff(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),$=this.formatFileTimestamp(r),c,l;if(t instanceof Error)c=t.message,l=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":lB[i],A=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:M.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:M.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:h,tag:A,message:w,level:i}),console.error(T),l){let C=l.split(`
|
|
111
|
-
`);for(let E of C)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:M.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!fi()){if(console.error(`${$} ${this.environment}.${i.toUpperCase()}: ${c}`),l)console.error(l)}let u=`${$} ${this.environment}.${i.toUpperCase()}: ${y}
|
|
112
|
-
`;if(l)u+=`${l}
|
|
113
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(i,t=""){let n={update:(l,w)=>{},finish:(l)=>{},interrupt:(l,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,w="info")=>{if(!fi()&&z.stdout.isTTY)z.stdout.write(`
|
|
114
|
-
`);if(this[w==="warning"?"warn":w](l),this.activeProgressBar&&this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:n,message:`${M.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),$=`${i} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${$}`;if(n)y+=` ${JSON.stringify(n)}`;if(y+=`
|
|
115
|
-
`,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":M.green("✓"),tag:u,message:`${$}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new af(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!ff(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return jy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=ct.isBuffer(i)?i:ct.from(i,"base64"),f=r.subarray(0,16),$=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=gE("aes-256-gcm",n,f);l.setAuthTag($);let w=l.update(c),y=l.final(),u=w.length+y.length,h=ct.allocUnsafe(u);return w.copy(h,0),y.copy(h,w.length),h.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return fi()}isServerMode(){return!fi()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:$}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let l=f.split(`
|
|
116
|
-
`),w=Math.max(...l.map((A)=>A.length))+2,y=`┌${"─".repeat(w)}┐`,u=`└${"─".repeat(w)}┘`,h=l.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:M.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:M.cyan(y),showTimestamp:!1})),h.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:M.cyan(u),showTimestamp:!1}))}else if(!fi())console.error(`${r} ${this.environment}.INFO: [BOX] ${$}`);let c=`${r} ${this.environment}.INFO: [BOX] ${$}
|
|
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(`${M.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();z.stdin.removeListener("data",n);try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!1)}catch{}z.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!0)}catch{}z.stdin.resume(),z.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,y=0;if(n=i.replace(w,(u,h)=>{if(h==="%")return"%";if(y>=t.length)return u;let A=t[y++];switch(h){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return u}}),y<t.length)n+=` ${t.slice(y).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${y}${w} ${M.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
118
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!z.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,$=M.green("━".repeat(r)),c=M.gray("━".repeat(f)),l=`[${$}${c}]`,w=`${n}%`.padStart(4),y=i.message?` ${i.message}`:"",u=this.options.showIcons===!1?"":t||n===100?M.green("✓"):M.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",A=`\r${u}${h} ${l} ${w}${y}`,T=z.stdout.columns||80,C=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${C}`,z.stdout.write(i.lastRenderedLine),t)z.stdout.write(`
|
|
119
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!z.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await $f(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let $=Tn(this.config.logDirectory,r);if(i.before)try{if((await An($)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${$}:`,c);continue}n.push($)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await cf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var bN=new af("stacks");class gi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class lu extends gi{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map(($)=>`"${$}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class ef extends gi{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class wu extends gi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class yu extends gi{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class Z$ extends gi{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class uu extends gi{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class hu extends gi{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class If extends gi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Au extends gi{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class Tu extends gi{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var Bn={configNotFound(i,t,n){return new lu(i,t,n)},configLoad(i,t,n){return new ef(i,t,n)},configValidation(i,t,n){return new wu(i,t,n)},configMerge(i,t,n,r){return new yu(i,t,n,r)},envVar(i,t,n,r){return new Z$(i,t,n,r)},fileSystem(i,t,n){return new uu(i,t,n)},typeGeneration(i,t,n){return new hu(i,t,n)},schemaValidation(i,t,n){return new If(i,t,n)},browserConfig(i,t,n,r){return new Au(i,t,n,r)},plugin(i,t,n){return new Tu(i,t,n)}};async function wB(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:$}=t,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),l===n||!f(c))break;if(r>0)await new Promise((y)=>setTimeout(y,r))}if($!==void 0)return $;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class v${defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:$=!0,customParsers:c={},verbose:l=!1,trackPerformance:w=!0}=n,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(i),h={...t};return this.processObject(h,[],u,{useCamelCase:f,useBackwardCompatibility:$,customParsers:c,verbose:l,configName:i}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return k$.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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=c.map((u)=>this.formatEnvKey(u,r.useCamelCase)),w=`${n}_${l.join("_")}`,y=r.useBackwardCompatibility?`${n}_${c.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,c,n,r);else{let u=wf.env[w]||(y?wf.env[y]:void 0);if(u!==void 0){if(r.verbose){let h=wf.env[w]?w:y}try{i[f]=this.parseEnvironmentValue(u,typeof $,w,r.customParsers,r.configName)}catch(h){if(h instanceof Z$)throw h;throw Bn.envVar(w,u,typeof $,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[$,c]of Object.entries(r))try{return c(i)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(i,t))try{return $.parse(i)}catch{throw Bn.envVar(n,i,`${t} (via ${$.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(wf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,$=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],$,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,n,r){for(let[f,$]of Object.entries(i)){let c=[...t,f],l=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,c,n,r);else r.push({key:l,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${c.join(".")}`,example:this.generateExample($)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
120
|
-
|
|
121
|
-
`;for(let r of i)n+=`${r.key}
|
|
122
|
-
`,n+=` Type: ${r.type}
|
|
123
|
-
`,n+=` Description: ${r.description}
|
|
124
|
-
`,n+=` Example: ${r.example}
|
|
125
|
-
|
|
126
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
127
|
-
|
|
128
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
129
|
-
`,n+=`|----------|------|-------------|----------|
|
|
130
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
131
|
-
`;return n}}function yB(i,t,n={}){return Eu(i,t,n,new WeakMap)}function Eu(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:$=!1,customMerger:c}=n;if(t===null||t===void 0)return $?i:t;if(c){let l=c(i,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(i))return Yu(i,t,f,r);if(!ai(t)||!ai(i))return t;return TB(i,t,n,r)}function Yu(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return uB(i,t);case"smart":return hB(i,t,r);default:return t}return t}function uB(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>g$(f,r)))n.push(r);return n}function hB(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(ai(t[0])&&ai(i[0]))return AB(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function AB(i,t,n){let r=[...t];for(let f of i){if(!ai(f)){r.push(f);continue}let $=["id","name","key","path","type"],c=!1;for(let l of $)if(l in f){if(r.find((y)=>ai(y)&&(l in y)&&y[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function TB(i,t,n,r){let f=t;if(ai(f)&&r.has(f))return r.get(f);let $={...i};if(ai(f))r.set(f,$);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],w=$[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){$[c]=l;continue}if(ai(l)&&ai(w))$[c]=Eu(w,l,n,r);else if(Array.isArray(l)||Array.isArray(w))$[c]=Yu(w,l,n.arrayMergeMode||"smart",r);else $[c]=l}return $}function Bu(i,t,n="replace"){return yB(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function g$(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!g$(i[n],t[n]))return!1;return!0}if(ai(i)&&ai(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!g$(i[f],t[f]))return!1}return!0}return!1}function ai(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Cu{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:$,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let y=Bf.getWithFileCheck("file",i);if(y){if(l)console.log(`Configuration loaded from cache: ${i}`);return y}}let w=async()=>{if(!yf(i))return null;try{let y=`?t=${Date.now()}`,u=await import(i+y),h=u.default||u,A="default"in u,T=Object.keys(u).length>0;if(!A&&!T)throw new ef(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new ef(i,Error("Configuration must export a valid object"),"unknown");let B={config:Bu(t,h,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Bf.setWithFileCheck("file",B,i,$);return B}catch(y){throw y instanceof Error?Bn.configLoad(i,y):Bn.configLoad(i,Error(String(y)))}};if(c)return k$.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let $ of r)for(let c of this.extensions)f.push(I$(t,`${$}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let $ of r){if(!$)continue;if(n.push($,`.${$}.config`,`${$}.config`,`.${$}`),i)n.push(`${i}.${$}.config`,`.${i}.${$}.config`)}let f=new Set;return n.filter(($)=>{if(!$||f.has($))return!1;return f.add($),!0})}checkFileAccess(i){return wB(async()=>{return yf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!yf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let $ of f)for(let c of this.extensions){let l=I$(i,`${$}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),$=f(i);for(let c of $)if(this.looksLikeConfigFile(c)){let l=I$(i,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!yf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),$=f(i,"utf8");JSON.parse($)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var YB=/^https?:\/\//;class Uu{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:$=!0,customRules:c=[],trackPerformance:l=!0,verbose:w=!1}=n,y=async()=>{let u=[],h=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:$,customRules:c,trackPerformance:l,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return u.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(l)return await k$.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,n){try{if(!EB(t))throw new If(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new If(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,$){if($.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),$.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),$.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,l,r,f,$),$.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if($.validateRequired&&t.required){for(let l of t.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(t.properties){for(let[l,w]of Object.entries(t.properties))if(l in c){let y=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],w,y,r,f,$),$.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!l.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let $ of t)try{let c=this.getValueByPath(i,$.path),l=this.validateWithRule(c,$,$.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:$.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,$,c]=r;t.push({path:f,required:!$,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:YB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var lt=new af("bunfig",{showTags:!0});function BB(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class ju{fileLoader=new Cu;envProcessor=new v$;validator=new Uu;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:$,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let y=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(y)throw w;l={...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 u=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),h=!u&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(y&&(A||u))throw w;if(h&&(!y||!A))l={...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)l={...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 l={...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||$)await this.validateConfiguration(l.config,f,$,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)lt.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);l.metrics=w}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let w=Date.now()-t;throw lt.error(`Configuration loading failed after ${w}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:$,configDir:c,defaultConfig:l,checkEnv:w=!0,arrayStrategy:y="replace",verbose:u=!1}=i,h=$||_f.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,h,c,l,y,u,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,h,c)),this.finalizeResult(T,A,w,r,u);let C=await this.loadHomeConfiguration(r,f,l,y,u,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,u);let E=await this.loadPackageJsonConfiguration(r,f,h,l,y,u,w);if(E)return A.push(Ki(h,"package.json")),this.finalizeResult(E,A,w,r,u);if(A.push(...this.getAllSearchPaths(r,f,h,c)),t)throw Bn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,l,w,u),warnings:[`No configuration file found for "${r}"${BB(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,$,c,l,w){let y=l?uf(i,f,c):f,u=this.getLocalDirectories(n,r);for(let h of u){if(c)lt.info(`Searching for configuration in: ${h}`);let A=this.fileLoader.generateConfigPaths(i,h,t),T=await this.fileLoader.tryLoadFromPaths(A,y,{arrayStrategy:$,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(c)lt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,$){if(!i)return null;let c=$?uf(i,n,f):n,l=[Ki(fn(),".config",i),Ki(fn(),".config"),fn()];for(let w of l){if(f)lt.info(`Checking home directory: ${w}`);let y=this.fileLoader.generateConfigPaths(i,w,t),u=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:r,verbose:f});if(u){if(f)lt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,$,c){let l=c?uf(i,r,$):r;try{let w=Ki(n,"package.json");if(!yE(w))return null;let y={};try{y=JSON.parse(uE(w,"utf8"))}catch(A){if($)lt.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let u=y[i],h=i;if(!u&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(y[T]){u=y[T],h=T;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if($)lt.success(`Configuration loaded from package.json: ${h}`);return{config:Bu(l,u,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if($)lt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:uf(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let $=n(i);if($)f.push(...$)}if(t){let $=await this.validator.validateConfiguration(i,t);if(!$.isValid)f.push(...$.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Bn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Bf.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Bf.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ki(i,"config"),Ki(i,".config"),t?Ki(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ki(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),$=[];for(let c of f)$.push(...this.fileLoader.generateConfigPaths(i,c,t));return $}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ki(fn(),".config",i),Ki(fn(),".config"),fn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var oN=new ju;function uf(i,t,n=!1){let r=new v$,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(c,l=[]){let w={...c};for(let[y,u]of Object.entries(c)){let h=[...l,y],A=[`${f}_${h.join("_").toUpperCase()}`,`${f}_${h.map((E)=>E.toUpperCase()).join("")}`,`${f}_${h.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=_f.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof u==="boolean")w[y]=["true","1","yes"].includes(T.toLowerCase());else if(typeof u==="number"){let E=Number(T);if(!Number.isNaN(E))w[y]=E}else if(Array.isArray(u))try{w[y]=JSON.parse(T)}catch{w[y]=T.split(",").map((E)=>E.trim())}else w[y]=T;else if(u&&typeof u==="object"&&!Array.isArray(u))w[y]=$(u,h)}return w}return $(t)}var iW=Ki(_f.cwd(),"config"),tW=Ki(_f.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",CB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:o$(p$(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:o$(p$(),".stacks","ssl","stacks.localhost.crt"),keyPath:o$(p$(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var mu=CB;import{execSync as Ln}from"node:child_process";import{homedir as RB}from"node:os";import{join as NB}from"node:path";function UB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Ot(i){try{return Pr(i)}catch{return null}}function ic(i){try{return l$(i)||null}catch{return null}}function tc(i,t){try{return t.every((n)=>y$(i,n))}catch{return!1}}function jB(i,t,n=443){return w$(i,t,n)}function mB(i){let t=[];for(let n of i.split(`
|
|
132
|
-
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var Qi="-d -r trustRoot -p ssl -p basic",At="/Library/Keychains/System.keychain",nc="rpx.localhost";function xn(){return NB(RB(),"Library/Keychains/login.keychain-db")}function rc(){return[At,xn()]}function Ru(i,t=nc){let n=Ln(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
133
|
-
`)){let $=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if($)r.push($[1].toUpperCase())}return r}function Of(i){if(process.platform!=="darwin")return;let t=Ot(i.caPath);if(!t)return;let n=i.commonName??nc,r=i.keychains??rc();for(let f of r)for(let $ of Ru(f,n)){if($===t)continue;try{if(f.startsWith("/Library"))Nt(`security delete-certificate -Z ${$} "${f}"`);else Ln(`security delete-certificate -Z ${$} "${f}"`,{stdio:"ignore"});Y("ssl",`Removed stale Root CA ${$} from ${f}`,i.verbose)}catch{}}}function gn(i,t,n){if(process.platform!=="darwin")return kn(i,n);try{let f=Ln(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return Y("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function kn(i,t){let n=Ot(i);if(!n)return!1;for(let r of rc())try{let f=Ln(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let $ of f.split(`
|
|
134
|
-
`))if($.toUpperCase().includes("SHA-256")){if($.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return Y("ssl",`Root CA fingerprint found in ${r}`,t?.verbose),!0}}catch{}return!1}function fc(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Of({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=xn();try{Ln(`security add-trusted-cert ${Qi} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{Nt(`security add-trusted-cert ${Qi} -k ${At} "${i}"`)}catch{return!1}return gn(i,n,{verbose:t.verbose})||kn(i,{verbose:t.verbose})}var Wt=null,wc=Q(Cn(),".stacks","ssl","rpx.localhost.crt");function eu(i,t){return[...new Set(i.filter(Boolean))].map((n)=>({serverName:n,cert:t.cert,key:t.key}))}function Iu(i,t,n){let r=Q(Cn(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:wc,keyPath:Q(r,"rpx.localhost.key"),caCertPath:Q(r,"rpx.localhost.ca.crt"),commonName:t},verbose:n,regenerateUntrustedCerts:!0,proxies:f.map(($)=>({from:"localhost:1",to:$,cleanUrls:!1}))}}var WB="rpx-root-ca.crt",XB="rpx-root-ca.key";function yc(i){return{caCertPath:Q(i,WB),caKeyPath:Q(i,XB)}}function eW(i){return{certPath:Q(i,"rpx.localhost.crt"),keyPath:Q(i,"rpx.localhost.key"),caCertPath:Q(i,"rpx.localhost.ca.crt"),rootCA:yc(i)}}async function SB(i,t){try{let[n,r]=await Promise.all([Z.readFile(i.caCertPath,"utf8"),Z.readFile(i.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return Y("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:n,privateKey:r}}catch(n){return Y("ssl",`No existing Root CA at ${i.caCertPath} (${n.code||n}), will create one`,t),null}}function Nu(i){let t=new Set;t.add(i);let n=i.split(".");if(n.length>=3){let r=n[n.length-1],f=n[n.length-2],$=new Set(["co","com","org","net","ac","gov","edu"]);if(!(n.length===3&&r.length===2&&$.has(f)))t.add(`*.${n.slice(1).join(".")}`)}return Array.from(t)}function _u(i){let n=lc(i).replace(/\*/g,"wildcard"),r=Q(Cn(),".stacks","ssl"),f=r;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:r,{caCertPath:i.https.caCertPath||Q(f,`${n}.ca.crt`),certPath:i.https.certPath||Q(f,`${n}.crt`),keyPath:i.https.keyPath||Q(f,`${n}.key`)};return{caCertPath:Q(f,`${n}.ca.crt`),certPath:Q(f,`${n}.crt`),keyPath:Q(f,`${n}.key`)}}function Wu(i){let t=new Set;if(Gf(i))i.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";Nu(r).forEach((f)=>t.add(f))});else if(Su(i)){let n=i.to||"rpx.localhost";Nu(n).forEach((r)=>t.add(r))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function IW(i){Y("ssl","Loading SSL configuration",i.verbose);let t={...mu,...i};if(i.https=Ac(t),!i.https?.keyPath&&!i.https?.certPath)return Y("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let n=!i.https?.keyPath?"keyPath":"certPath";throw Y("ssl",`Invalid SSL configuration - missing ${n}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{Y("ssl","Reading SSL certificate files",i.verbose);let n=await Z.readFile(i.https?.keyPath,"utf8"),r=await Z.readFile(i.https?.certPath,"utf8");return Y("ssl","SSL configuration loaded successfully",i.verbose),{key:n,cert:r}}catch(n){return Y("ssl",`Failed to read certificates: ${n}`,i.verbose),null}}catch(n){throw Y("ssl",`SSL configuration error: ${n}`,i.verbose),n}}async function _W(i,t){if(ki.platform==="darwin")return FB(i,t);if(ki.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,($)=>{r(!$)})})})}catch{return!1}return!1}async function FB(i,t){if(ki.platform!=="darwin")return!1;let n=t?.serverName??"rpx.localhost",r=t?.verbose??!1;try{if(gn(i,n,{verbose:r}))return Y("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return Y("ssl","Trusting Root CA for browsers (login + system keychains)",r),fc(i,{serverName:n,verbose:r})}catch{return!1}}async function Ku(i){if(Wt&&!i.forceRegenerate){Y("ssl","Using cached SSL configuration",i.verbose);return}uc();let t=Gf(i)?i.proxies.map((u)=>u.to):[i.to];Y("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let n=Ac(i,i.verbose),r=n.basePath||Q(Cn(),".stacks","ssl");await Z.mkdir(r,{recursive:!0});let f=yc(r),$=await SB(f,i.verbose),c=!1;if(!$){if(i.verbose)e.info("Generating Root CA certificate (one-time)...");$=await $$(n);try{await Promise.all([Z.writeFile(f.caCertPath,$.certificate),Z.writeFile(f.caKeyPath,$.privateKey,{mode:384})]),c=!0,Y("ssl",`Persisted Root CA at ${f.caCertPath}`,i.verbose)}catch(u){throw Y("ssl",`Error saving Root CA files: ${u}`,i.verbose),Error(`Failed to save Root CA files: ${u}`)}}else Y("ssl",`Reusing existing Root CA from ${f.caCertPath}`,i.verbose);if(i.verbose)e.info(`Generating host certificate for: ${t.join(", ")}`);let l=await c$({...n,rootCA:{certificate:$.certificate,privateKey:$.privateKey}});try{await Promise.all([Z.writeFile(n.certPath,l.certificate),Z.writeFile(n.keyPath,l.privateKey),Z.writeFile(n.caCertPath,$.certificate)]),Y("ssl","Certificate files saved successfully",i.verbose)}catch(u){throw Y("ssl",`Error saving certificate files: ${u}`,i.verbose),Error(`Failed to save certificate files: ${u}`)}if(c?!1:await zu(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(Y("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)e.success("Root CA is already trusted in system trust store");if(Wt={key:l.privateKey,cert:l.certificate,ca:$.certificate},i.verbose)e.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)e.info("Adding certificate to system trust store (may require sudo permission)...");let y=!1;if(ki.platform==="darwin")try{Of({caPath:f.caCertPath,verbose:i.verbose});let u=xn();try{$c(`security add-trusted-cert ${Qi} -k "${u}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Nt(`security add-trusted-cert ${Qi} -k ${At} "${f.caCertPath}"`),i.verbose)e.success("Successfully added Root CA to system trust store");y=!0;let h=Q(r,"trust-rpx-cert.sh"),A=`#!/bin/bash
|
|
135
|
-
echo "Trusting RPX Root CA"
|
|
136
|
-
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
137
|
-
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
138
|
-
if [ -n "$SUDO_PASSWORD" ]
|
|
139
|
-
then
|
|
140
|
-
printf '%s
|
|
141
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Qi} -k ${At} "${f.caCertPath}"
|
|
142
|
-
else
|
|
143
|
-
sudo security add-trusted-cert ${Qi} -k ${At} "${f.caCertPath}"
|
|
144
|
-
fi
|
|
145
|
-
echo "Root CA trusted! Please restart your browser."
|
|
146
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
147
|
-
`;await Z.writeFile(h,A,{mode:493})}catch(u){if(i.verbose)e.warn(`Could not add Root CA to trust store automatically: ${u}`);let h=Q(r,"trust-rpx-cert.sh"),A=`#!/bin/bash
|
|
148
|
-
echo "Trusting RPX Root CA"
|
|
149
|
-
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
150
|
-
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
151
|
-
if [ -n "$SUDO_PASSWORD" ]
|
|
152
|
-
then
|
|
153
|
-
printf '%s
|
|
154
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Qi} -k ${At} "${f.caCertPath}"
|
|
155
|
-
else
|
|
156
|
-
sudo security add-trusted-cert ${Qi} -k ${At} "${f.caCertPath}"
|
|
157
|
-
fi
|
|
158
|
-
echo "Root CA trusted! Please restart your browser."
|
|
159
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
160
|
-
`;if(await Z.writeFile(h,A,{mode:493}),i.verbose)e.info(`Created a trust helper script at: ${h}`),e.info(`If you're still having certificate issues, run: sh ${h}`)}else if(ki.platform==="linux")try{let{exec:u}=await import("node:child_process"),h="/usr/local/share/ca-certificates/rpx",A=`
|
|
161
|
-
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
162
|
-
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
163
|
-
update-ca-certificates
|
|
164
|
-
echo "RPX Root CA installed. Please restart your browser."
|
|
165
|
-
`,T=Q(cc.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((C)=>{u(`sudo bash "${T}"`,(E)=>{if(E){if(i.verbose)e.warn(`Could not trust certificates: ${E}`);C(!1)}else{if(i.verbose)e.success("Successfully added certificates to system trust store");C(!0)}})}),await Z.unlink(T).catch(()=>{}),y=!0}catch(u){if(i.verbose)e.warn(`Failed to trust certificates: ${u}`)}else if(ki.platform==="win32")try{let u=`
|
|
166
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
167
|
-
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
168
|
-
$store.Open("ReadWrite")
|
|
169
|
-
$store.Add($cert)
|
|
170
|
-
$store.Close()
|
|
171
|
-
Write-Host "Root CA trusted successfully!"
|
|
172
|
-
`,h=Q(cc.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile(h,u),$c(`powershell -ExecutionPolicy Bypass -File "${h}"`),i.verbose)e.success("Successfully added certificate to Windows trust store");y=!0}catch(u){if(i.verbose)e.warn(`Could not trust certificate: ${u}`)}else try{await u$(l,$.certificate,n),y=!0}catch(u){if(i.verbose)e.warn(`Could not add certificate to trust store: ${u}`)}if(Wt={key:l.privateKey,cert:l.certificate,ca:$.certificate},i.verbose)e.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!y&&i.verbose)e.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),e.warn("This will bypass the warning and you should only need to do it once")}function uc(){Wt=null}async function hc(i){if(!i)return null;if(Wt)return Wt;let t=Ac(i);try{let[n,r,f]=await Promise.all([Z.access(t.keyPath).then(()=>!0).catch(()=>!1),Z.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?Z.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return Y("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let $="regenerateUntrustedCerts"in i,c=i.regenerateUntrustedCerts,l=$?c!==!1:!0;Y("ssl",`Trust check: hasFlag=${$}, flagValue=${c}, shouldCheckTrust=${l}`,i.verbose);let w=t.basePath||Q(Cn(),".stacks","ssl"),y=yc(w);if(!(l?await zu(y.caCertPath,i):!0))return Y("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[h,A,T]=await Promise.all([Z.readFile(t.keyPath,"utf8"),Z.readFile(t.certPath,"utf8"),f&&t.caCertPath?Z.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(T&&!T.includes("-----BEGIN CERTIFICATE-----"))return Y("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(Gf(i))try{let{X509Certificate:C}=await import("node:crypto"),B=new C(A).subjectAltName||"",m=i.proxies.map((S)=>S.to).filter((S)=>!B.includes(`DNS:${S}`));if(m.length>0)return Y("ssl",`Certificate missing SANs for: ${m.join(", ")}, will regenerate`,i.verbose),null}catch(C){Y("ssl",`Could not verify cert SANs: ${C}`,i.verbose)}return Y("ssl","Successfully loaded existing certificates",i.verbose),Wt={key:h,cert:A,ca:T},Wt}catch(n){return Y("ssl",`Error checking existing certificates: ${n}`,i.verbose),null}}function Ac(i,t){let n=lc(i);Y("ssl",`Primary domain: ${n}`,t);let r=_u(i),f=Q(Cn(),".stacks","ssl");if(typeof i.https==="object"){let $=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,c={domain:n,hostCertCN:n,basePath:$,caCertPath:i.https.caCertPath||r.caCertPath,certPath:i.https.certPath||r.certPath,keyPath:i.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||n,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(Wu(i)).map((l)=>({type:2,value:l}))};if(Xu(i.https.rootCA))c.rootCA=i.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Wu(i)).map(($)=>({type:2,value:$}))}}async function KW(i,t){let n=_u({to:i,verbose:t}),r=[n.caCertPath,n.certPath,n.keyPath];Y("certificates","Attempting to clean up relating certificates",t),await Promise.all(r.map((f)=>Fu(f,t)))}async function zu(i,t){try{if(Y("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),ki.platform==="darwin"){if(t?.serverName)return gn(i,t.serverName,{verbose:t?.verbose});return kn(i,{verbose:t?.verbose})}else if(ki.platform==="win32")try{let n=ic(i)||"";if(!n)return Y("ssl","Could not extract certificate subject",t?.verbose),!1;let r=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if($c(r).toString().includes(n))return Y("ssl","Certificate found in trusted root store",t?.verbose),!0;return Y("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(n){return Y("ssl",`Error checking certificate trust on Windows: ${n}`,t?.verbose),!1}else if(ki.platform==="linux")try{let n=Ot(i);if(!n)return Y("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let r=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of r){let $;try{$=await Z.readdir(f)}catch{continue}for(let c of $){let l=Ot(Ju.join(f,c));if(l&&l===n)return Y("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return Y("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(n){return Y("ssl",`Error checking certificate trust on Linux: ${n}`,t?.verbose),!1}return Y("ssl",`Platform ${ki.platform} not supported for certificate trust check`,t?.verbose),!1}catch(n){return Y("ssl",`Error checking if certificate is trusted: ${n}`,t?.verbose),!1}}function JB(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 eB(i){return(Array.isArray(i)?i:[i]).map((n)=>{let r=typeof n==="string"?{url:n}:n;return{url:r.url,weight:r.weight&&r.weight>0?r.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function au(i){return(Array.isArray(i)?i:[i]).map((n)=>typeof n==="string"?n:n.url)}function Ou(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 Gu(i,t){return{upstreams:eB(i),strategy:t?.strategy??"round-robin",healthCheck:JB(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function IB(i){let t=i.upstreams.filter((n)=>n.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function _B(i,t){let n=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[n]}function KB(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let n=t.reduce((f,$)=>f+$.weight,0),r=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[r])r=f;return i.wrrCurrentWeights[r]-=n,t[r]}function zB(i){let t=i[0];for(let n=1;n<i.length;n++)if(i[n].activeConnections<t.activeConnections)t=i[n];return t}function Mu(i){let t=IB(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return KB(i,t);case"least-connections":return zB(t);case"round-robin":default:return _B(i,t)}}function Mf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function Vn(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function aB(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let n=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(n)?n:80}}async function OB(i,t){let{hostname:n,port:r}=aB(t.url),f=new AbortController,$=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${n}:${r}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Mf(i,t)}catch{Vn(i,t)}finally{clearTimeout($)}}function Hu(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let n of i.upstreams)OB(i,n)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function Tc(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as Lu,timingSafeEqual as qu}from"node:crypto";import{readFileSync as GB}from"node:fs";var MB="/.well-known/acme-challenge/";function sn(i,t){let n=Buffer.from(i,"utf8"),r=Buffer.from(t,"utf8");if(n.length!==r.length)return qu(n,n),!1;return qu(n,r)}function HB(i,t){let n=(A)=>Lu("md5").update(A).digest(),r=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),$=n(Buffer.concat([r,f,r])),c=[r,Buffer.from("$apr1$","utf8"),f];for(let A=r.length;A>0;A-=16)c.push($.subarray(0,Math.min(A,16)));for(let A=r.length;A>0;A>>=1)c.push(A&1?Buffer.from([0]):r.subarray(0,1));let l=n(Buffer.concat(c));for(let A=0;A<1000;A++){let T=[];if(T.push(A&1?r:l.subarray(0,16)),A%3)T.push(f);if(A%7)T.push(r);T.push(A&1?l.subarray(0,16):r),l=n(Buffer.concat(T))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",y=(A,T)=>{let C="",E=A;for(let B=0;B<T;B++)C+=w[E&63],E>>=6;return C},u=l,h="";return h+=y(u[0]<<16|u[6]<<8|u[12],4),h+=y(u[1]<<16|u[7]<<8|u[13],4),h+=y(u[2]<<16|u[8]<<8|u[14],4),h+=y(u[3]<<16|u[9]<<8|u[15],4),h+=y(u[4]<<16|u[10]<<8|u[5],4),h+=y(u[11],2),`$apr1$${t}$${h}`}function qB(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let r=t.split("$")[2]??"";return sn(HB(i,r),t)}if(t.startsWith("{SHA}")){let n=Lu("sha1").update(i,"utf8").digest("base64");return sn(`{SHA}${n}`,t)}return sn(i,t)}function LB(i){let t=new Map;for(let n of i.split(`
|
|
173
|
-
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let f=r.indexOf(":");if(f<=0)continue;t.set(r.slice(0,f),r.slice(f+1))}return t}function xu(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",n=[];if(i.username)n.push({username:i.username,password:i.password??""});for(let $ of i.users??[])if($?.username)n.push({username:$.username,password:$.password??""});let r;if(i.htpasswdFile)try{r=LB(GB(i.htpasswdFile,"utf8"))}catch{r=void 0}if(n.length===0&&(!r||r.size===0))return;return{realm:t,verify:($,c)=>{let l=!1;for(let w of n)if(sn($,w.username)&&sn(c,w.password))l=!0;if(r){let w=r.get($);if(w&&qB(c,w))l=!0}return l}}}function gu(i,t,n){if(t.startsWith(MB))return;let r=i.headers.get("authorization")??"",f=r.indexOf(" "),$=f===-1?r:r.slice(0,f),c=f===-1?"":r.slice(f+1).trim();if($.toLowerCase()==="basic"&&c){let w="";try{w=Buffer.from(c,"base64").toString("utf8")}catch{w=""}let y=w.indexOf(":");if(y>=0&&n.verify(w.slice(0,y),w.slice(y+1)))return}let l=n.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${l}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:xB}=Bun,dn=Symbol("rpx.pool.fallback"),Hf=Symbol("rpx.pool.stale");var gB=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function kB(i){return gB.has(i.toUpperCase())}var Yc=Symbol("rpx.pool.timeout"),Gt=Symbol("rpx.pool.busy");function VB(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function sB(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function dB(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function DB(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Vu=1048576;function QB(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var Ec=30000,bB=16384,su=262144,PB=2097152,ZB=524288,vB=8192,pB=4096,oB=new TextEncoder,du=new TextDecoder,iC=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class Du{socket=null;buf=new Uint8Array(bB);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,n=t.write(i);while(n<i.length){if(this.closed)throw Hf;await new Promise((r)=>{this.drainWaiter=r}),n+=t.write(i.subarray(n))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>PB)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=ZB)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let n=new Uint8Array(Math.max(this.buf.length*2,t));n.set(this.buf.subarray(0,this.len)),this.buf=n}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Qu{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=VB();maxWaiters;checkoutIdleMs=dB();inUse=new Set;constructor(i,t,n,r=""){this.host=i;this.port=t;this.maxTotal=n;this.key=r;this.maxWaiters=sB(n)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new Du;return xB({hostname:this.host,port:this.port,socket:{data:(t,n)=>i.push(n),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let n=t;n.setNoDelay?.(!0);let r=DB();if(r>0)n.timeout?.(r);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Gt;let i=await this.waitForSlot();if(i===Gt)throw Gt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,n=($)=>{if(t)return;t=!0,clearTimeout(f),i($)},r=($)=>n($),f=setTimeout(()=>{let $=this.waiters.indexOf(r);if($!==-1)this.waiters.splice($,1);n(Gt)},this.queueWaitMs);f.unref?.(),this.waiters.push(r)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min(Ec,this.checkoutIdleMs):Ec;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-Ec;if(this.idle.length){let n=[];for(let r of this.idle)if(r.closed||r.idleSince<=t)r.destroy(),this.open--;else n.push(r);this.idle=n}if(this.checkoutIdleMs>0&&this.inUse.size){let n=i-this.checkoutIdleMs;for(let r of this.inUse)if(!r.closed&&r.lastActivityAt>0&&r.lastActivityAt<=n)r.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&qf.get(this.key)===this)qf.delete(this.key)}}}var qf=new Map;function tC(i,t){let n=qf.get(i);if(!n){let r=i.lastIndexOf(":"),f=r===-1?i:i.slice(0,r),$=r===-1?80:Number(i.slice(r+1));n=new Qu(f,$,t,i),qf.set(i,n)}return n}function ku(i,t,n){for(let r=n+3;r<t;r++)if(i[r]===10&&i[r-1]===13&&i[r-2]===10&&i[r-3]===13)return r-3;return-1}function nC(i,t,n){let r=du.decode(i.subarray(t,n)),f=r.indexOf(`\r
|
|
174
|
-
`),$=f===-1?r:r.slice(0,f),c=$.indexOf(" "),l=Number.parseInt($.slice(c+1,c+5),10),w=$.startsWith("HTTP/1.0"),y=[],u=-1,h=!1,A=w,T=!1,C=!1,E=f===-1?r.length:f+2;while(E<r.length){let B=r.indexOf(`\r
|
|
175
|
-
`,E);if(B===-1)B=r.length;let U=r.slice(E,B);if(E=B+2,U==="")continue;let m=U.indexOf(":");if(m===-1)continue;let S=U.slice(0,m),F=U.slice(m+1).trim(),W=S.charCodeAt(0)|32;if(W===99||W===116||W===107){let J=S.toLowerCase();if(J==="content-length"){let H=/^\d+$/.test(F)?Number(F):Number.NaN;if(!Number.isSafeInteger(H)||u>=0&&u!==H)C=!0;else u=H;continue}if(J==="transfer-encoding"){if(F.toLowerCase().includes("chunked"))h=!0;continue}if(J==="connection"){let H=F.toLowerCase();if(H.includes("close"))A=!0;if(H.includes("keep-alive"))T=!0;continue}if(J==="keep-alive")continue}y.push([S,F])}if(w&&T)A=!1;if(h&&u>=0)u=-1;return{status:l,headerEnd:n,headers:y,contentLength:u,chunked:h,closeConn:A,malformed:C}}function rC(i,t){return t||i===204||i===304}async function bu(i){let{hostPort:t,method:n,path:r,reqHeaders:f,forwardedHost:$,originOverride:c,body:l}=i,w=n==="HEAD";if(f.get("expect")||f.get("upgrade"))throw dn;let y=null;if(l){let T=f.get("content-length"),C=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(C)||C>Vu)throw dn;if(y=await uC(l),y===null)throw dn}let u=yC(n,r,f,t,$,c,y),h=u;if(y&&y.length)h=new Uint8Array(u.length+y.length),h.set(u),h.set(y,u.length);let A=tC(t,i.maxPerHost??QB());for(let T=0;;T++){if(T>0)await new Promise((E)=>{setTimeout(E,T)});let C;try{C=A.acquireIdleSync()??await A.acquireOrDial()}catch(E){if(E!==Gt&&T<4)continue;throw E}try{let E=C.socket.write(h);if(E<h.length)await C.writeAll(h.subarray(E));return await $C(A,C,w)}catch(E){let B=E===Hf&&T<4&&(C.fresh||kB(n));if(A.destroy(C),B)continue;if(E===Hf)throw Error("upstream closed connection");throw E}}}async function fC(i){let t=ku(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw Yc;if(i.len===i.pos)throw Hf;throw Error("upstream closed mid-header")}if(i.len-i.pos>su)throw Error("upstream header block too large");await i.waitForData(i.len),t=ku(i.buf,i.len,i.pos)}return t}async function $C(i,t,n){let r;for(;;){let $=await fC(t);if(r=nC(t.buf,t.pos,$),t.pos=$+4,r.status>=100&&r.status<200)continue;break}if(r.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=r.headers;if(rC(r.status,n))return Pu(i,t,r.closeConn),new Response(null,{status:r.status,headers:f});if(r.chunked)return new Response(wC(i,t,r.closeConn),{status:r.status,headers:f});if(r.contentLength>=0){if(t.len-t.pos>=r.contentLength){let c=t.pos+r.contentLength,l=t.len>c,w=null;if(r.contentLength>=vB)w=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(pB);else if(r.contentLength>0)w=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,r.closeConn||l)i.destroy(t);else i.release(t);return new Response(w,{status:r.status,headers:f})}return new Response(cC(i,t,r.contentLength,r.closeConn),{status:r.status,headers:f})}return new Response(lC(t),{status:r.status,headers:f})}function Pu(i,t,n){if(n||t.pos!==t.len)i.destroy(t);else i.release(t)}function cC(i,t,n,r){let f=t.len-t.pos,$=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=n-f,t.queuedBytes=0,t.streamingBody=!0;let c=(l)=>{if(t.bodyQueue=null,r||t.len>0)i.destroy(t);else i.release(t);l.close()};return new ReadableStream({start(l){if($)l.enqueue($);if(t.bodyRemaining===0&&t.bodyQueue.length===0)c(l)},async pull(l){for(;;){let w=t.bodyQueue;if(w&&w.length>0){let y=w.shift();if(t.queuedBytes-=y.length,t.resumeIfDrained(),l.enqueue(y),t.bodyRemaining===0&&w.length===0)c(l);return}if(t.bodyRemaining===0){if(t.bodyQueue)c(l);return}if(t.closed){t.bodyQueue=null,i.destroy(t),l.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function lC(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 wC(i,t,n){t.streamingBody=!0;let r=0,f=!1;async function $(){for(;;){for(let c=t.pos;c+1<t.len;c++)if(t.buf[c]===13&&t.buf[c+1]===10){let l=du.decode(t.buf.subarray(t.pos,c));return t.pos=c+2,l}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>su)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(c){for(;;){if(r>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 u=Math.min(r,t.len-t.pos);if(c.enqueue(t.buf.slice(t.pos,t.pos+u)),t.pos+=u,r-=u,t.resumeIfDrained(),r===0)f=!0;return}if(f)await $(),f=!1;let l=await $(),w=l.indexOf(";"),y=Number.parseInt(w===-1?l:l.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 $()==="")break;Pu(i,t,n),c.close();return}r=y}},cancel(){i.destroy(t)}})}function yC(i,t,n,r,f,$,c){let l=`${i} ${t} HTTP/1.1\r
|
|
176
|
-
host: ${r}\r
|
|
177
|
-
x-forwarded-for: 127.0.0.1\r
|
|
178
|
-
x-forwarded-proto: https\r
|
|
179
|
-
x-forwarded-host: ${f}\r
|
|
180
|
-
`;if($!==void 0)l+=`origin: ${$}\r
|
|
181
|
-
`;let w=!1;for(let[y,u]of n){let h=y.toLowerCase();if(iC.has(h))continue;if($!==void 0&&h==="origin")continue;if(h==="content-length")w=!0;l+=`${y}: ${u}\r
|
|
182
|
-
`}if(l+=`connection: keep-alive\r
|
|
183
|
-
`,c&&!w)l+=`content-length: ${c.length}\r
|
|
184
|
-
`;return l+=`\r
|
|
185
|
-
`,oB.encode(l)}async function uC(i){let t=i.getReader(),n=[],r=0;for(;;){let{done:c,value:l}=await t.read();if(c)break;if(l){if(r+=l.length,r>Vu)return t.cancel().catch(()=>{}),null;n.push(l)}}if(n.length===1)return n[0];let f=new Uint8Array(r),$=0;for(let c of n)f.set(c,$),$+=c.length;return f}function xW(i){let t=typeof i==="string"?{to:i}:i,n=(t.to??"").trim();if(n&&!/^[a-z][\w+.-]*:\/\//i.test(n))n=`https://${n}`;return n=n.replace(/\/+$/,""),{to:n,status:t.status??301,preservePath:t.preservePath??!0}}function Zu(i,t,n){if(!i.preservePath)return i.to||"/";let r=`${t}${n}`;return r==="/"?`${i.to}/`:`${i.to}${r}`}import*as Oi from"node:path";function vu(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 hC={".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 AC(i){let t=Oi.extname(i).toLowerCase();return hC[t]??"application/octet-stream"}function TC(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let n=Oi.posix.normalize(`/${t}`);if(n.split("/").includes(".."))return null;return n.replace(/^\/+/,"")}function EC(i,t){let n=TC(i);if(n===null)return null;let r=Oi.posix.extname(n);if(t.cleanUrls&&r===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Oi.join(t.dir,n),redirectTo:f||"/"}}if(n===""||i.endsWith("/"))return{filePath:Oi.join(t.dir,n,"index.html")};if(r!=="")return{filePath:Oi.join(t.dir,n)};if(t.pathRewriteStyle==="flat")return{filePath:Oi.join(t.dir,`${n}.html`)};return{filePath:Oi.join(t.dir,n,"index.html")}}async function pu(i,t){let n=EC(i,t);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(n.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":AC(n.filePath),"Cache-Control":r}});if(t.spa){let $=Oi.join(t.dir,"index.html"),c=Bun.file($);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 YC(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var BC=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function CC(i){let t=i.headers.get("host")||"",n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function nh(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let n=i.slice(t.length);return n===""?"/":n}return i}function ou(i){if(i.upstreamPool)return Mu(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function ih(i,t,n,r){let f=n?.url??t.sourceHost??"",c=t.stripBasePathPrefix??!1?nh(i,t.basePath):i,l=th(c,t.pathRewrites);if(l)f=l.targetHost,c=l.targetPath,Y("request",`Path rewrite: ${i} → ${f}${c}`,r);return{targetHost:f,targetPath:c}}function UC(i){let t=i.indexOf("://"),n=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(n===-1)return{pathname:"/",search:""};let r=i.indexOf("?",n);if(r===-1)return{pathname:i.slice(n),search:""};return{pathname:i.slice(n,r),search:i.slice(r)}}function Bc(i,t,n){let r=async(f,$)=>{let{pathname:c,search:l}=UC(f.url),w=CC(f),y=i(w,c);if(!y&&n){let B=await n(w,c,f);if(B instanceof Response)return B;if(B&&B.retry)y=i(w,c)}if(!y)return Y("request",`No route found for host: ${w}`,t),new Response(`No proxy configured for ${w}`,{status:404});if(y.auth){let B=gu(f,c,y.auth);if(B)return Y("request",`401 challenge for ${w}${c}`,t),B}if(y.redirect){let B=Zu(y.redirect,c,l);return Y("request",`${y.redirect.status} redirect ${w}${c} → ${B}`,t),new Response(null,{status:y.redirect.status,headers:{location:B}})}if(y.static){let U=y.stripBasePathPrefix??!0?nh(c,y.basePath):c;return pu(U,y.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let B=ou(y);if(!$||!B)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:U,targetPath:m}=ih(c,y,B,t),S=`ws://${U}${m}${l}`,F={};for(let[H,p]of f.headers)if(!BC.has(H.toLowerCase())&&H.toLowerCase()!=="host")F[H]=p;F.host=U,F["x-forwarded-for"]="127.0.0.1",F["x-forwarded-proto"]="https",F["x-forwarded-host"]=w;let W={targetUrl:S,forwardHeaders:F};if($.upgrade(f,{data:W})){Y("ws",`upgraded ${w}${m} → ${S}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let u=ou(y);if(!u)return new Response(`No upstream configured for ${w}`,{status:502});if(y.cleanUrls&&c.endsWith(".html")){let B=c.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:B}})}let{targetHost:h,targetPath:A}=ih(c,y,u,t),T=y.changeOrigin?`http://${h}`:void 0,C=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=y.upstreamPool;if(E)u.activeConnections++;try{let B=await bu({hostPort:h,method:f.method,path:`${A}${l}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body});if(E)Mf(E,u);return B}catch(B){if(B===Yc){if(Y("request",`Upstream timeout for ${w}`,t),E)Vn(E,u);return new Response("Gateway Timeout",{status:504})}if(B===Gt)return Y("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(B===dn||!C)try{let U=new Headers(f.headers);if(U.set("host",h),U.set("x-forwarded-for","127.0.0.1"),U.set("x-forwarded-proto","https"),U.set("x-forwarded-host",w),T!==void 0)U.set("origin",T);let m=await fetch(`http://${h}${A}${l}`,{method:f.method,headers:U,body:f.body,redirect:"manual"});if(E)Mf(E,u);return m}catch(U){if(Y("request",`Proxy error for ${w}: ${U}`,t),E)Vn(E,u);return new Response(`Proxy Error: ${U}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)Vn(E,u);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)u.activeConnections--}};return async(f,$)=>{try{return await r(f,$)}catch(c){return Y("request",`Unhandled proxy handler error: ${c}`,t),new Response("Bad Gateway",{status:502})}}}function Cc(i){let t=new WeakMap,n=YC();return{open(r){let{targetUrl:f,forwardHeaders:$}=r.data,c;try{c=new WebSocket(f,{headers:$})}catch(w){Y("ws",`failed to open upstream ${f}: ${w}`,i),r.close(1011,"upstream connect failed");return}c.binaryType="arraybuffer";let l={upstream:c,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(r,l),c.addEventListener("open",()=>{l.upstreamOpen=!0;for(let w of l.pending)c.send(w);l.pending=[],l.pendingBytes=0}),c.addEventListener("message",(w)=>{r.send(w.data)}),c.addEventListener("close",(w)=>{try{r.close(w.code||1000,w.reason||"")}catch{}}),c.addEventListener("error",()=>{Y("ws",`upstream error for ${f}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,f){let $=t.get(r);if(!$)return;let c=typeof f==="string"?f:new Uint8Array(f);if($.upstreamOpen){$.upstream.send(c);return}let l=typeof c==="string"?Buffer.byteLength(c):c.byteLength;if($.pendingBytes+l>n){Y("ws",`pending buffer would exceed ${n}B before upstream open; closing socket`,i);try{r.close(1009,"buffer limit")}catch{}try{$.upstream.close(1011,"client buffer overflow")}catch{}t.delete(r);return}$.pending.push(c),$.pendingBytes+=l},close(r,f,$){let c=t.get(r);if(!c)return;t.delete(r);try{c.upstream.close(f||1000,$||"")}catch{}}}}import*as fh from"node:fs";import*as $h from"node:path";var rh="/.well-known/acme-challenge/";function ch(i,t){if(!i||!t.startsWith(rh))return null;let n=t.slice(rh.length);if(!n||!/^[A-Za-z0-9_-]+$/.test(n))return null;try{return fh.readFileSync($h.join(i,n),"utf8")}catch{return null}}function Lf(i){return i.startsWith("*.")}function Uc(i,t){if(!Lf(t))return!1;let n=t.slice(1);return i.length>n.length&&i.endsWith(n)}function lh(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[$,c]of i){if(!Lf($))continue;if(Uc(t,$)){let l=$.length-1;if(l>f)f=l,r=c}}return r}function Mt(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function jC(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function jc(i){let t=new Map;for(let r of i){let f=Mt(r.path),$=t.get(r.host);if(!$)$=new Map,t.set(r.host,$);$.set(f,r.route)}let n=new Map;for(let[r,f]of t){let $=[];for(let[c,l]of f)$.push({path:c,route:l});$.sort((c,l)=>l.path.length-c.path.length),n.set(r,$)}return n}function mc(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[$,c]of i){if(!Lf($))continue;if(Uc(t,$)){let l=$.length-1;if(l>f)f=l,r=c}}return r}function Rc(i,t,n){let r=mc(i,t);if(!r)return;for(let f of r)if(jC(n,f.path))return f.route;return}import*as Dn from"node:fs/promises";import*as Nc from"node:path";function mC(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 RC(i,t,n,r){try{let[f,$]=await Promise.all([Dn.readFile(t,"utf8"),Dn.readFile(n,"utf8")]);return{serverName:i,cert:f,key:$}}catch(f){return Y("sni",`skipping ${i}: ${f.message}`,r),null}}async function Wc(i,t){let n=new Map;if(i.certsDir){let f=[];try{f=await Dn.readdir(i.certsDir)}catch($){Y("sni",`certsDir read failed (${i.certsDir}): ${$.message}`,t)}for(let $ of f){let c=mC($);if(!c)continue;let l=$.slice(0,-4);n.set(c,{certPath:Nc.join(i.certsDir,$),keyPath:Nc.join(i.certsDir,`${l}.key`)})}}if(i.domains)for(let[f,$]of Object.entries(i.domains))n.set(f,$);let r=[];for(let[f,$]of n){let c=await RC(f,$.certPath,$.keyPath,t);if(c)r.push(c)}return r}import*as Xt from"node:fs/promises";import*as Xc from"node:path";var NC=60000,wh=4096;function WC(i,t){if(!t||t.length===0)return!1;return t.some((n)=>{let r=n.startsWith(".")?n.slice(1):n;return i===r||i.endsWith(`.${r}`)})}function yh(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class xf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??kr,this.issuer=i.issuer??d0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??NC;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(!yh(i))return!1;if(WC(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return Y("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!yh(i))return!1;let t=this.inFlight.get(i);if(t)return t;let n=this.negativeCache.get(i);if(n!==void 0&&Date.now()<n)return Y("on-demand",`${i} negatively cached for ${n-Date.now()}ms`,this.verbose),!1;let r=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,r),r}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return Y("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{Y("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let n={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,n),this.negativeCache.delete(i),Y("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),Y("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=wh){let t=Date.now();for(let[n,r]of this.negativeCache)if(r<=t)this.negativeCache.delete(n);if(this.negativeCache.size>=wh){let n=this.negativeCache.keys().next().value;if(n!==void 0)this.negativeCache.delete(n)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:n}=this.pathsFor(i);try{let[r,f]=await Promise.all([Xt.readFile(t,"utf8"),Xt.readFile(n,"utf8")]),$={serverName:i,cert:r,key:f};return this.certs.set(i,$),Y("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:Xc.join(this.certsDir,`${i}.crt`),keyPath:Xc.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await Xt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([Xt.writeFile(r,t,"utf8"),Xt.writeFile(f,n,{encoding:"utf8",mode:384})])}}import{existsSync as XC,readdirSync as SC,readFileSync as FC,statSync as JC}from"node:fs";import{homedir as Ah}from"node:os";import{isAbsolute as eC,join as Un}from"node:path";var Th=["~/Code"],Eh=["localhost","test"],IC=1800000,Sc={dirExists:(i)=>{try{return JC(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return XC(i)}catch{return!1}},readText:(i)=>{try{return FC(i,"utf8")}catch{return null}}};function Fc(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Un(t,i.slice(2));return i}function _C(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function uh(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function KC(i,t){for(let n of t){let r=`.${n}`;if(i.endsWith(r)){let f=i.slice(0,-r.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function zC(i,t){let n=t.readText(Un(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(Un(i,"package.json"));if(r)try{let f=JSON.parse(r);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function aC(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 OC(i,t){let n=zC(i,t);if(n?.command)return aC(n);let r=t.fileExists(Un(i,"buddy")),f=t.readText(Un(i,"package.json")),$=null;if(f)try{$=JSON.parse(f)}catch{$=null}let c={...$?.dependencies??{},...$?.devDependencies??{}};if(r||Object.keys(c).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:r?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if($?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Jc(i,t={}){let n={dirExists:t.dirExists??Sc.dirExists,fileExists:t.fileExists??Sc.fileExists,readText:t.readText??Sc.readText},r=t.detect??OC,f=t.homeDir??Ah(),$=i.tlds??Eh,c=(i.roots??Th).map((A)=>Fc(A,f)),l=i.idleTimeoutMs??IC,w=new Map;for(let A of i.sites??[])w.set(A.to,A);let y=(A)=>A.idleTimeoutMs??l;function u(A){let T=lh(w,A);if(!T)return null;let C=eC(T.dir)?T.dir:Fc(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=r(C,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let U=hh({...T.env??{}},void 0,A);return{host:A,id:uh(A),dir:C,command:T.command,env:U,routes:B,selfRegisters:E,idleTimeoutMs:y(T),source:"config"}}function h(A){let T=KC(A,$);if(!T)return null;for(let C of c){let E=Un(C,T);if(!n.dirExists(E))continue;let B=r(E,n);if(!B)continue;let U=B.selfRegisters??!1;return{host:A,id:uh(A),dir:E,command:B.command,env:hh({...B.env??{}},B.urlEnv,A),routes:U?[]:B.routes??[],selfRegisters:U,idleTimeoutMs:l,source:"discovered"}}return null}return{resolve(A){let T=_C(A);if(!T)return null;return u(T)??h(T)}}}function GC(i){try{return SC(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function yX(i,t={}){let n=t.homeDir??Ah(),r=i.tlds??Eh,f=(i.roots??Th).map((h)=>Fc(h,n)),$=t.readdir??GC,c=Jc(i,t),l=[],w=new Set,y=(h)=>{if(h&&!w.has(h.host))w.add(h.host),l.push(h)};for(let h of i.sites??[])if(!h.to.includes("*"))y(c.resolve(h.to));let u=r[0]??"localhost";for(let h of f)for(let A of $(h))y(c.resolve(`${A}.${u}`));return l}function hh(i,t,n){if(!t)return i;let r=`https://${n}`;for(let f of t)if(i[f]===void 0)i[f]=r;return i}import{closeSync as mh,openSync as xC,readFileSync as gC}from"node:fs";import*as Rh from"node:fs/promises";import{spawn as kC}from"node:child_process";import{homedir as VC}from"node:os";import*as bn from"node:path";import*as Vi from"node:process";import*as gf from"node:net";function Bh(i,t,n){return Y("port",`Checking if port ${i} is in use on ${t}`,n),new Promise((r)=>{let f=gf.createServer(),$=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout($),c.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,n),r(!0);else Y("port",`Error checking port ${i}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout($),Y("port",`Port ${i} is available`,n),f.close(),r(!1)});try{f.listen(i,t)}catch(c){clearTimeout($),Y("port",`Exception checking port ${i}: ${c}`,n),r(!0)}})}async function ec(i,t,n,r=50){Y("port",`Finding available port starting from ${i} (max attempts: ${r})`,n);let f=i,$=0;while($<r){if($++,!await Bh(f,t,n))return Y("port",`Found available port: ${f} after ${$} attempts`,n),f;Y("port",`Port ${f} is in use, trying ${f+1} (attempt ${$}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${i}`)}function Yh(i,t,n=5000,r){return Y("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let $=gf.connect({host:t,port:i,timeout:n});$.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,r),$.end(),f(!0)}),$.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,r),$.destroy(),f(!1)}),$.once("error",(c)=>{Y("port",`Failed to connect to ${t}:${i}: ${c.message}`,r),$.destroy(),f(!1)})})}class Ch{usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,n=50){this.hostname=i,this.verbose=t,this.maxRetries=n}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await Bh(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await Yh(i,this.hostname,3000,this.verbose))return Y("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let n=await ec(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await Yh(n,this.hostname,3000,this.verbose))if(n<i+this.maxRetries)return this.findNextAvailablePort(n+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var AX=new Ch;import*as kf from"node:fs";import*as ji from"node:fs/promises";import{homedir as MC}from"node:os";import*as Ic from"node:path";import*as Vf from"node:process";var HC=/^[a-zA-Z0-9._-]+$/;function St(){return Ic.join(MC(),".stacks","rpx","registry.d")}function _c(i){return typeof i==="string"&&i.length>0&&i.length<=128&&HC.test(i)}function Kc(i,t){if(!_c(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Ic.join(i,`${t}.json`)}function mi(i){if(!Number.isInteger(i)||i<=0)return!1;try{return Vf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function Uh(i){if(!i||typeof i!=="object")return!1;let t=i,n=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,r=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",$=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&_c(t.id)&&(r||f)&&typeof t.to==="string"&&t.to.length>0&&$&&n&&typeof t.createdAt==="string"}async function qC(i){await ji.mkdir(i,{recursive:!0})}async function jh(i,t=St(),n){if(!Uh(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await qC(t);let r=Kc(t,i.id),f=`${r}.tmp.${Vf.pid}.${Date.now()}`,$=JSON.stringify(i,null,2);try{await ji.writeFile(f,$,{encoding:"utf8",mode:420}),await ji.rename(f,r),Y("registry",`wrote entry ${i.id} → ${r}`,n)}catch(c){throw await ji.unlink(f).catch(()=>{}),c}}async function zc(i,t=St(),n){let r=Kc(t,i);try{await ji.unlink(r),Y("registry",`removed entry ${i}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function LC(i,t=St(),n){let r=Kc(t,i);try{let f=await ji.readFile(r,"utf8"),$=JSON.parse(f);if(!Uh($))return Y("registry",`entry ${i} failed validation, removing`,n),await ji.unlink(r).catch(()=>{}),null;return $}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return Y("registry",`entry ${i} has invalid JSON, removing`,n),await ji.unlink(r).catch(()=>{}),null;throw f}}async function Tt(i=St(),t){let n;try{n=await ji.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let $=f.slice(0,-5);if(!_c($))continue;let c=await LC($,i,t);if(c)r.push(c)}return r}async function Qn(i=St(),t){let n=await Tt(i,t),r=0;for(let f of n){if(f.pid===void 0)continue;if(!mi(f.pid))Y("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await zc(f.id,i,t).catch(()=>{}),r++}return r}function sf(i,t={}){let n=t.dir??St(),r=t.debounceMs??100,f=t.pollMs??Math.max(r*2,250),$=t.verbose;kf.mkdirSync(n,{recursive:!0});let c=null,l=!1,w=null,y=!1,u=(B)=>{return JSON.stringify(B.map((U)=>({id:U.id,from:U.from,to:U.to,path:U.path,pid:U.pid,pathRewrites:U.pathRewrites,cleanUrls:U.cleanUrls,changeOrigin:U.changeOrigin,static:U.static,loadBalancer:U.loadBalancer})).sort((U,m)=>U.id.localeCompare(m.id)))},h=()=>{if(c=null,l)return;Tt(n,$).then((B)=>{return w=u(B),i(B)}).catch((B)=>{Y("registry",`watcher onChange failed: ${B}`,$)})},A=()=>{if(l)return;if(c)clearTimeout(c);c=setTimeout(h,r)},C=setInterval(()=>{if(l||y)return;y=!0,Tt(n,$).then((B)=>{if(u(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,$)}).finally(()=>{y=!1})},f),E=kf.watch(n,{persistent:!0},(B,U)=>{if(U&&/\.tmp\.\d+\.\d+$/.test(U))return;A()});return E.on("error",(B)=>{Y("registry",`watcher error: ${B}`,$)}),A(),{close:()=>{if(l=!0,c)clearTimeout(c);clearInterval(C),E.close()}}}var sC=120000,dC=200,DC=30000,QC=3000,bC=4000;class Oc{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??St(),this.rpxDir=i.rpxDir??bn.join(VC(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??sC,this.pollIntervalMs=i.pollIntervalMs??dC,this.restartDelayMs=i.restartDelayMs??QC,this.killGraceMs=i.killGraceMs??bC,this.launch=i.launcher??ZC(this.verbose),this.probePort=i.probePort??PC,this.pickPort=i.pickPort??((n)=>ec(n,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??jh,this.removeEntry=i.removeEntry??zc;let t=i.reapIntervalMs??DC;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let n=this.resolver.resolve(i);if(!n)return{kind:"unknown"};t=await this.start(n)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let l of i.routes){if(t.has(l.portEnv))continue;let w=await this.pickPort(l.defaultPort??3000);t.set(l.portEnv,w)}let n=bn.join(this.rpxDir,"sites",`${i.id}.log`);await Rh.mkdir(bn.dirname(n),{recursive:!0}).catch(()=>{});let r=this.buildEnv(i,t),f=null,$;try{f=this.launch({command:i.command,cwd:i.dir,env:r,logPath:n})}catch(l){$=`failed to spawn: ${l.message}`}let c={site:i,status:$?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:$?this.now():0,error:$,logPath:n,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,c),$)return e.warn(`rpx: site ${i.host} ${$}`),c;return e.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then((l)=>this.onProcessExit(c,l)).catch(()=>{}),c.ready=this.driveReadiness(c).catch((l)=>{Y("sites",`readiness loop for ${i.host} threw: ${l}`,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"){e.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let n of i.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,n=this.now()+this.startupTimeoutMs,r=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<n&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await r()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",e.success(`rpx: ${t.host} ready`);return}await ac(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let n=i.routes.filter((f)=>f.readyGate??Mt(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),r=n.length>0?n:[...t.values()];return async()=>{for(let f of r)if(!await this.probePort(f))return!1;return r.length>0}}async publishRoutes(i){let{site:t,ports:n}=i;if(t.selfRegisters||t.routes.length===0)return;let r=t.routes.find((w)=>Mt(w.path)==="/")??t.routes[0],f=n.get(r.portEnv);if(f===void 0)return;let $=[];for(let w of t.routes){if(w===r)continue;let y=n.get(w.portEnv);if(y===void 0)continue;$.push({from:Mt(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:$.length>0?$:void 0,pid:i.handle?.pid};await this.writeEntry(c,this.registryDir,this.verbose),i.routeIds=[t.id];let l=this.now()+2000;while(this.now()<l&&!this.isHostRoutable(t.host))await ac(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),e.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(Vi.env))if(typeof f==="string")n[r]=f;Object.assign(n,i.env);for(let[r,f]of t)n[r]=String(f);return n.RPX_SITE_HOST=i.host,n.RPX_SITE_URL=`https://${i.host}`,n}readLogTail(i,t=40){try{return gC(i.logPath,"utf8").split(`
|
|
186
|
-
`).slice(-t).join(`
|
|
187
|
-
`).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let n of t.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),e.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let n=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof n.unref==="function")n.unref();await Promise.race([t.exited.catch(()=>{}),ac(this.killGraceMs+500)]),clearTimeout(n)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,n]of this.sites){let r=n.site.idleTimeoutMs;if(r<=0)continue;let f=i-n.lastAccess;if((n.status==="ready"||i-n.startedAt>this.startupTimeoutMs)&&f>r)Y("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function ac(i){return new Promise((t)=>setTimeout(t,i))}async function PC(i){let t=new AbortController,n=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(n)}}function ZC(i){let t=vC();return({command:n,cwd:r,env:f,logPath:$})=>{let c=xC($,"a");try{let l=kC("sh",["-c",n],{cwd:r,env:f,detached:!0,stdio:["ignore",c,c],...t?{uid:t.uid,gid:t.gid}:{}}),w=l.pid;if(w===void 0)throw Error("spawn returned no pid");let y=new Promise((u)=>{l.once("exit",(h)=>{u(h)}),l.once("error",()=>{u(null)})}).finally(()=>{try{mh(c)}catch{}});return Y("sites",`spawned pid ${w}: sh -c ${n} (cwd ${r})`,i),{pid:w,exited:y,stop:(u="SIGTERM")=>{try{Vi.kill(-w,u)}catch{try{l.kill(u)}catch{}}}}}catch(l){try{mh(c)}catch{}throw l}}}function vC(){if(Vi.platform==="win32")return null;if(!(typeof Vi.getuid==="function"&&Vi.getuid()===0))return null;let t=Number.parseInt(Vi.env.SUDO_UID??"",10),n=Number.parseInt(Vi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(n)||n<=0)return null;return{uid:t,gid:n}}function jn(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var pC=`
|
|
188
|
-
:root { color-scheme: light dark }
|
|
189
|
-
* { box-sizing: border-box }
|
|
190
|
-
body {
|
|
191
|
-
margin: 0; min-height: 100vh; display: grid; place-items: center;
|
|
192
|
-
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
193
|
-
background: #0b0c0f; color: #e7e9ee;
|
|
194
|
-
}
|
|
195
|
-
.card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
|
|
196
|
-
.row { display: flex; align-items: center; gap: .75rem; }
|
|
197
|
-
h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
|
|
198
|
-
p { margin: .5rem 0 0; color: #9aa1ad }
|
|
199
|
-
code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
|
|
200
|
-
pre {
|
|
201
|
-
margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
|
|
202
|
-
background: #16181d; border: 1px solid #23262d; border-radius: 8px;
|
|
203
|
-
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
|
|
204
|
-
white-space: pre-wrap; word-break: break-word;
|
|
205
|
-
}
|
|
206
|
-
.spinner {
|
|
207
|
-
width: 16px; height: 16px; border-radius: 50%;
|
|
208
|
-
border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
|
|
209
|
-
animation: spin .8s linear infinite;
|
|
210
|
-
}
|
|
211
|
-
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
212
|
-
@keyframes spin { to { transform: rotate(360deg) } }
|
|
213
|
-
`;function Nh(i,t,n){return`<!doctype html>
|
|
214
|
-
<html lang="en">
|
|
215
|
-
<head>
|
|
216
|
-
<meta charset="utf-8">
|
|
217
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
218
|
-
${n>0?`<meta http-equiv="refresh" content="${n}">`:""}
|
|
219
|
-
<title>${jn(i)}</title>
|
|
220
|
-
<style>${pC}</style>
|
|
221
|
-
</head>
|
|
222
|
-
<body><main class="card">${t}</main></body>
|
|
223
|
-
</html>`}function Wh(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),n=i.logTail?`<pre>${jn(i.logTail)}</pre>`:"",r=`
|
|
224
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${jn(i.host)}…</h1></div>
|
|
225
|
-
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
226
|
-
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
227
|
-
<p>Booting for ${t}s.</p>
|
|
228
|
-
${n}`;return new Response(Nh(`Starting ${i.host}`,r,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function Xh(i){let t=i.logTail?`<pre>${jn(i.logTail)}</pre>`:"<p>No output was captured.</p>",n=`
|
|
229
|
-
<div class="row"><div class="dot"></div><h1>${jn(i.host)} failed to start</h1></div>
|
|
230
|
-
<p>${jn(i.error)}</p>
|
|
231
|
-
${t}
|
|
232
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(Nh(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as oC}from"node:child_process";import Zn from"node:fs";import iU from"node:os";import eh from"node:path";import*as Ht from"node:process";import{promisify as tU}from"node:util";var Pn=tU(oC);function Sh(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var bi=Ht.platform==="win32"?eh.join(Ht.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Fh="# rpx",nU="# Added by rpx",vn=new Set(["127.0.0.1","::1"]),Gc=!1;async function Ih(i){if(Ht.platform==="win32")throw Error("Administrator privileges required on Windows");if(Jh()){let{stdout:r}=await Pn(i);return r}let t=Mc(),n=i.replace(/'/g,"'\\''");try{if(t){let{stdout:r}=await Pn(`echo '${t}' | sudo -S sh -c '${n}' 2>/dev/null`);return Gc=!0,r}if(Gc)try{let{stdout:r}=await Pn(`sudo -n sh -c '${n}'`);return r}catch(r){Y("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:r}=await Pn(`sudo -n sh -c '${n}'`);return Gc=!0,r}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}function pn(i){let t=i.indexOf("#"),n=(t===-1?i:i.slice(0,t)).trim();if(!n)return null;let r=t===-1?"":i.slice(t+1).trim(),[f,...$]=n.split(/\s+/);if(!f||$.length===0)return null;let c=/^rpx(?::pid=(\d+))?$/.exec(r);return{address:f,names:$,comment:r,rpxPid:c?.[1]?Number.parseInt(c[1],10):null,rpxManaged:c!==null}}function _h(i,t){let n=pn(i);return n!==null&&vn.has(n.address)&&n.names.includes(t)}function rU(i,t){let n=new Set(t),r=new Set,f=i.split(`
|
|
233
|
-
`),$=[],c=0;while(c<f.length){let l=f[c];if(l.trim()===nU){let y=[],u=c+1;while(u<f.length){let A=f[u];if(A.trim()===""||A.trim().startsWith("#"))break;y.push(A),u++}let h=y.filter((A)=>{let T=pn(A),C=T!==null&&vn.has(T.address)&&T.names.some((E)=>n.has(E));if(C){for(let E of T.names)if(n.has(E))r.add(E)}return!C});if(h.length>0||y.length===0)$.push(l,...h);c=u;continue}let w=pn(l);if(w?.rpxManaged&&vn.has(w.address)&&w.names.some((y)=>n.has(y))){for(let y of w.names)if(n.has(y))r.add(y);c++;continue}$.push(l),c++}while($.length>0&&$[$.length-1].trim()==="")$.pop();return{content:`${$.join(`
|
|
234
|
-
`)}
|
|
235
|
-
`,removed:[...r]}}function fU(i,t){let n=[],r=new Set,f=[];for(let $ of i.split(`
|
|
236
|
-
`)){let c=pn($);if(c?.rpxManaged&&c.rpxPid!==null&&vn.has(c.address)&&!t(c.rpxPid)){n.push(...c.names),r.add(c.rpxPid);continue}f.push($)}while(f.length>0&&f[f.length-1].trim()==="")f.pop();return{content:`${f.join(`
|
|
237
|
-
`)}
|
|
238
|
-
`,removed:n,stalePids:[...r]}}async function Hc(i){try{return await Zn.promises.readFile(bi,"utf-8")}catch{return Y("hosts","Reading hosts file requires elevated permissions, using sudo",i),Ih(`cat "${bi}"`)}}async function qc(i,t){let n=eh.join(iU.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Zn.promises.writeFile(n,i,"utf8"),await Ih(`cat "${n}" | tee "${bi}" > /dev/null`)}finally{await Zn.promises.unlink(n).catch((r)=>{Y("hosts",`Failed to remove temporary file: ${r}`,t)})}}async function OX(i,t){let n=i.filter((f)=>!Sh(f)),r=i.filter((f)=>Sh(f));if(r.length>0)Y("hosts",`Skipping /etc/hosts for loopback dev names: ${r.join(", ")}`,t);if(n.length===0)return;Y("hosts",`Adding hosts: ${n.join(", ")}`,t),Y("hosts",`Using hosts file at: ${bi}`,t);try{let f;try{f=await Hc(t)}catch(y){throw console.log(" Could not read hosts file — skipping hosts setup"),Y("hosts",`sudo read also failed: ${y}`,t),Error(`Cannot read hosts file: ${y}`)}let $=f.split(`
|
|
239
|
-
`),c=n.filter((y)=>!$.some((u)=>_h(u,y)));if(c.length===0){Y("hosts","All hosts already exist in hosts file",t);return}let l=Ht.pid,w=c.map((y)=>`
|
|
240
|
-
127.0.0.1 ${y} ${Fh}:pid=${l}
|
|
241
|
-
::1 ${y} ${Fh}:pid=${l}`).join(`
|
|
242
|
-
`);try{await qc(f+w,t),console.log(` Hosts updated: ${c.join(", ")}`)}catch(y){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),c.forEach((u)=>{console.log(` 127.0.0.1 ${u}`),console.log(` ::1 ${u}`)}),console.log(` Or run: sudo nano ${bi}`)}}catch(f){Y("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function GX(i,t){Y("hosts",`Removing hosts: ${i.join(", ")}`,t);try{let n;try{n=await Hc(t)}catch($){throw Y("hosts",`sudo read also failed: ${$}`,t),Error(`Cannot read hosts file: ${$}`)}let{content:r,removed:f}=rU(n,i);if(f.length===0){Y("hosts","No matching rpx-managed hosts found to remove",t);return}try{await qc(r,t),Y("hosts",`Hosts removed successfully: ${f.join(", ")}`,t)}catch($){Y("hosts","Could not clean up hosts file automatically",t)}}catch(n){Y("hosts",`Failed to clean up hosts file: ${n.message}`,t)}}async function MX(i,t){Y("hosts",`Checking hosts: ${i}`,t);let n;try{n=await Zn.promises.readFile(bi,"utf-8")}catch(f){Y("hosts",`Error reading hosts file: ${f}`,t);try{let $=Mc(),c;if($)c=`echo '${$}' | sudo -S cat "${bi}" 2>/dev/null`;else c=`sudo -n cat "${bi}" 2>/dev/null || cat "${bi}" 2>/dev/null || echo ""`;let{stdout:l}=await Pn(c);n=l}catch($){return Y("hosts",`Cannot read hosts file, assuming entries don't exist: ${$}`,t),i.map(()=>!1)}}let r=n.split(`
|
|
243
|
-
`);return i.map((f)=>r.some(($)=>_h($,f)))}async function HX(i=mi){let t;try{t=await Zn.promises.readFile(bi,"utf-8")}catch{return[]}let n=[];for(let r of t.split(`
|
|
244
|
-
`)){let f=pn(r);if(f?.rpxManaged&&f.rpxPid!==null&&vn.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function on(i={}){let t=i.isAlive??mi,n;try{n=await Hc(i.verbose)}catch(c){return Y("hosts",`stale hosts GC: cannot read hosts file: ${c}`,i.verbose),[]}let{content:r,removed:f,stalePids:$}=fU(n,t);if(f.length===0)return[];try{return await qc(r,i.verbose),Y("hosts",`stale hosts GC: removed ${f.join(", ")} (dead pid(s): ${$.join(", ")})`,i.verbose),[...new Set(f)]}catch(c){return Y("hosts",`stale hosts GC: write failed: ${c}`,i.verbose),[]}}var $U=5000;function Ri(){return Pi.join(Mh(),".stacks","rpx")}function bf(i=Ri()){return Pi.join(i,"daemon.pid")}async function Rn(i=Ri()){try{let t=await Ti.readFile(bf(i),"utf8"),n=Number.parseInt(t.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(t){if(t.code==="ENOENT")return null;throw t}}async function cU(i=Ri()){let t=await Rn(i);return t!==null&&mi(t)}async function Hh(i=Ri()){await Ti.mkdir(i,{recursive:!0});let t=bf(i);while(!0){try{let r=await Ti.open(t,"wx");try{await r.write(`${R.pid}
|
|
245
|
-
`)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await Rn(i);if(n!==null&&mi(n))throw Error(`rpx daemon already running (pid=${n})`);await Ti.unlink(t).catch(()=>{})}}async function mn(i=Ri()){await Ti.unlink(bf(i)).catch(()=>{})}var Df=new Map;function Qf(i){for(let[t,n]of Df)if(!i.has(t))Tc(n),Df.delete(t)}function lU(i,t){let n=au(t??"localhost:1");if(i.upstreams.length!==n.length)return!1;return i.upstreams.every((r,f)=>r.url===n[f])}function qh(i){let t=i.cleanUrls??!1,n=Mt(i.path),r=xu(i.auth);if(i.static)return{static:vu(i.static,t),cleanUrls:t,basePath:n,auth:r};let f=i.from??"localhost:1",$=Ou(f),c=new URL($.startsWith("http")?$:`http://${$}`),l=Df.get(i.id);if(l&&!lU(l,f))Tc(l),l=void 0;if(!l)l=Gu(f,i.loadBalancer),Hu(l),Df.set(i.id,l);return{sourceHost:c.host,upstreamPool:l,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:n,auth:r}}function wU(i){return i.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??i[0]??"rpx.localhost"}async function df(i,t,n=[],r=!1){let f=await Tt(t,i.verbose),$=[...new Set([...f.map((u)=>u.to).filter(Boolean),...n])],c=wU($),l=[...new Set([c,...$,"rpx.localhost"])],w=Iu($,c,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let y=await hc(w);if(y&&(r||!tc(wc,l)))Y("daemon",`regenerating shared cert for host(s): ${l.join(", ")}`,i.verbose),uc(),y=null;if(!y)Y("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Ku({...w,forceRegenerate:!0}),y=await hc(w);if(!y)throw Error("failed to bootstrap TLS for rpx daemon");return y}async function yU(i,t,n,r){let f=R.env.SUDO_PASSWORD,$=R.env.HOME??Mh(),c=[R.execPath,...R.argv.slice(1)],l=[`HOME=${$}`,`PATH=${R.env.PATH??""}`];if(r)l.push("RPX_VERBOSE=1");for(let[C,E]of Object.entries(R.env))if(E!==void 0&&C!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(C))l.push(`${C}=${E}`);let w=f?["-S","-p","","env",...l,...c]:["-n","env",...l,...c];Y("daemon",`elevating daemon via sudo for privileged ports ${t}/${n}`,r);let y=Gh("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,h=null;if(y.once("error",(C)=>{u=C}),y.once("exit",(C)=>{h=C??0}),f&&y.stdin)y.stdin.write(`${f}
|
|
246
|
-
`),y.stdin.end();y.unref();let A=bf(i),T=Date.now()+15000;while(Date.now()<T){if(u)throw u;let C=await Rn(i);if(C!==null&&mi(C)){if(r)e.success(`rpx daemon elevated to root (pid=${C}, https on :${t})`);return{httpsPort:t,httpPort:n,pidPath:A,done:Promise.resolve(),stop:async()=>{try{R.kill(C,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(h!==null&&h!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${h}). 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 Kh=!1;function Lc(){if(Kh)return;Kh=!0,R.on("uncaughtException",(i)=>{e.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),R.on("unhandledRejection",(i)=>{e.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function Lh(i,t,n){let r;try{r=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??r.hostname).split(":")[0];if(r.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let $=t.challengeStore.handlePath(r.pathname);if($!==void 0)return new Response($,{status:200,headers:{"content-type":"text/plain"}})}if(n){let $=ch(n,r.pathname);if($!=null)return new Response($,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${r.pathname}${r.search}`}})}async function $S(i={}){Lc();let t=i.verbose??!1,n=i.rpxDir??Ri(),r=i.registryDir??Pi.join(n,"registry.d"),f=i.httpsPort??443,$=i.httpPort??80,c=i.hostname??"0.0.0.0",l=i.gcIntervalMs??$U;if(R.env.RPX_DAEMON_WORKER==="1")return AU({rpxDir:R.env.RPX_WORKER_RPXDIR??n,registryDir:R.env.RPX_WORKER_REGISTRYDIR??r,httpsPort:Number.parseInt(R.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:R.env.RPX_WORKER_HOSTNAME??c,verbose:R.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||$>0&&$<1024,y=typeof R.getuid==="function"&&R.getuid()===0;if(R.platform!=="win32"&&w&&!y)return yU(n,f,$,t);let u=Math.max(1,i.workers??(Number.parseInt(R.env.RPX_WORKERS??"",10)||1));if(u>1){if(i.onDemandSites?.enabled)e.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return TU(i,{rpxDir:n,registryDir:r,httpsPort:f,httpPort:$,hostname:c,verbose:t,gcIntervalMs:l,workers:u})}let h=await Hh(n),A=new Map,T=(j,I)=>Rc(A,j,I);function C(j){A=jc(j.map((Di)=>({host:Di.to,path:Di.path,route:qh(Di)}))),Qf(new Set(j.map((Di)=>Di.id)));let I=Array.from(A.keys());Y("daemon",`routing table now covers ${I.length} host(s): ${I.join(", ")||"<empty>"}`,t)}await Qn(r,t).catch((j)=>{Y("daemon",`initial gc failed: ${j}`,t)}),await on({verbose:t}).catch((j)=>{Y("daemon",`stale hosts GC on start failed: ${j}`,t)});let E=await Tt(r,t);C(E),await Wn({rpxDir:n,verbose:t}).catch((j)=>{Y("daemon",`DNS reconcile on start failed: ${j}`,t)}),await ir(E,{rpxDir:n,verbose:t,ownerPid:R.pid}).catch((j)=>{Y("daemon",`DNS setup on start failed: ${j}`,t)});let B=[];if(i.productionCerts){if(B=await Wc(i.productionCerts,t),t&&B.length>0)e.info(`SNI: serving ${B.length} real cert(s): ${B.map((j)=>j.serverName).join(", ")}`)}let U=new Set,m=null,S;if(i.onDemandSites?.enabled){if(m=new Oc({resolver:Jc(i.onDemandSites),registryDir:r,rpxDir:n,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(j)=>mc(A,j)!==void 0,onSiteActivating:(j)=>{_t(j)}}),S=async(j)=>{let I=await m.onRequest(j);switch(I.kind){case"ready":return{retry:!0};case"starting":return Wh({host:I.host,sinceMs:I.sinceMs,logTail:I.logTail});case"failed":return Xh({host:I.host,error:I.error,logTail:I.logTail});case"unknown":default:return}},t)e.info("rpx: on-demand sites enabled")}let F=Bc(T,t,S),W=Cc(t),J=null;if(B.length===0)J=await df(i,r);let H=i.onDemandTls,p=H?.enabled?new xf({config:H,certsDir:H.certsDir??i.productionCerts?.certsDir??Pi.join(n,"on-demand-certs"),initial:B,verbose:t,onCertAdded:(j)=>{Lt(j)}}):null;function si(j){if(j.length>0)return j.map((I)=>({serverName:I.serverName,cert:I.cert,key:I.key}));return{key:J.key,cert:J.cert,ca:J.ca,requestCert:!1,rejectUnauthorized:!1}}function rr(j){return Bun.serve({port:f,hostname:c,reusePort:Oh(),tls:si(j),fetch(I,Di){return F(I,Di)},websocket:W,error(I){return Y("daemon",`https server error: ${I}`,t),new Response(`Server Error: ${I.message}`,{status:500})}})}let Jt=(j)=>[...new Set(j.map((I)=>I.to).filter(Boolean))],qt=(j)=>{if(!J)return B;return eu([...Jt(j),...U,"rpx.localhost"],J)},Yt=rr(p?p.sniEntries():B.length>0?B:qt(E)),et=null,It=!1;async function Lt(j){if(di)return;if(et=j,It)return;It=!0;try{while(!di&&et){let I=et;et=null,Y("daemon",`rebuilding :443 with ${I.length} SNI cert(s)`,t),Yt.stop(!1);let Di,t0=!1,Pc=60,i1=500;for(let n0=0;!di&&!t0;n0++)try{Yt=rr(I),t0=!0;break}catch(t1){if(Di=t1,n0>=Pc)break;await new Promise((n1)=>setTimeout(n1,Math.min(25*2**Math.min(n0,4),i1)))}if(!t0)e.error(`rpx: CRITICAL — could not rebind :443 after ${Pc} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Di?.message}`)}}finally{It=!1}}let Zi=null;if($>0)Zi=Bun.serve({port:$,hostname:c,fetch(j){return Lh(j,p,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)e.success(`rpx daemon listening on https://${c}:${f}${Zi?` (http→https on :${$})`:""}`),e.info(`pid file: ${h}`),e.info(`registry: ${r}`);async function _(j){if(di||B.length>0||p||!J)return;try{J=await df(i,r,[...U]),await Lt(qt(j))}catch(I){Y("daemon",`TLS sync on registry change failed: ${I}`,t)}}async function _t(j){if(di||B.length>0||p||!J||!j)return;if(U.has(j))return;U.add(j);try{J=await df(i,r,[...U],!0);let I=await Tt(r,t);await Lt(qt(I))}catch(I){Y("daemon",`dev cert refresh for ${j} failed: ${I}`,t)}}let of=sf((j)=>{C(j),_(j),ir(j,{rpxDir:n,verbose:t,ownerPid:R.pid}).catch((I)=>{Y("daemon",`DNS sync on registry change failed: ${I}`,t)})},{dir:r,verbose:t}),xt=setInterval(()=>{Qn(r,t).then((j)=>{if(j>0)Y("daemon",`gc reaped ${j} stale entries`,t)}).catch((j)=>{Y("daemon",`periodic gc failed: ${j}`,t)}),on({verbose:t}).then((j)=>{if(j.length>0)Y("daemon",`gc reaped stale hosts entries: ${j.join(", ")}`,t)}).catch((j)=>{Y("daemon",`periodic hosts gc failed: ${j}`,t)})},l);if(typeof xt.unref==="function")xt.unref();let di=!1,Xn,gt=new Promise((j)=>{Xn=j});async function i0(){if(di)return gt;if(di=!0,clearInterval(xt),of.close(),await m?.stopAll().catch((j)=>{Y("daemon",`site supervisor stopAll failed: ${j}`,t)}),Yt.stop(!1),Zi?.stop(!1),await Nn({rpxDir:n,verbose:t}).catch((j)=>{Y("daemon",`DNS teardown failed: ${j}`,t)}),Qf(new Set),await mn(n),t)e.info("rpx daemon stopped");return Xn(),gt}let bc=(j)=>{Y("daemon",`received ${j}, shutting down`,t),i0().catch(()=>{})};return R.once("SIGINT",bc),R.once("SIGTERM",bc),{stop:i0,done:gt,httpsPort:typeof Yt.port==="number"?Yt.port:f,httpPort:Zi&&typeof Zi.port==="number"?Zi.port:$,pidPath:h,ensureCert:(j)=>p?p.ensureCert(j):Promise.resolve(!1),listSites:()=>m?.list()??[]}}function xc(i){return Pi.join(i,"cluster-sni.json")}async function zh(i,t,n){let r=xc(i),f=`${r}.${R.pid}.tmp`;await Ti.writeFile(f,JSON.stringify({sni:t,dev:n}),"utf8"),await Ti.rename(f,r)}async function ah(i){try{return JSON.parse(await Ti.readFile(xc(i),"utf8"))}catch{return{sni:[],dev:null}}}function uU(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 hU(){let i=R.execPath,t=R.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let n=Pi.basename(i).toLowerCase();if((n==="bun"||n==="node"||n.startsWith("bun-"))&&R.argv[1])return[i,R.argv[1],"daemon:start"];return[i,"daemon:start"]}async function AU(i){Lc();let{rpxDir:t,registryDir:n,httpsPort:r,hostname:f,verbose:$}=i,c=new Map,l=(W,J)=>Rc(c,W,J),w=(W)=>{c=jc(W.map((J)=>({host:J.to,path:J.path,route:qh(J)}))),Qf(new Set(W.map((J)=>J.id)))};w(await Tt(n,$));let y=Bc(l,$),u=Cc($),h=!1,A=(W)=>Bun.serve({port:r,hostname:f,reusePort:!0,tls:uU(W),fetch(J,H){return y(J,H)},websocket:u,error(J){return Y("daemon",`worker https error: ${J}`,$),new Response(`Server Error: ${J.message}`,{status:500})}}),T=A(await ah(t));async function C(){if(h)return;let W=await ah(t),J=null;for(let p=0;p<20&&!h;p++)try{J=A(W);break}catch{await new Promise((si)=>setTimeout(si,25))}if(!J){Y("daemon","worker reloadTls: could not bind new listener; keeping current",$);return}let H=T;T=J,H.stop(!1)}let E=sf((W)=>w(W),{dir:n,verbose:$}),B=()=>{C().catch(()=>{})};R.on("SIGHUP",B);let U,m=new Promise((W)=>{U=W});async function S(){if(h)return m;return h=!0,R.off("SIGHUP",B),E.close(),T.stop(!1),Qf(new Set),U(),m}let F=()=>{S().then(()=>R.exit(0)).catch(()=>R.exit(0))};if(R.once("SIGTERM",F),R.once("SIGINT",F),$)e.success(`rpx worker (pid ${R.pid}) serving :${r}`);return{stop:S,done:m,httpsPort:typeof T.port==="number"?T.port:r,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function TU(i,t){Lc();let{rpxDir:n,registryDir:r,httpsPort:f,httpPort:$,hostname:c,verbose:l,gcIntervalMs:w,workers:y}=t,u=await Hh(n),h=[];if(i.productionCerts)h=await Wc(i.productionCerts,l);let A=null;if(h.length===0)A=await df(i,r);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
|
|
247
|
-
`):A.ca}:null,C=!1,E=[];function B(_){for(let _t of E)try{_t.kill(_)}catch{}}async function U(_){await zh(n,_,T),B("SIGHUP")}let m=i.onDemandTls,S=m?.enabled?new xf({config:m,certsDir:m.certsDir??i.productionCerts?.certsDir??Pi.join(n,"on-demand-certs"),initial:h,verbose:l,onCertAdded:(_)=>{U(_)}}):null;await zh(n,S?S.sniEntries():h,T);let F=await Tt(r,l);await Wn({rpxDir:n,verbose:l}).catch((_)=>{Y("daemon",`DNS reconcile on start failed: ${_}`,l)}),await ir(F,{rpxDir:n,verbose:l,ownerPid:R.pid}).catch((_)=>{Y("daemon",`DNS setup on start failed: ${_}`,l)}),await Qn(r,l).catch(()=>{}),await on({verbose:l}).catch(()=>{});let W=sf((_)=>{ir(_,{rpxDir:n,verbose:l,ownerPid:R.pid}).catch((_t)=>{Y("daemon",`DNS sync on registry change failed: ${_t}`,l)})},{dir:r,verbose:l}),J=setInterval(()=>{Qn(r,l).catch(()=>{}),on({verbose:l}).catch(()=>{})},w);J.unref?.();let H=null;if($>0)H=Bun.serve({port:$,hostname:c,fetch(_){return Lh(_,S,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let p=10,si=60000,rr=30000,Jt=0,qt=Date.now();function Yt(){if(C)return;let _={...R.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:n,RPX_WORKER_REGISTRYDIR:r,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:c,RPX_WORKER_VERBOSE:l?"1":"0"},_t=Bun.spawn(hU(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(of,xt){if(C)return;let di=E.indexOf(of);if(di!==-1)E.splice(di,1);let Xn=Date.now();if(Xn-qt>si)qt=Xn,Jt=0;if(Jt++,Jt>p){e.error(`rpx: worker keeps exiting (code ${xt}); giving up after ${p} restarts in ${Math.round(si/1000)}s`);return}let gt=Math.min(rr,100*2**Math.min(Jt,8));Y("daemon",`worker exited (code ${xt}); respawning in ${gt}ms (restart ${Jt}/${p})`,l),setTimeout(Yt,gt).unref?.()}});E.push(_t)}for(let _=0;_<y;_++)Yt();if(l)e.success(`rpx coordinator listening on https://${c}:${f} via ${y} worker(s)${H?` (http→https on :${$})`:""}`),e.info(`pid file: ${u}`);let et,It=new Promise((_)=>{et=_});async function Lt(){if(C)return It;if(C=!0,clearInterval(J),W.close(),H?.stop(!1),B("SIGTERM"),await Promise.race([Promise.all(E.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),B("SIGKILL"),await Nn({rpxDir:n,verbose:l}).catch((_)=>{Y("daemon",`DNS teardown failed: ${_}`,l)}),await mn(n),await Ti.unlink(xc(n)).catch(()=>{}),l)e.info("rpx coordinator stopped");return et(),It}let Zi=(_)=>{Y("daemon",`coordinator received ${_}, shutting down`,l),Lt().catch(()=>{})};return R.once("SIGINT",Zi),R.once("SIGTERM",Zi),{stop:Lt,done:It,httpsPort:f,httpPort:$,pidPath:u,ensureCert:(_)=>S?S.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function EU(){let i=R.execPath,t=Pi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&R.argv[1])return[i,R.argv[1],"daemon:start"];return[i,"daemon:start"]}async function cS(i={}){let t=i.rpxDir??Ri(),n=i.verbose??!1;await Wn({rpxDir:t,verbose:n}).catch((u)=>{Y("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,n)});let r=await Rn(t);if(r!==null&&mi(r))return Y("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)Y("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await mn(t);await Ti.mkdir(t,{recursive:!0});let f=i.spawnCommand??EU();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");Y("daemon",`spawning daemon: ${f.join(" ")}`,n);let $=Gh(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??R.cwd(),env:i.spawnEnv?{...R.env,...i.spawnEnv}:R.env});$.unref();let c=null;$.once("error",(u)=>{c=u});let l=i.startupTimeoutMs??5000,w=i.pollIntervalMs??50,y=Date.now()+l;while(Date.now()<y){if(c)throw c;let u=await Rn(t);if(u!==null&&mi(u))return Y("daemon",`daemon registered with pid=${u}`,n),{pid:u,spawned:!0};await new Promise((h)=>setTimeout(h,w))}if(c)throw c;throw Error(`rpx daemon failed to start within ${l}ms (rpxDir=${t})`)}async function lS(i={}){let t=i.rpxDir??Ri(),n=i.verbose??!1,r=i.timeoutMs??5000,f=i.pollIntervalMs??50,$=i.forceAfterTimeout??!0,c=await Rn(t);if(c===null||!mi(c)){if(c!==null)await mn(t);return await Wn({rpxDir:t,verbose:n}).catch(()=>{}),{stopped:!1,pid:c,forced:!1}}try{R.kill(c,"SIGTERM")}catch(w){let y=w.code;if(y==="ESRCH")return await mn(t),{stopped:!1,pid:c,forced:!1};if(y==="EPERM")Nt(`kill -TERM ${c}`);else throw w}let l=Date.now()+r;while(Date.now()<l){if(!mi(c))return Y("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((w)=>setTimeout(w,f))}if(!$)throw Error(`rpx daemon (pid=${c}) did not exit within ${r}ms`);Y("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,n);try{R.kill(c,"SIGKILL")}catch(w){let y=w.code;if(y==="EPERM")Nt(`kill -KILL ${c}`);else if(y!=="ESRCH")throw w}return await mn(t),await Nn({rpxDir:t,verbose:n}).catch((w)=>{Y("daemon",`DNS teardown after SIGKILL: ${w}`,n)}),{stopped:!0,pid:c,forced:!0}}async function wS(i={}){let t=i.rpxDir??Ri();if(await cU(t))return;await Wn({rpxDir:t,verbose:i.verbose})}import*as Ft from"node:fs/promises";import{homedir as YU}from"node:os";import*as gc from"node:path";var Pf=1,BU="dns-state.json",xh=["com","test","dev","app","page","local","localhost","example","invalid"];function gh(){return gc.join(YU(),".stacks","rpx")}function kc(i=gh()){return gc.join(i,BU)}async function Zf(i=gh()){try{let t=await Ft.readFile(kc(i),"utf8"),n=JSON.parse(t);if(n.version!==Pf||!Array.isArray(n.resolvers))return null;return{version:Pf,resolvers:n.resolvers.filter((r)=>typeof r==="string"),domains:Array.isArray(n.domains)?n.domains.filter((r)=>typeof r==="string"):[],ownerPid:typeof n.ownerPid==="number"?n.ownerPid:null,updatedAt:typeof n.updatedAt==="string"?n.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function kh(i,t){await Ft.mkdir(i,{recursive:!0}),await Ft.writeFile(kc(i),`${JSON.stringify(t,null,2)}
|
|
248
|
-
`,"utf8")}async function Vc(i){await Ft.rm(kc(i),{force:!0})}function Vh(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 CU(i){let t=Vh(i);if(!t)return null;let n=t.split(".");if(n.length<2)return null;return n.slice(-2).join(".")}function sc(i){let t=new Set;for(let n of i){let r=CU(n);if(r)t.add(r)}return Array.from(t).sort()}function dc(i){let t=new Set;for(let n of i){let r=Vh(n);if(r)t.add(r)}return Array.from(t).sort()}var pf=15353,UU="# managed-by: rpx",Qh="/etc/resolver",Ni=null,vf=new Set;function bh(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 Ph(i,t,n=0){let r=[],f=t,$=0;while(!0){if(f>=i.length||++$>128)break;let c=i[f];if(c===0){f++;break}if((c&192)===192){if(f+1>=i.length||n>=10)break;let l=i.readUInt16BE(f)&16383,{name:w}=Ph(i,l,n+1);if(w)r.push(w);f+=2;break}if(f++,f+c>i.length)break;r.push(i.subarray(f,f+c).toString("ascii")),f+=c}return{name:r.join("."),newOffset:f}}function jU(i,t){let{name:n,newOffset:r}=Ph(i,t),f=i.readUInt16BE(r),$=i.readUInt16BE(r+2);return{question:{name:n,type:f,class:$},newOffset:r+4}}function tr(i){let t=i.split("."),n=[];for(let r of t)n.push(Buffer.from([r.length])),n.push(Buffer.from(r,"ascii"));return n.push(Buffer.from([0])),Buffer.concat(n)}function mU(i,t,n){let r=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),r.push(f),r.push(tr(t.name));let $=Buffer.alloc(4);$.writeUInt16BE(t.type,0),$.writeUInt16BE(t.class,2),r.push($),r.push(tr(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),r.push(c);let l=n.split(".").map((w)=>Number.parseInt(w,10));r.push(Buffer.from(l))}else if(t.type===28)c.writeUInt16BE(16,8),r.push(c),r.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,tr(t.name),$]);return Buffer.concat(r)}function RU(i,t){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(i,0),r.writeUInt16BE(33155,2),r.writeUInt16BE(1,4),r.writeUInt16BE(0,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(tr(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),n.push(f),Buffer.concat(n)}async function NU(i,t){if(Et.platform!=="darwin")return!1;let n=dc(i);if(n.length===0)return!1;if(Ni){for(let r of n)vf.add(r);return Y("dns","DNS server already running — merged domains",t),!0}return vf=new Set(n),new Promise((r)=>{Ni=sh.createSocket("udp4"),Ni.on("error",(f)=>{Y("dns",`DNS server error: ${f.message}`,t),Ni?.close(),Ni=null,r(!1)}),Ni.on("message",(f,$)=>{try{let c=bh(f),{question:l}=jU(f,12);Y("dns",`Query for ${l.name} type ${l.type} from ${$.address}`,t);let w=l.name.toLowerCase(),y=!1;for(let h of vf)if(w===h||w.endsWith(`.${h}`)){y=!0;break}let u;if(y&&(l.type===1||l.type===28))u=mU(c.id,l,"127.0.0.1"),Y("dns",`Responding with localhost for ${l.name}`,t);else u=RU(c.id,l),Y("dns",`NXDOMAIN for ${l.name}`,t);Ni?.send(u,$.port,$.address)}catch(c){Y("dns",`Error processing DNS query: ${c}`,t)}}),Ni.on("listening",()=>{let f=Ni?.address();Y("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),r(!0)});try{Ni.bind(pf,"127.0.0.1")}catch(f){Y("dns",`Failed to bind DNS server: ${f}`,t),r(!1)}})}function Zh(i){if(Ni)Y("dns","Stopping DNS server",i),Ni.close(),Ni=null,vf=new Set}function CS(){return Ni!==null}async function WU(i,t=500){let n=i.trim().toLowerCase().replace(/\.$/,"");if(!n)return!1;return new Promise((r)=>{let f=sh.createSocket("udp4"),$=setTimeout(()=>{f.close(),r(!1)},t);f.on("message",(l)=>{clearTimeout($),f.close();try{let w=bh(l);r(w.ancount>0)}catch{r(!1)}}),f.on("error",()=>{clearTimeout($),f.close(),r(!1)});let c=XU(n,1);f.send(c,pf,"127.0.0.1",(l)=>{if(l)clearTimeout($),f.close(),r(!1)})})}function XU(i,t){let n=Buffer.alloc(12);n.writeUInt16BE(1,0),n.writeUInt16BE(256,2),n.writeUInt16BE(1,4);let r=Buffer.concat([tr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([n,r])}function SU(){return`${UU}
|
|
249
|
-
nameserver 127.0.0.1
|
|
250
|
-
port ${pf}
|
|
251
|
-
`}function nr(i){return Dh.join(Qh,i)}function FU(i){return i.includes("127.0.0.1")&&i.includes(String(pf))}async function JU(i){try{return await dh.readFile(nr(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Dc(i){if(Et.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:n,isProcessElevated:r}=await import("./chunk-22h4jf2c.js");if(!r()&&!n()){Y("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),Y("dns","DNS cache flushed",i)}catch(f){Y("dns",`Could not flush DNS cache: ${f}`,i)}}function vh(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function eU(i,t){vh(i);let{execSudoSync:n}=await import("./chunk-22h4jf2c.js"),r=SU().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${Qh} && printf "%b" "${r}" > ${nr(i)}'`;n(f),Y("dns",`Created ${nr(i)}`,t)}async function IU(i,t){vh(i);let{execSudoSync:n}=await import("./chunk-22h4jf2c.js");n(`rm -f ${nr(i)}`),Y("dns",`Removed ${nr(i)}`,t)}async function US(i,t){return oh({domains:t??[],verbose:i})}async function _U(i,t){if(Et.platform!=="darwin")return!0;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-22h4jf2c.js");if(!r()&&!n())return Y("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await eU(f,t);return await Dc(t),!0}catch(f){return Y("dns",`Failed to create resolver file: ${f}`,t),!1}}async function Qc(i,t){if(Et.platform!=="darwin")return;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-22h4jf2c.js");if(!r()&&!n())return;try{for(let f of i)await IU(f,t);await Dc(t)}catch(f){Y("dns",`Failed to remove resolver files: ${f}`,t)}}async function ph(i){if(Et.platform!=="darwin")return[];let t=[];for(let n of xh){let r=await JU(n);if(r&&FU(r))await Qc([n],i),t.push(n)}return t}async function oh(i){let t=i.rpxDir??Ri(),n=dc(i.domains);if(n.length===0)return!1;let r=sc(n),f=await NU(n,i.verbose);if(!f){let l=n[0];if(l&&await WU(l))f=!0;else Y("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await _U(r,i.verbose))return!1;let c={version:Pf,resolvers:r,domains:n,ownerPid:i.ownerPid??Et.pid,updatedAt:new Date().toISOString()};return await kh(t,c),!0}async function ir(i,t={}){let n=i.map((w)=>w.to).filter(Boolean),r=t.rpxDir??Ri(),f=sc(n),l=((await Zf(r))?.resolvers??[]).filter((w)=>!f.includes(w));if(l.length>0)await Qc(l,t.verbose);if(f.length===0){Zh(t.verbose),await Vc(r);return}await oh({domains:n,rpxDir:r,verbose:t.verbose,ownerPid:t.ownerPid??Et.pid})}async function Nn(i={}){let t=i.rpxDir??Ri();Zh(i.verbose);let r=(await Zf(t))?.resolvers??[];await Qc(r,i.verbose),await ph(i.verbose),await Vc(t)}async function jS(i){await Nn({verbose:i})}async function Wn(i={}){let t=i.rpxDir??Ri(),n=await Zf(t),r=n?.ownerPid!=null&&mi(n.ownerPid);if(n&&!r){Y("dns",`reconcile: owner pid ${n.ownerPid} is gone — tearing down DNS`,i.verbose),await Nn(i);return}let f=await ph(i.verbose);if(f.length>0)Y("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await Dc(i.verbose)}
|
|
252
|
-
export{e as a,mu as b,UB as c,Ot as d,ic as e,tc as f,jB as g,mB as h,Qi as i,At as j,nc as k,xn as l,rc as m,Ru as n,Of as o,gn as p,kn as q,fc as r,wc as s,eu as t,Iu as u,yc as v,eW as w,IW as x,_W as y,Ku as z,uc as A,hc as B,Ac as C,KW as D,zu as E,Ou as F,Gu as G,Mu as H,Mf as I,Vn as J,Hu as K,Tc as L,LB as M,xu as N,gu as O,xW as P,Zu as Q,vu as R,AC as S,TC as T,EC as U,pu as V,nh as W,Bc as X,Cc as Y,rh as Z,ch as _,Lf as $,Uc as aa,lh as ba,Mt as ca,jC as da,jc as ea,mc as fa,Rc as ga,mC as ha,Wc as ia,WC as ja,yh as ka,xf as la,Fc as ma,uh as na,KC as oa,zC as pa,OC as qa,Jc as ra,yX as sa,Bh as ta,ec as ua,Ch as va,AX as wa,St as xa,_c as ya,mi as za,jh as Aa,zc as Ba,LC as Ca,Tt as Da,Qn as Ea,sf as Fa,Oc as Ga,jn as Ha,Wh as Ia,Xh as Ja,Fh as Ka,pn as La,_h as Ma,rU as Na,fU as Oa,OX as Pa,GX as Qa,MX as Ra,HX as Sa,on as Ta,Pf as Ua,xh as Va,Vh as Wa,CU as Xa,sc as Ya,dc as Za,pf as _a,UU as $a,NU as ab,Zh as bb,CS as cb,WU as db,nr as eb,FU as fb,US as gb,ph as hb,oh as ib,ir as jb,Nn as kb,jS as lb,Wn as mb,Ri as nb,bf as ob,Rn as pb,cU as qb,Hh as rb,mn as sb,$S as tb,EU as ub,cS as vb,lS as wb,wS as xb};
|