@stacksjs/rpx 0.11.46 → 0.11.48
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 +239 -181
- package/dist/chunk-3tg7caak.js +311 -0
- package/dist/{chunk-t3s94va5.js → chunk-er1mtkha.js} +1 -1
- package/dist/{chunk-086aa2f7.js → chunk-handw2xw.js} +1 -1
- package/dist/{chunk-nnnptjfw.js → chunk-pcyc92vj.js} +11 -11
- package/dist/daemon.d.ts +4 -2
- package/dist/gateway.d.ts +65 -0
- package/dist/https.d.ts +8 -0
- package/dist/index.d.ts +26 -2
- package/dist/index.js +2 -2
- package/dist/local-ca.d.ts +77 -0
- package/dist/sni.d.ts +37 -0
- package/dist/start.d.ts +9 -1
- package/dist/types.d.ts +23 -0
- package/package.json +2 -2
- package/dist/chunk-z0swphpg.js +0 -253
package/dist/chunk-z0swphpg.js
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
import{Ab as W,Bb as Wa,Cb as Lh,Eb as $t,Fb as m,Gb as Kh,Kb as Du,Lb as ha,Nb as In,Ob as Fu,Qb as fh,Rb as Bu}from"./chunk-nnnptjfw.js";import Zh from"node:dgram";import*as ed from"node:fs/promises";import*as td from"node:path";import*as yt from"node:process";import{spawn as Hh}from"node:child_process";import*as ge from"node:fs/promises";import{homedir as Yh}from"node:os";import*as Qe from"node:path";import*as C from"node:process";var A={info:(...e)=>console.log("[info]",...e),success:(...e)=>console.log("[success]",...e),warn:(...e)=>console.warn("[warn]",...e),error:(...e)=>console.error("[error]",...e),debug:(...e)=>console.debug("[debug]",...e),log:(...e)=>console.log(...e),start:(...e)=>console.log("[start]",...e),box:(...e)=>console.log("[box]",...e)};import{execSync as fa}from"node:child_process";import G from"node:fs/promises";import*as ua from"node:os";import{homedir as mr}from"node:os";import*as Lu from"node:path";import{join as X}from"node:path";import*as Ve from"node:process";import{createRequire as hd}from"node:module";import{Resolver as as}from"node:dns/promises";import{createHash as md,sign as gd}from"node:crypto";import{createHash as pd}from"node:crypto";import{sign as yd}from"node:crypto";import{generateKeyPairSync as cl,X509Certificate as Td}from"node:crypto";import cs from"node:os";import ls from"node:path";import{existsSync as nc,statSync as sc}from"fs";import{existsSync as Ad,mkdirSync as sC,readdirSync as oC,readFileSync as Rd,writeFileSync as aC}from"fs";import{homedir as jt}from"os";import{dirname as fC,resolve as Oe}from"path";import Vi from"process";import{existsSync as oc,statSync as ac}from"fs";import{existsSync as Ds,mkdirSync as kd,readdirSync as Nd,writeFileSync as Od}from"fs";import{homedir as Ut}from"os";import{dirname as cc,resolve as ye}from"path";import Nt from"process";import{join as Dd,relative as Fd,resolve as lc}from"path";import Ri from"process";import{existsSync as ll,mkdirSync as bC,readdirSync as CC,writeFileSync as SC}from"fs";import{homedir as fs}from"os";import{dirname as $C,resolve as pe}from"path";import Ar from"process";import{join as Bd,relative as Ld,resolve as fc}from"path";import ki from"process";import{existsSync as fl,mkdirSync as kC,readdirSync as NC,writeFileSync as OC}from"fs";import{dirname as FC,resolve as Ni}from"path";import Fs from"process";import{Buffer as vt}from"buffer";import{createCipheriv as Md,createDecipheriv as Id,randomBytes as us}from"crypto";import{closeSync as hs,createReadStream as uc,createWriteStream as _d,existsSync as ds,fsyncSync as hc,openSync as dc,writeFileSync as jd}from"fs";import{access as Ud,constants as mc,mkdir as Wd,readdir as oi,rename as gc,stat as Wt,unlink as ai,writeFile as ms}from"fs/promises";import{join as Kt}from"path";import le from"process";import{pipeline as Kd}from"stream/promises";import{createGzip as pc}from"zlib";import Ht from"process";import it from"process";import{Buffer as et}from"buffer";import{createCipheriv as Hd,createDecipheriv as Yd,randomBytes as gs}from"crypto";import{closeSync as ps,createReadStream as yc,createWriteStream as Vd,existsSync as ci,fsyncSync as wc,openSync as vc,writeFileSync as zd}from"fs";import{access as Xd,constants as bc,mkdir as Jd,readdir as li,rename as Cc,stat as Yt,unlink as fi,writeFile as ys}from"fs/promises";import{isAbsolute as qd,join as Vt,resolve as Gd}from"path";import _ from"process";import{pipeline as Qd}from"stream/promises";import{createGzip as Sc}from"zlib";import zt from"process";import nt from"process";import ui from"process";import{existsSync as hi}from"fs";import{resolve as ws}from"path";import{existsSync as Zd}from"fs";import{existsSync as em,readdirSync as tm}from"fs";import{extname as vs,resolve as Ec}from"path";import rm from"process";import{join as im,relative as nm,resolve as xc}from"path";import Oi from"process";import{Buffer as tt}from"buffer";import{createCipheriv as sm,createDecipheriv as om,randomBytes as bs}from"crypto";import{closeSync as Cs,createReadStream as $c,createWriteStream as am,existsSync as di,fsyncSync as Tc,openSync as Pc,writeFileSync as cm}from"fs";import{access as lm,constants as Ac,mkdir as fm,readdir as mi,rename as Rc,stat as Xt,unlink as gi,writeFile as Ss}from"fs/promises";import{isAbsolute as um,join as Jt,resolve as hm}from"path";import j from"process";import{pipeline as dm}from"stream/promises";import{createGzip as kc}from"zlib";import qt from"process";import st from"process";import pi from"process";import{existsSync as yi}from"fs";import{resolve as Es}from"path";import{existsSync as mm}from"fs";import{exec as Lg}from"node:child_process";import Ys from"node:fs";import Mg from"node:os";import _e from"node:path";import Vl from"node:process";import{promisify as Ig}from"node:util";import er from"node:crypto";import ot from"node:fs";import Xs from"node:path";import ap from"node:crypto";import cp from"node:fs";import lp from"node:tls";import{execSync as hp}from"node:child_process";import Hi from"node:os";var dd=hd(import.meta.url),Xc=30000;async function bi(e,t={},r=30000){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){if(i&&typeof i==="object"&&i.name==="TimeoutError"){let n=Error(`ACME HTTP request to ${e} timed out after ${r}ms`);throw n.name="AcmeRequestTimeoutError",n}throw i}}async function Jc(e,t,r={}){let i=r.timeoutMs??120000,n=r.intervalMs??3000,s=e.split(".").slice(-2).join("."),o;try{let l=new as,f=await l.resolveNs(s),u=(await Promise.all(f.map((h)=>l.resolve4(h).catch(()=>[])))).flat();if(u.length>0)o=new as,o.setServers(u)}catch{}let a=Date.now()+i,c=o??new as;for(;;){try{if((await c.resolveTxt(e)).some((l)=>l.join("")===t))return!0}catch{}if(Date.now()>=a)return!1;await new Promise((l)=>setTimeout(l,n))}}class Pr{tokens=new Map;add(e,t){this.tokens.set(e,t)}get(e){return this.tokens.get(e)}remove(e){this.tokens.delete(e)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(e){let t=e.indexOf(Pr.PATH_PREFIX);if(t===-1)return;let r=e.slice(t+Pr.PATH_PREFIX.length);return this.get(r)}}var Yi=new Pr;function Ci(e){return(typeof e==="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")}function Rs(e){return Buffer.from(e,"base64url")}function qc(e){let t=e.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 Gc(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}","y":"${e.y}"}`;return md("sha256").update(t).digest("base64url")}function Qc(e){let{protectedHeader:t,payload:r,privateKey:i}=e,n=Ci(JSON.stringify(t)),s=r===""?"":Ci(JSON.stringify(r)),o=`${n}.${s}`,a=gd("sha256",Buffer.from(o),{key:i,dsaEncoding:"ieee-p1363"});return{protected:n,payload:s,signature:Ci(a)}}var Zc="https://acme-staging-v02.api.letsencrypt.org/directory",el="https://acme-v02.api.letsencrypt.org/directory";class Pi extends Error{problem;httpStatus;constructor(e,t,r){super(e);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class Ai{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(e){this.directoryUrl=e.directoryUrl,this.accountKey=e.accountKey,this.jwk=qc(e.accountPublicKey),this.thumbprint=Gc(this.jwk),this.requestTimeoutMs=e.requestTimeoutMs??Xc}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let e=await bi(this.directoryUrl,{},this.requestTimeoutMs);if(!e.ok)throw Error(`Failed to fetch ACME directory: HTTP ${e.status}`);return this.directoryCache=await e.json(),this.directoryCache}async newNonce(){let e=await this.directory(),t=(await bi(e.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let e=this.nonce;return this.nonce=void 0,e}return this.newNonce()}async signedPost(e){let{url:t,payload:r,useJwk:i}=e,n={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(i)n.jwk=this.jwk;else n.kid=this.requireKid();let s=Qc({protectedHeader:n,payload:r,privateKey:this.accountKey}),o=await bi(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(s)},this.requestTimeoutMs),a=o.headers.get("replay-nonce");if(a)this.nonce=a;let c=o.headers.get("content-type")??"",l;if(c.includes("application/pem-certificate-chain")||c.startsWith("text/"))l=await o.text();else{let f=await o.text();l=f?JSON.parse(f):{}}if(o.status>=400){let f=l??{};throw new Pi(`ACME request to ${t} failed (HTTP ${o.status}): ${f.type??""} ${f.detail??""}`.trim(),f,o.status)}return{status:o.status,headers:o.headers,body:l,location:o.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(e={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(e.email)r.contact=[`mailto:${e.email}`];let i=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!i.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=i.location,this.accountKid}async newOrder(e){let t=await this.directory(),r={identifiers:e.map((n)=>({type:"dns",value:n}))},i=await this.signedPost({url:t.newOrder,payload:r});if(!i.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:i.body,orderUrl:i.location}}async getAuthorization(e){return(await this.signedPost({url:e,payload:""})).body}keyAuthorization(e){return`${e}.${this.thumbprint}`}dns01TxtValue(e){return pd("sha256").update(this.keyAuthorization(e)).digest("base64url")}async notifyChallengeReady(e){await this.signedPost({url:e,payload:{}})}async pollAuthorization(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getAuthorization(e);if(s.status==="valid")return;if(s.status==="invalid"){let o=s.challenges.find((a)=>a.status==="invalid");throw new Pi(`Authorization for ${s.identifier.value} became invalid: ${o?.error?.detail??"unknown reason"}`,o?.error??{},0)}await ic(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for authorization ${e} to become valid`)}async finalizeOrder(e,t){return(await this.signedPost({url:e,payload:{csr:t}})).body}async getOrder(e){return(await this.signedPost({url:e,payload:""})).body}async pollOrder(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getOrder(e);if(s.status==="valid"){if(!s.certificate)throw Error("ACME order is valid but has no certificate URL");return s.certificate}if(s.status==="invalid")throw Error(`ACME order ${e} became invalid`);await ic(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for order ${e} to become valid`)}async downloadCertificate(e){let t=await this.signedPost({url:e,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(e,t){let r=e.challenges.find((i)=>i.type===t);if(!r)throw Error(`No ${t} challenge available for ${e.identifier.value}`);return r}}function tl(e){let t=e.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${e.trim()}
|
|
2
|
-
`,chainPem:""};let i=`${r.trim()}
|
|
3
|
-
`,n=t.slice(1).map((s)=>s.trim()).join(`
|
|
4
|
-
`);return{certPem:i,chainPem:n?`${n}
|
|
5
|
-
`:""}}function rl(e){return`_acme-challenge.${e.startsWith("*.")?e.slice(2):e}`}function ic(e){return new Promise((t)=>setTimeout(t,e))}function wd(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function St(e,t){return Buffer.concat([Buffer.from([e]),wd(t.length),t])}function il(e){let t;if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=[],i=e;while(i>0)r.unshift(i&255),i>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=e.length===0?Buffer.from([0]):e,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return St(2,t)}function kt(e){let t=e.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${e}`);let r=[40*t[0]+t[1]];for(let i=2;i<t.length;i++){let n=t[i],s=[n&127];n=Math.floor(n/128);while(n>0)s.unshift(n&127|128),n=Math.floor(n/128);r.push(...s)}return St(6,Buffer.from(r))}function Ne(...e){return St(48,Buffer.concat(e))}function ks(...e){return St(49,Buffer.concat(e))}function Ns(e){return St(3,Buffer.concat([Buffer.from([0]),e]))}function nl(e){return St(4,e)}function sl(e){return St(12,Buffer.from(e,"utf8"))}function Os(e,t,r){let i=128|(r?32:0)|e;return St(i,t)}var vd="1.2.840.10045.2.1",bd="1.2.840.10045.3.1.7",Cd="1.2.840.10045.4.3.2",Sd="2.5.4.3",Ed="1.2.840.113549.1.9.14",xd="2.5.29.17";function $d(e){let t=e.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Rs(t.x),i=Rs(t.y);if(r.length!==32||i.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${i.length}`);return Buffer.concat([Buffer.from([4]),r,i])}function ol(e){let{domains:t,publicKey:r,privateKey:i}=e;if(t.length===0)throw Error("At least one domain is required to build a CSR");let n=Ne(ks(Ne(kt(Sd),sl(t[0])))),s=Ne(Ne(kt(vd),kt(bd)),Ns($d(r))),o=t.map((g)=>Os(2,Buffer.from(g,"ascii"),!1)),a=Ne(...o),c=Ne(kt(xd),nl(a)),l=Ne(c),f=Ne(kt(Ed),ks(l)),u=Os(0,f,!0),h=Ne(il(0),n,s,u),d=yd("sha256",h,i),y=Ne(kt(Cd));return Ne(h,y,Ns(d))}function al(e){return ol(e).toString("base64url")}function Pd(e){if(e){let{createPrivateKey:n,createPublicKey:s}=dd("node:crypto"),o=n(e),a=s(o.export({format:"pem",type:"pkcs8"}));return{privateKey:o,publicKey:a,pem:e}}let{privateKey:t,publicKey:r}=cl("ec",{namedCurve:"P-256"}),i=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:i}}async function Js(e){let{domains:t,method:r}=e;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!e.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((u)=>u.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let i=e.directoryUrl??(e.staging===!1?el:Zc),n=Pd(e.accountKeyPem),s=new Ai({directoryUrl:i,accountKey:n.privateKey,accountPublicKey:n.publicKey,requestTimeoutMs:e.requestTimeoutMs});await s.newAccount({email:e.email});let{order:o,orderUrl:a}=await s.newOrder(t),c=e.http01Store??Yi,l=[],f=[];try{for(let T of o.authorizations){let N=await s.getAuthorization(T);if(N.status==="valid")continue;let P=Ai.selectChallenge(N,r);if(r==="dns-01"){let Z=rl(N.identifier.value),ee=s.dns01TxtValue(P.token);await e.dnsProvider.setTxt(Z,ee),l.push({name:Z,value:ee}),await Jc(Z,ee,{timeoutMs:e.dnsPropagationTimeoutMs??120000})}else c.add(P.token,s.keyAuthorization(P.token)),f.push(P.token);await s.notifyChallengeReady(P.url),await s.pollAuthorization(T,{timeoutMs:e.timeoutMs})}let{privateKey:u,publicKey:h}=cl("ec",{namedCurve:"P-256"}),d=al({domains:t,publicKey:h,privateKey:u});await s.finalizeOrder(o.finalize,d);let y=await s.pollOrder(a,{timeoutMs:e.timeoutMs}),g=await s.downloadCertificate(y),{certPem:p,chainPem:w}=tl(g),v=w?`${p}${w}`:p,E=u.export({format:"pem",type:"pkcs8"}).toString(),R=new Date(new Td(p).validTo);return{certPem:p,keyPem:E,chainPem:w,fullChainPem:v,accountKeyPem:n.pem,notAfter:R}}finally{for(let{name:u,value:h}of l)await e.dnsProvider?.removeTxt(u,h).catch(()=>{});for(let u of f)c.remove(u)}}class ul{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!nc(e))return!0;return sc(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=nc(r)?sc(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class hl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Di=new ul,qs=new hl,gm=Object.defineProperty,pm=(e)=>e;function ym(e,t){this[e]=pm.bind(null,t)}var wm=(e,t)=>{for(var r in t)gm(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ym.bind(t,r)})},vm=(e,t)=>()=>(e&&(t=e(e=0)),t),dl={};wm(dl,{withErrorRecovery:()=>pl,tryLoadConfig:()=>Wm,loadConfigWithResult:()=>jm,loadConfig:()=>Cl,isRetryableError:()=>Fm,isConfigNotFoundError:()=>Dm,isBunfigError:()=>yl,globalPerformanceMonitor:()=>Or,globalCache:()=>Qt,getEnvOrDefault:()=>Bm,generateConfigTypes:()=>Km,defaultGeneratedDir:()=>Rl,defaultConfigDir:()=>Al,deepMergeWithArrayStrategy:()=>to,deepMerge:()=>wl,createLibraryConfig:()=>Hm,config:()=>Um,bunfigPlugin:()=>Ym,applyEnvVarsToConfig:()=>$r,TypeGenerationError:()=>Us,SchemaValidationError:()=>kr,PluginError:()=>Ks,PerformanceMonitor:()=>Qs,FileSystemError:()=>js,ErrorFactory:()=>Ct,EnvVarError:()=>_i,EnvProcessor:()=>zi,ConfigValidator:()=>ro,ConfigValidationError:()=>Is,ConfigNotFoundError:()=>Ii,ConfigMergeError:()=>_s,ConfigLoader:()=>io,ConfigLoadError:()=>Rr,ConfigFileLoader:()=>Xi,ConfigCache:()=>Gs,CacheUtils:()=>El,BunfigError:()=>Te,BrowserConfigError:()=>Ws,ArrayMergeStrategies:()=>Tl});class Gs{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!oc(e))return!0;return ac(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=oc(r)?ac(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Qs{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function bm(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Cm(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Sm(e){return e.getStats().size*2}function Zs(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(V(e)&&"arr"in e&&Array.isArray(e.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&V(t[0])&&V(e[0])){let i=[...t];for(let n of e)if(V(n)&&"name"in n){if(!i.find((s)=>V(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(V(n)&&"path"in n){if(!i.find((s)=>V(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>Fi(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!V(t)||!V(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(V(n)&&V(r[i]))r[i]=Zs(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&V(n[0])&&V(r[i][0])){let s=[...n];for(let o of r[i])if(V(o)&&"name"in o){if(!s.find((a)=>V(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(V(o)&&"path"in o){if(!s.find((a)=>V(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>Fi(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Fi(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Fi(e[r],t[r]))return!1;return!0}if(V(e)&&V(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Fi(e[n],t[n]))return!1}return!0}return!1}function V(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Em(e,t){if(!fl(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Zs(t,i)}catch{return null}}catch{return null}}async function xm({name:e="",cwd:t,defaultConfig:r}){let i=t||Fs.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of n){let c=Ni(i,`${o}${a}`),l=await Em(c,r);if(l!==null)return l}try{let o=Ni(i,"package.json");if(fl(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Zs(r,a)}catch{}}}catch{}return r}function $m(e,t={}){let r=ki.cwd();while(r.includes("storage"))r=fc(r,"..");let i=fc(r,e||"");if(t?.relative)return Ld(ki.cwd(),i);return i}async function Tm(){try{let e=await xm({name:"clarity",defaultConfig:Ei,cwd:ki.cwd(),endpoint:"",headers:{}});return{...Ei,...e}}catch{return Ei}}function J(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Pm(){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 e=it.type;if(e==="renderer"||e==="worker")return!1;return!!(it.versions&&(it.versions.node||it.versions.bun))}return!1}class ml{async format(e){let t=await Pm(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Ht.pid,hostname:t(),environment:Ht.env.NODE_ENV||"development",platform:Ht.platform,version:Ht.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ht.env.NODE_ENV||Ht.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bi{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(e,t={}){this.name=e,this.config={...Ls},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ml,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??le.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...xi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...xi};return{...xi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ls.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Ud(this.config.logDirectory,mc.F_OK|mc.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Wd(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:vt.from(e);try{if(!ds(this.currentLogFile))await ms(this.currentLogFile,"",{mode:420});if(i=dc(this.currentLogFile,"a",420),jd(i,a,{flag:"a"}),hc(i),i!==void 0)hs(i),i=void 0;if((await Wt(this.currentLogFile)).size===0){if(await ms(this.currentLogFile,a,{flag:"w",mode:420}),(await Wt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let l=c;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let f=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,f);let u=o*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{hs(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-1){let l=a,f=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}n++;let c=o*2**(n-1);await new Promise((l)=>setTimeout(l,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 Kt(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 Kt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Kt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(J())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return us(16).toString("hex")}generateKey(){return us(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=us(16),i=Md("aes-256-gcm",t,r),n=vt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:vt.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=pc(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(vt.from(vt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(J())return;let e=await Wt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await oi(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Wt(r).catch(()=>null))try{if(await gc(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ai(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await ms(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Wt(r).catch(()=>null))await gc(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await oi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await ai(Kt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=uc(e),i=_d(t),n=pc();await Kd(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ds(this.currentLogFile))try{let e=dc(this.currentLogFile,"r+");hc(e),hs(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!J()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await oi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ai(Kt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?H.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=le.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${H.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!J()){let l=xl[e],f=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:H.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:H.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u),a){let h=a.split(`
|
|
6
|
-
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:H.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!J()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
7
|
-
`;if(a)c+=`${a}
|
|
8
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!J()){let r=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:H.blue("◐"),tag:r,message:`${H.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
9
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!J()){let l=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:H.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!J())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Bi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(J())throw Error("createReadStream is not supported in browser environments");if(!ds(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uc(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=vt.isBuffer(e)?e:vt.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),a=Id("aes-256-gcm",r,n);return a.setAuthTag(s),vt.concat([a.update(o),a.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J()}isServerMode(){return!J()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!J()){let s=e.split(`
|
|
10
|
-
`),o=Math.max(...s.map((f)=>f.length))+2,a=`┌${"─".repeat(o)}┐`,c=`└${"─".repeat(o)}┘`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`│ ${f}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:H.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(a)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(c),showTimestamp:!1}))}else if(!J())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(J())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${H.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();le.stdin.removeListener("data",r);try{if(typeof le.stdin.setRawMode==="function")le.stdin.setRawMode(!1)}catch{}le.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof le.stdin.setRawMode==="function")le.stdin.setRawMode(!0)}catch{}le.stdin.resume(),le.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let n=/%([sdijfo%])/g,s=0;if(r=e.replace(n,(o,a)=>{if(a==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!J()){let n=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",s=H.blue("◐");console.error(`${s} ${n} ${H.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||J()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(i,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),n!==void 0)this.activeProgressBar.message=n;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J())return;le.stdout.write(`${"\r".padEnd(le.stdout.columns||80)}\r`),this.log(n,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||J()||!le.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=H.green("━".repeat(i)),o=H.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?H.green("✓"):H.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=le.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,le.stdout.write(e.lastRenderedLine),t)le.stdout.write(`
|
|
13
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||J()||!le.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(J()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await oi(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Kt(this.config.logDirectory,i);if(e.before)try{if((await Wt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await ai(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Si(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&U(t[0])&&"id"in t[0]&&t[0].id===3&&U(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(U(t)&&U(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(U(e)&&"arr"in e&&Array.isArray(e.arr)&&U(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&U(t[0])&&U(e[0])){let i=[...t];for(let n of e)if(U(n)&&"name"in n){if(!i.find((s)=>U(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(U(n)&&"path"in n){if(!i.find((s)=>U(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>Li(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!U(t)||!U(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(U(n)&&U(r[i]))r[i]=Si(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&U(n[0])&&U(r[i][0])){let s=[...n];for(let o of r[i])if(U(o)&&"name"in o){if(!s.find((a)=>U(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(U(o)&&"path"in o){if(!s.find((a)=>U(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>Li(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function eo(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Si(e,t);if(Array.isArray(e))return r==="replace"?t:Si(e,t);if(!U(t)||!U(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=Si(o,s);else if(U(s)&&U(o))i[n]=eo(o,s,r);else i[n]=s}return i}function Li(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Li(e[r],t[r]))return!1;return!0}if(U(e)&&U(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Li(e[n],t[n]))return!1}return!0}return!1}function U(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function wi(e,t,r="replace"){if(!ll(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return eo(t,n,r)}catch{return null}}catch{return null}}function Am(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${u.map(h).join("_")}`,y=`${i}_${u.map((g)=>g.toUpperCase()).join("_")}`;if(r)ue.info(`Checking environment variable ${d} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))c[l]=s(f,u);else{let g=Ar.env[d]||Ar.env[y];if(g!==void 0){if(r)ue.info(`Using environment variable ${g?d:y} for config ${e}.${u.join(".")}`);if(typeof f==="number")c[l]=Number(g);else if(typeof f==="boolean")c[l]=g.toLowerCase()==="true";else if(Array.isArray(f))try{let p=JSON.parse(g);if(Array.isArray(p))c[l]=p;else c[l]=g.split(",").map((w)=>w.trim())}catch{c[l]=g.split(",").map((p)=>p.trim())}else c[l]=g}}}return c}return s(n)}async function Rm({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Am(e,n,s):n,l=r||Ar.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)ue.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,pe(l,"config"),pe(l,".config"),i?pe(l,i):void 0].filter(Boolean)));for(let p of g){if(s)ue.info(`Searching for configuration in: ${p}`);let w=[pe(l,"config"),pe(l,".config")].concat(i?[pe(l,i)]:[]).includes(p)?[...u,...h,...d,...y]:[...h,...u,...y,...d];for(let v of w)for(let E of f){let R=pe(p,`${v}${E}`),T=await wi(R,c,a);if(T!==null){if(s)ue.success(`Configuration loaded from: ${R}`);return T}}}if(e){let p=pe(fs(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)ue.info(`Checking user config directory: ${p}`);for(let v of w)for(let E of f){let R=pe(p,`${v}${E}`),T=await wi(R,c,a);if(T!==null){if(s)ue.success(`Configuration loaded from user config directory: ${R}`);return T}}}if(e){let p=pe(fs(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)ue.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let E of f){let R=pe(p,`${v}${E}`),T=await wi(R,c,a);if(T!==null){if(s)ue.success(`Configuration loaded from user config directory dotfile: ${R}`);return T}}}if(e){let p=fs(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)ue.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let E of f){let R=pe(p,`${v}${E}`),T=await wi(R,c,a);if(T!==null){if(s)ue.success(`Configuration loaded from user home directory: ${R}`);return T}}}try{let p=pe(l,"package.json");if(ll(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)ue.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)ue.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return eo(c,v,a)}catch(E){if(s)ue.warn("Failed to merge package.json config:",E)}}}catch(p){if(s)ue.warn("Failed to load package.json:",p)}if(s)ue.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function km(e,t={}){let r=Ri.cwd();while(r.includes("storage"))r=lc(r,"..");let i=lc(r,e||"");if(t?.relative)return Fd(Ri.cwd(),i);return i}async function Nm(){try{let e=await Rm({name:"clarity",alias:"logging",defaultConfig:$i,cwd:Ri.cwd()});return{...$i,...e||{}}}catch{return $i}}function te(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Om(){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 e=nt.type;if(e==="renderer"||e==="worker")return!1;return!!(nt.versions&&(nt.versions.node||nt.versions.bun))}return!1}class gl{async format(e){let t=await Om(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:zt.pid,hostname:t(),environment:zt.env.NODE_ENV||"development",platform:zt.platform,version:zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:zt.env.NODE_ENV||zt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mi{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(e,t={}){this.name=e,this.config={...Ms},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new gl,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ti,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ti};return{...Ti,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ms.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!te()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Xd(this.config.logDirectory,bc.F_OK|bc.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Jd(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:et.from(e);try{if(!ci(this.currentLogFile))await ys(this.currentLogFile,"",{mode:420});if(i=vc(this.currentLogFile,"a",420),zd(i,a,{flag:"a"}),wc(i),i!==void 0)ps(i),i=void 0;if((await Yt(this.currentLogFile)).size===0){if(await ys(this.currentLogFile,a,{flag:"w",mode:420}),(await Yt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let l=c;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let f=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,f);let u=o*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{ps(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-1){let l=a,f=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}n++;let c=o*2**(n-1);await new Promise((l)=>setTimeout(l,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(te())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return gs(16).toString("hex")}generateKey(){return gs(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=gs(16),i=Hd("aes-256-gcm",t,r),n=et.isBuffer(e)?e:et.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=et.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Sc(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(et.from(et.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(te())return;if(!this.shouldWriteToFile())return;let e=await Yt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await li(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Yt(r).catch(()=>null))try{if(await Cc(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await fi(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await ys(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Yt(r).catch(()=>null))await Cc(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await li(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await fi(Vt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=yc(e),i=Vd(t),n=Sc();await Qd(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ci(this.currentLogFile))try{let e=vc(this.currentLogFile,"r+");wc(e),ps(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!te()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await li(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await fi(Vt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?B.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||te())return!1;let e=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=_.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${B.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=B.underline(B.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>B.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>B.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>B.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>B.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>B.strikethrough(i)),t}supportsHyperlinks(){if(te())return!1;let e=_.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(qd(t)||t.startsWith("./")||t.startsWith("../"))t=Gd(t);else return null;return ci(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":$l[e],h=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:B.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:B.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let y=a.split(`
|
|
14
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:B.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!te()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
15
|
-
`;if(a)f+=`${a}
|
|
16
|
-
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!te()&&_.stdout.isTTY)_.stdout.write(`
|
|
17
|
-
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":B.blue("◐"),tag:r,message:`${B.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
18
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":B.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!te())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Mi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(te())throw Error("createReadStream is not supported in browser environments");if(!ci(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yc(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=et.isBuffer(e)?e:et.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=Yd("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=et.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return te()}isServerMode(){return!te()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
19
|
-
`),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:B.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(f),showTimestamp:!1}))}else if(!te())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(te())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${B.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,l)=>{if(l==="%")return"%";if(a>=t.length)return c;let f=t[a++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${B.blue("◐")} `;console.error(`${a}${o} ${B.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=B.green("━".repeat(i)),o=B.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?B.green("✓"):B.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=_.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,_.stdout.write(e.lastRenderedLine),t)_.stdout.write(`
|
|
22
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||te()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(te()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await li(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Vt(this.config.logDirectory,i);if(e.before)try{if((await Yt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await fi(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function pl(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function yl(e){return e instanceof Te}function Dm(e){return e instanceof Ii}function Fm(e){if(yl(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class zi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Or.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=ui.env[c]||(l?ui.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=ui.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof _i)throw u;throw Ct.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Ct.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(ui.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
23
|
-
|
|
24
|
-
`;for(let i of e)r+=`${i.key}
|
|
25
|
-
`,r+=` Type: ${i.type}
|
|
26
|
-
`,r+=` Description: ${i.description}
|
|
27
|
-
`,r+=` Example: ${i.example}
|
|
28
|
-
|
|
29
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
30
|
-
|
|
31
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
32
|
-
`,r+=`|----------|------|-------------|----------|
|
|
33
|
-
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
34
|
-
`;return r}}function Bm(e,t){let r=Sl("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function wl(e,t,r={}){return vl(e,t,r,new WeakMap)}function vl(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return bl(e,t,n,i);if(!De(t)||!De(e))return t;return _m(e,t,r,i)}function bl(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Lm(e,t);case"smart":return Mm(e,t,i);default:return t}return t}function Lm(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Bs(n,i)))r.push(i);return r}function Mm(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(De(t[0])&&De(e[0]))return Im(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Im(e,t,r){let i=[...t];for(let n of e){if(!De(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((c)=>De(c)&&(a in c)&&c[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function _m(e,t,r,i){let n=t;if(De(n)&&i.has(n))return i.get(n);let s={...e};if(De(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(De(a)&&De(c))s[o]=vl(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=bl(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function to(e,t,r="replace"){return wl(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Bs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Bs(e[r],t[r]))return!1;return!0}if(De(e)&&De(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Bs(e[n],t[n]))return!1}return!0}return!1}function De(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Xi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=Qt.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!hi(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new Rr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Rr(e,Error("Configuration must export a valid object"),"unknown");let y={config:to(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Qt.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Ct.configLoad(e,l):Ct.configLoad(e,Error(String(l)))}};if(o)return Or.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(ws(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return pl(async()=>hi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!hi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=ws(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=ws(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){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(e))}async validateConfigFile(e){let t=[];try{if(!hi(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class ro{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await Or.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Zd(t))throw new kr(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new kr(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Pl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class io{fileLoader=new Xi;envProcessor=new zi;validator=new ro;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)je.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw je.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Nt.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let y=await this.loadHomeConfiguration(i,n,a,l,f,c);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(ye(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw Ct.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?$r(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)je.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)je.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?$r(e,r,n):r,a=[ye(Ut(),".config",e),ye(Ut(),".config"),Ut()];for(let c of a){if(n)je.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)je.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?$r(e,i,s):i;try{let c=ye(r,"package.json");if(!Ds(c))return null;let l=await import(c),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)je.success(`Configuration loaded from package.json: ${u}`);return{config:to(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)je.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:$r(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw Ct.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Qt.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Qt.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,ye(e,"config"),ye(e,".config"),t?ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(ye(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[ye(Ut(),".config",e),ye(Ut(),".config"),Ut()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Nc(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function jm(e){return at.loadConfig({...e,__strictErrorHandling:!0})}async function Cl(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await at.loadConfig(e);else i=await at.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)je.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await at.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Um(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await at.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Nc(r)))return(await at.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await at.loadConfig({...e,cwd:e.cwd||Nt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Nc(t)))return(await at.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Wm(e,t,r="replace"){let i=new Xi;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function $r(e,t,r=!1){let i=new zi,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Nt.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}function Km(e){let t=ye(Nt.cwd(),e.configDir),r=ye(Nt.cwd(),e.generatedDir),i=ye(r,"config-types.ts");if(!Ds(cc(i)))kd(cc(i),{recursive:!0,mode:511});let n=Ds(t)?Nd(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${wg}
|
|
35
|
-
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
36
|
-
`;Od(i,s,{mode:438})}function Hm(e){let t=null,r=null,i=()=>{if(!r)r=Cl(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)je.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let a=n[o];return i(),a},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,a){if(!t)t={...n};return t[o]=a,!0}})}function Ym(e){let t=Ec(rm.cwd(),e?.configDir||"./config");function r(){if(!em(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=tm(t).filter((c)=>n.has(vs(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:l}of o){let f=vs(l).toLowerCase(),u=a.get(c);if(!u){a.set(c,l);continue}let h=vs(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))a.set(c,l)}return Array.from(a.entries()).map(([c,l])=>({base:c,file:l})).sort((c,l)=>c.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",a=n.length?`{
|
|
37
|
-
${n.map((c)=>{let l=Ec(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${l}').default`}).join(`,
|
|
38
|
-
`)}
|
|
39
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
40
|
-
export type ConfigByName = ${a}
|
|
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(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var Sl,Qt,Or,El,Vm,zm,Oc,Ei,Ls,fe,H,Xm,Dc,Jm,Fc,qm,Gm,xs,Qm,Bc,Lc,$s,Zm,eg,tg,rg,xi,xl,ig,ue,ng,sg,Mc,$i,Ms,re,B,og,Ic,ag,_c,cg,lg,Ts,fg,jc,Uc,ug,Ps,hg,dg,mg,gg,pg,Ti,$l,yg,wg="0.15.6",Te,Ii,Rr,Is,_s,_i,js,Us,kr,Ws,Ks,Ct,Tl,Pl,je,at,Al,Rl,vg=vm(async()=>{Sl=import.meta.require,Qt=new Gs,Or=new Qs,El={createKey:bm,isEquivalent:Cm,estimateMemoryUsage:Sm},Vm=Ni(Fs.cwd(),"config"),zm=Ni(Fs.cwd(),"src/generated"),Oc=ki.env.CLARITY_LOG_DIR||Bd($m(),"logs"),Ei={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Oc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ls=await Tm(),fe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},H=fe,Xm=fe.red,Dc=fe.green,Jm=fe.yellow,Fc=fe.blue,qm=fe.magenta,Gm=fe.cyan,xs=fe.white,Qm=fe.gray,Bc=fe.bgRed,Lc=fe.bgYellow,$s=fe.bold,Zm=fe.dim,eg=fe.italic,tg=fe.underline,rg=fe.reset,xi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xl={debug:"\uD83D\uDD0D",info:Fc("ℹ"),success:Dc("✓"),warning:Lc(xs($s(" WARN "))),error:Bc(xs($s(" ERROR ")))},ig=new Bi("stacks"),ue=new Bi("bunfig",{showTags:!0}),ng=pe(Ar.cwd(),"config"),sg=pe(Ar.cwd(),"src/generated"),Mc=Ri.env.CLARITY_LOG_DIR||Dd(km(),"logs"),$i={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ms=await Nm(),re={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},B=re,og=re.red,Ic=re.green,ag=re.yellow,_c=re.blue,cg=re.magenta,lg=re.cyan,Ts=re.white,fg=re.gray,jc=re.bgRed,Uc=re.bgYellow,ug=re.bgGray,Ps=re.bold,hg=re.dim,dg=re.italic,mg=re.underline,gg=re.strikethrough,pg=re.reset,Ti={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$l={debug:"\uD83D\uDD0D",info:_c("ℹ"),success:Ic("✓"),warning:Uc(Ts(Ps(" WARN "))),error:jc(Ts(Ps(" ERROR ")))},yg=new Mi("stacks"),Te=class extends Error{timestamp;context;constructor(e,t={}){super(e);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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Ii=class extends Te{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Rr=class extends Te{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Is=class extends Te{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},_s=class extends Te{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},_i=class extends Te{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},js=class extends Te{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Us=class extends Te{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},kr=class extends Te{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ws=class extends Te{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Ks=class extends Te{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ct={configNotFound(e,t,r){return new Ii(e,t,r)},configLoad(e,t,r){return new Rr(e,t,r)},configValidation(e,t,r){return new Is(e,t,r)},configMerge(e,t,r,i){return new _s(e,t,r,i)},envVar(e,t,r,i){return new _i(e,t,r,i)},fileSystem(e,t,r){return new js(e,t,r)},typeGeneration(e,t,r){return new Us(e,t,r)},schemaValidation(e,t,r){return new kr(e,t,r)},browserConfig(e,t,r,i){return new Ws(e,t,r,i)},plugin(e,t,r){return new Ks(e,t,r)}},Tl={replace:"replace",concat:"concat",smart:"smart"},Pl=/^https?:\/\//,je=new Mi("bunfig",{showTags:!0}),at=new io,Al=ye(Nt.cwd(),"config"),Rl=ye(Nt.cwd(),"src/generated")});function bg(e,t={}){let r=Oi.cwd();while(r.includes("storage"))r=xc(r,"..");let i=xc(r,e||"");if(t?.relative)return nm(Oi.cwd(),i);return i}var Cg=Oi.env.CLARITY_LOG_DIR||im(bg(),"logs"),kl={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ji={...kl},$S=(async()=>{try{let{loadConfig:e}=await vg().then(()=>dl),t=await e({name:"clarity",alias:"logging",defaultConfig:kl,cwd:Oi.cwd()});if(t)Object.assign(ji,t)}catch{}return ji})();function ie(){if(st.env.NODE_ENV==="test"||st.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Sg(){if(st.env.NODE_ENV==="test"||st.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof st<"u"){let e=st.type;if(e==="renderer"||e==="worker")return!1;return!!(st.versions&&(st.versions.node||st.versions.bun))}return!1}class Nl{async format(e){let t=await Sg(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:qt.pid,hostname:t(),environment:qt.env.NODE_ENV||"development",platform:qt.platform,version:qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qt.env.NODE_ENV||qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ae={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},M=ae,TS=ae.red,Eg=ae.green,PS=ae.yellow,xg=ae.blue,AS=ae.magenta,RS=ae.cyan,Wc=ae.white,kS=ae.gray,$g=ae.bgRed,Tg=ae.bgYellow,NS=ae.bgGray,Kc=ae.bold,OS=ae.dim,DS=ae.italic,FS=ae.underline,BS=ae.strikethrough,LS=ae.reset,As={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Pg={debug:"\uD83D\uDD0D",info:xg("ℹ"),success:Eg("✓"),warning:Tg(Wc(Kc(" WARN "))),error:$g(Wc(Kc(" ERROR ")))};class Ji{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(e,t={}){this.name=e,this.config={...ji},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Nl,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??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...As,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...As};return{...As,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ji.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ie()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await lm(this.config.logDirectory,Ac.F_OK|Ac.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await fm(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:tt.from(e);try{if(!di(this.currentLogFile))await Ss(this.currentLogFile,"",{mode:420});if(i=Pc(this.currentLogFile,"a",420),cm(i,a,{flag:"a"}),Tc(i),i!==void 0)Cs(i),i=void 0;if((await Xt(this.currentLogFile)).size===0){if(await Ss(this.currentLogFile,a,{flag:"w",mode:420}),(await Xt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let l=c;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let f=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,f);let u=o*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{Cs(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-1){let l=a,f=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}n++;let c=o*2**(n-1);await new Promise((l)=>setTimeout(l,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 Jt(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 Jt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Jt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ie())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return bs(16).toString("hex")}generateKey(){return bs(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bs(16),i=sm("aes-256-gcm",t,r),n=tt.isBuffer(e)?e:tt.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=tt.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=kc(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(tt.from(tt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ie())return;if(!this.shouldWriteToFile())return;let e=await Xt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await mi(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Xt(r).catch(()=>null))try{if(await Rc(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await gi(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Ss(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Xt(r).catch(()=>null))await Rc(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await mi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await gi(Jt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=$c(e),i=am(t),n=kc();await dm(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),di(this.currentLogFile))try{let e=Pc(this.currentLogFile,"r+");Tc(e),Cs(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ie()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await mi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await gi(Jt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?M.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ie())return!1;let e=typeof j.env.NO_COLOR<"u",t=j.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=j.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${M.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=M.underline(M.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>M.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>M.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>M.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>M.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>M.strikethrough(i)),t}supportsHyperlinks(){if(ie())return!1;let e=j.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=j.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(um(t)||t.startsWith("./")||t.startsWith("../"))t=hm(t);else return null;return di(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Pg[e],h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:M.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:M.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let y=a.split(`
|
|
44
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:M.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!ie()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
45
|
-
`;if(a)f+=`${a}
|
|
46
|
-
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ie()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!ie()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!ie()&&j.stdout.isTTY)j.stdout.write(`
|
|
47
|
-
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!ie()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:r,message:`${M.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
48
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":M.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ie())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ji(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ie())throw Error("createReadStream is not supported in browser environments");if(!di(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $c(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=tt.isBuffer(e)?e:tt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=om("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=tt.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ie()}isServerMode(){return!ie()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
49
|
-
`),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:M.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(f),showTimestamp:!1}))}else if(!ie())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(ie())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${M.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,l)=>{if(l==="%")return"%";if(a>=t.length)return c;let f=t[a++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${a}${o} ${M.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=M.green("━".repeat(i)),o=M.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?M.green("✓"):M.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=j.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,j.stdout.write(e.lastRenderedLine),t)j.stdout.write(`
|
|
52
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ie()||!j.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ie()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await mi(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Jt(this.config.logDirectory,i);if(e.before)try{if((await Xt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await gi(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var MS=new Ji("stacks");class Ke extends Error{timestamp;context;constructor(e,t={}){super(e);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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class Ol extends Ke{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Ui extends Ke{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Dl extends Ke{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Fl extends Ke{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class no extends Ke{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}}class Bl extends Ke{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ll extends Ke{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wi extends Ke{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Ml extends Ke{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}}class Il extends Ke{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Zt={configNotFound(e,t,r){return new Ol(e,t,r)},configLoad(e,t,r){return new Ui(e,t,r)},configValidation(e,t,r){return new Dl(e,t,r)},configMerge(e,t,r,i){return new Fl(e,t,r,i)},envVar(e,t,r,i){return new no(e,t,r,i)},fileSystem(e,t,r){return new Bl(e,t,r)},typeGeneration(e,t,r){return new Ll(e,t,r)},schemaValidation(e,t,r){return new Wi(e,t,r)},browserConfig(e,t,r,i){return new Ml(e,t,r,i)},plugin(e,t,r){return new Il(e,t,r)}};async function Ag(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class so{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return qs.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=pi.env[c]||(l?pi.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=pi.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof no)throw u;throw Zt.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Zt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(pi.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
53
|
-
|
|
54
|
-
`;for(let i of e)r+=`${i.key}
|
|
55
|
-
`,r+=` Type: ${i.type}
|
|
56
|
-
`,r+=` Description: ${i.description}
|
|
57
|
-
`,r+=` Example: ${i.example}
|
|
58
|
-
|
|
59
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
60
|
-
|
|
61
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
62
|
-
`,r+=`|----------|------|-------------|----------|
|
|
63
|
-
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
64
|
-
`;return r}}function Rg(e,t,r={}){return _l(e,t,r,new WeakMap)}function _l(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return jl(e,t,n,i);if(!Fe(t)||!Fe(e))return t;return Dg(e,t,r,i)}function jl(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return kg(e,t);case"smart":return Ng(e,t,i);default:return t}return t}function kg(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Hs(n,i)))r.push(i);return r}function Ng(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Fe(t[0])&&Fe(e[0]))return Og(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Og(e,t,r){let i=[...t];for(let n of e){if(!Fe(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((c)=>Fe(c)&&(a in c)&&c[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function Dg(e,t,r,i){let n=t;if(Fe(n)&&i.has(n))return i.get(n);let s={...e};if(Fe(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Fe(a)&&Fe(c))s[o]=_l(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=jl(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function Ul(e,t,r="replace"){return Rg(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Hs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Hs(e[r],t[r]))return!1;return!0}if(Fe(e)&&Fe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Hs(e[n],t[n]))return!1}return!0}return!1}function Fe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Wl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=Di.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!yi(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new Ui(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Ui(e,Error("Configuration must export a valid object"),"unknown");let y={config:Ul(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Di.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Zt.configLoad(e,l):Zt.configLoad(e,Error(String(l)))}};if(o)return qs.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Es(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return Ag(async()=>yi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!yi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=Es(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=Es(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){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(e))}async validateConfigFile(e){let t=[];try{if(!yi(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var Fg=/^https?:\/\//;class Kl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await qs.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!mm(t))throw new Wi(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Wi(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Fg},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var rt=new Ji("bunfig",{showTags:!0});function Bg(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Hl{fileLoader=new Wl;envProcessor=new so;validator=new Kl;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)rt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw rt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Vi.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let y=await this.loadHomeConfiguration(i,n,a,l,f,c);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(Oe(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw Zt.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${Bg(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?vi(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)rt.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)rt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?vi(e,r,n):r,a=[Oe(jt(),".config",e),Oe(jt(),".config"),jt()];for(let c of a){if(n)rt.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)rt.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?vi(e,i,s):i;try{let c=Oe(r,"package.json");if(!Ad(c))return null;let l={};try{l=JSON.parse(Rd(c,"utf8"))}catch(h){if(s)rt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){f=l[d],u=d;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)rt.success(`Configuration loaded from package.json: ${u}`);return{config:Ul(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)rt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:vi(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw Zt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Di.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Di.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Oe(e,"config"),Oe(e,".config"),t?Oe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Oe(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Oe(jt(),".config",e),Oe(jt(),".config"),jt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}var IS=new Hl;function vi(e,t,r=!1){let i=new so,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Vi.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}var _S=Oe(Vi.cwd(),"config"),jS=Oe(Vi.cwd(),"src/generated"),Yl={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:ls.join(cs.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ls.join(cs.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ls.join(cs.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var Q=Yl,Ue={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"},Gt={info:(...e)=>console.log(...e),warn:(...e)=>console.warn(...e),success:(...e)=>console.log(...e),error:(...e)=>console.error(...e),debug:(...e)=>console.debug(...e)};function zl(e){return Ys.readFileSync(e,"utf8")}function Vs(e,t){let r=[];function i(n){let s;try{s=Ys.readdirSync(n)}catch{return}for(let o of s){let a=_e.join(n,o);try{if(Ys.statSync(a).isDirectory())i(a);else if(o===t)r.push(n)}catch{continue}}}return i(e),r}function S(e,t,r){if(r||Q.verbose)console.debug(`[tlsx:${e}] ${t}`)}var _g=Ig(Lg);function Xl(){return Vl.env.SUDO_PASSWORD}var Hc="[redacted]",jg=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Ug=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Wg(e){let t=e.toLowerCase();return jg.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Ki(e){if(Array.isArray(e))return e.map((r)=>Ki(r));if(typeof e==="string")return Ug.test(e)?Hc:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,i]of Object.entries(e)){if(Wg(r)){t[r]=Hc;continue}t[r]=Ki(i)}return t}function qi(e){return JSON.stringify(Ki(e))}function Kg(e){let t=Xl();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(e))return e;let r=t.replace(/'/g,"'\\''"),i=e.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${i}`}async function bt(e,t={}){let r=Kg(e);try{let{stdout:i,stderr:n}=await _g(r,{cwd:t.cwd||Vl.cwd(),timeout:t.timeout||30000});return{stdout:i.trim(),stderr:n.trim()}}catch(i){let n=Error(`Failed to execute command: ${e}
|
|
65
|
-
Error: ${i.message}`);throw n.stack=i.stack,n}}function Jl(e){if(e.domain)return e.domain;if(e.domains?.length)return e.domains[0];throw Error("Either domain or domains must be specified")}function oo(e){let t=_e.join(Mg.homedir(),".stacks","ssl"),r=e.basePath&&e.basePath.trim()!==""?e.basePath:Q.basePath&&Q.basePath.trim()!==""?Q.basePath:t,i=e.certPath?_e.isAbsolute(e.certPath)?e.certPath:_e.join(r,e.certPath):_e.join(r,Q.certPath),n=e.keyPath?_e.isAbsolute(e.keyPath)?e.keyPath:_e.join(r,e.keyPath):_e.join(r,Q.keyPath),s=e.caCertPath?_e.isAbsolute(e.caCertPath)?e.caCertPath:_e.join(r,e.caCertPath):_e.join(r,Q.caCertPath);return{certPath:i,keyPath:n,caCertPath:s,basePath:r}}function ql(e){let t=[],r=new Set;if(e.domain)r.add(e.domain);if(e.domains?.length)e.domains.forEach((i)=>r.add(i));for(let i of r)t.push({type:2,value:i});if(e.altNameIPs?.length)for(let i of e.altNameIPs)t.push({type:7,ip:i});if(e.altNameURIs?.length)for(let i of e.altNameURIs)t.push({type:6,value:i});if(e.subjectAltNames?.length)t.push(...e.subjectAltNames);return S(x.CERT,`Generated ${t.length} Subject Alternative Names`,e.verbose),t}function ao(e){let t=e.notBeforeDays??Ue.DEFAULT_NOT_BEFORE_DAYS,r=e.validityDays??(e.validityYears?e.validityYears*365:Ue.DEFAULT_VALIDITY_DAYS);S(x.CERT,"Calculating certificate validity dates",e.verbose);let i=new Date(Date.now()-86400*t*1000),n=new Date(i.getTime()+r*24*60*60*1000);return i.setUTCHours(0,0,0,0),n.setUTCHours(23,59,59,999),S(x.CERT,`Validity period: ${i.toISOString()} to ${n.toISOString()}`,e.verbose),{notBefore:i,notAfter:n}}var We={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},we={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 Tr(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Ae(e,t){let r=Tr(t.length);return Buffer.concat([Buffer.from([e]),r,t])}function Nr(e){let t=e.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let i=2;i<t.length;i++){let n=t[i],s=[];s.unshift(n&127),n>>=7;while(n>0)s.unshift(n&127|128),n>>=7;r.push(...s)}return Ae(We.OID,Buffer.from(r))}function zs(e){let t;if(typeof e==="bigint"){let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=e;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ae(We.INTEGER,t)}function Gl(e,t=0){return Ae(We.BIT_STRING,Buffer.concat([Buffer.from([t]),e]))}function Ql(e){return Ae(We.OCTET_STRING,e)}function Pe(...e){return Ae(We.SEQUENCE,Buffer.concat(e))}function Hg(...e){return Ae(We.SET,Buffer.concat(e))}function Yg(e){return Ae(We.PRINTABLE_STRING,Buffer.from(e,"ascii"))}function Vg(e){return Ae(We.UTF8_STRING,Buffer.from(e,"utf8"))}function zg(){return Buffer.from([We.NULL,0])}function Yc(e,t,r=!0){let i=160|e|(r?0:0),n=Tr(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function Vc(e){let t=e.getUTCFullYear();if(t>=2050){let r=e.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Ae(We.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),i=(e.getUTCMonth()+1).toString().padStart(2,"0"),n=e.getUTCDate().toString().padStart(2,"0"),s=e.getUTCHours().toString().padStart(2,"0"),o=e.getUTCMinutes().toString().padStart(2,"0"),a=e.getUTCSeconds().toString().padStart(2,"0"),c=`${r}${i}${n}${s}${o}${a}Z`;return Ae(We.UTC_TIME,Buffer.from(c,"ascii"))}}function Xg(e,t){return Pe(Vc(e),Vc(t))}function zc(e){let t=[];for(let r of e){let i;switch(r.shortName){case"CN":i=we.COMMON_NAME;break;case"C":i=we.COUNTRY;break;case"L":i=we.LOCALITY;break;case"ST":i=we.STATE;break;case"O":i=we.ORGANIZATION;break;case"OU":i=we.ORGANIZATIONAL_UNIT;break;default:continue}let n=r.shortName==="C"?Yg(r.value):Vg(r.value),s=Pe(Nr(i),n);t.push(Hg(s))}return Pe(...t)}function Zl(e){return Pe(Nr(e),zg())}function Jg(e){return e.export({type:"spki",format:"der"})}function qg(e){if(e.includes(":")){let t=e;if(e.includes("::")){let n=e.split("::"),s=n[0]?n[0].split(":"):[],o=n[1]?n[1].split(":"):[],a=8-s.length-o.length,c=Array.from({length:a},()=>"0");t=[...s,...c,...o].join(":")}let r=t.split(":"),i=Buffer.alloc(16);for(let n=0;n<8;n++){let s=Number.parseInt(r[n]||"0",16);i.writeUInt16BE(s,n*2)}return i}else{let t=e.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function Gg(e){let t=[];for(let r of e)if(r.type===2&&r.value){let i=Tr(r.value.length);t.push(Buffer.concat([Buffer.from([130]),i,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let i=qg(r.ip),n=Tr(i.length);t.push(Buffer.concat([Buffer.from([135]),n,i]))}else if(r.type===6&&r.value){let i=Tr(r.value.length);t.push(Buffer.concat([Buffer.from([134]),i,Buffer.from(r.value,"ascii")]))}return Pe(...t)}function Qg(e,t){if(e){if(t!==void 0)return Pe(Ae(1,Buffer.from([255])),zs(t));return Pe(Ae(1,Buffer.from([255])))}return Pe()}function Zg(e){let t=0;if(e.digitalSignature)t|=128;if(e.keyEncipherment)t|=32;if(e.keyCertSign)t|=4;if(e.cRLSign)t|=2;let r=0,i=t;while(i>0&&(i&1)===0)r++,i>>=1;if(t===0)r=7;return Gl(Buffer.from([t]),r)}function ep(e){let t=[];if(e.serverAuth)t.push(Nr(we.SERVER_AUTH));if(e.clientAuth)t.push(Nr(we.CLIENT_AUTH));return Pe(...t)}function xr(e,t,r){let i=[Nr(e)];if(t)i.push(Ae(1,Buffer.from([255])));return i.push(Ql(r)),Pe(...i)}function tp(e){let t=[];if(t.push(Yc(0,zs(2))),t.push(zs(e.serialNumber)),t.push(Zl(we.SHA256_WITH_RSA)),t.push(zc(e.issuer)),t.push(Xg(e.notBefore,e.notAfter)),t.push(zc(e.subject)),t.push(Jg(e.publicKey)),e.extensions){let r=[];if(e.extensions.basicConstraints)r.push(xr(we.BASIC_CONSTRAINTS,e.extensions.basicConstraints.critical??!0,Qg(e.extensions.basicConstraints.isCA,e.extensions.basicConstraints.pathLenConstraint)));if(e.extensions.keyUsage)r.push(xr(we.KEY_USAGE,e.extensions.keyUsage.critical??!0,Zg(e.extensions.keyUsage)));if(e.extensions.extendedKeyUsage)r.push(xr(we.EXTENDED_KEY_USAGE,!1,ep(e.extensions.extendedKeyUsage)));if(e.extensions.subjectAltName?.length)r.push(xr(we.SUBJECT_ALT_NAME,!1,Gg(e.extensions.subjectAltName)));if(e.extensions.subjectKeyIdentifier)r.push(xr(we.SUBJECT_KEY_IDENTIFIER,!1,Ql(e.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(Yc(3,Pe(...r)))}return Pe(...t)}function rp(e,t){let r=er.createSign("SHA256");r.update(e);let i=r.sign(t);return Pe(e,Zl(we.SHA256_WITH_RSA),Gl(i))}function ip(e,t){let r=e.toString("base64"),i=[];for(let n=0;n<r.length;n+=64)i.push(r.slice(n,n+64));return`-----BEGIN ${t}-----
|
|
66
|
-
${i.join(`
|
|
67
|
-
`)}
|
|
68
|
-
-----END ${t}-----
|
|
69
|
-
`}function co(){let e=er.randomBytes(20);return e[0]=e[0]&127||1,e}function ef(e=2048){let{privateKey:t,publicKey:r}=er.generateKeyPairSync("rsa",{modulusLength:e});return{privateKey:t,publicKey:r}}function np(e){let t=e.export({type:"spki",format:"der"});return er.createHash("sha1").update(t).digest()}function tf(e){let t={serialNumber:e.serialNumber||co(),notBefore:e.notBefore,notAfter:e.notAfter,subject:e.subject,issuer:e.issuer||e.subject,publicKey:e.publicKey,extensions:{basicConstraints:{isCA:e.isCA??!1,critical:!0,pathLenConstraint:e.pathLenConstraint},subjectKeyIdentifier:np(e.publicKey)}};if(e.keyUsage)t.extensions.keyUsage={...e.keyUsage,critical:!0};if(e.extendedKeyUsage)t.extensions.extendedKeyUsage=e.extendedKeyUsage;if(e.subjectAltName?.length)t.extensions.subjectAltName=e.subjectAltName;let r=tp(t),i=rp(r,e.signingKey);return{certificate:ip(i,"CERTIFICATE"),certificateDer:i}}function rf(e){return e.export({type:"pkcs8",format:"pem"})}function sp(e){return er.createPrivateKey(e)}function op(e){let t=new er.X509Certificate(e),r=t.publicKey,i=[],n=t.subject.split(`
|
|
70
|
-
`);for(let s of n){let[o,...a]=s.split("="),c=a.join("=");if(o&&c)i.push({shortName:o.trim(),value:c.trim()})}return{publicKey:r,subject:i}}async function lo(e={}){S("ca","Creating new Root CA Certificate",e.verbose);let t=e.keySize||Ue.DEFAULT_KEY_SIZE;S("ca",`Generating ${t}-bit RSA key pair`,e.verbose);let{privateKey:r,publicKey:i}=ef(t),n=[{shortName:"C",value:e.countryName||Q.countryName},{shortName:"ST",value:e.stateName||Q.stateName},{shortName:"L",value:e.localityName||Q.localityName},{shortName:"O",value:e.organization||"Local Development CA"},{shortName:"OU",value:e.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:e.commonName||"Local Development Root CA"}],{notBefore:s,notAfter:o}=ao({validityYears:e.validityYears||Ue.DEFAULT_CA_VALIDITY_YEARS,verbose:e.verbose}),{certificate:a}=tf({serialNumber:co(),notBefore:s,notAfter:o,subject:n,publicKey:i,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:a,privateKey:rf(r),notBefore:s,notAfter:o}}async function fo(e){if(S("ca","Generating new certificate",e.verbose),S("ca",`Options: ${qi(e)}`,e.verbose),!e.domain&&!e.domains?.length)throw Error("Either domain or domains must be specified");if(!e.rootCA?.certificate||!e.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=op(e.rootCA.certificate),r=sp(e.rootCA.privateKey);S("ca",`Generating ${Ue.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,e.verbose);let i=Ue.DEFAULT_KEY_SIZE,{privateKey:n,publicKey:s}=ef(i),o=e.commonName||Jl(e),a=e.certificateAttributes||[{shortName:"C",value:e.countryName||Q.countryName},{shortName:"ST",value:e.stateName||Q.stateName},{shortName:"L",value:e.localityName||Q.localityName},{shortName:"O",value:e.organizationName||Q.organizationName},{shortName:"CN",value:o}],{notBefore:c,notAfter:l}=ao({validityDays:e.validityDays||Ue.DEFAULT_VALIDITY_DAYS,verbose:e.verbose}),f=ql(e),u=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0},h=e.extKeyUsage||{serverAuth:!0},{certificate:d}=tf({serialNumber:co(),notBefore:c,notAfter:l,subject:a,issuer:t,publicKey:s,signingKey:r,isCA:e.basicConstraints?.cA??!1,pathLenConstraint:e.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:h,subjectAltName:f});return{certificate:d,privateKey:rf(n),notBefore:c,notAfter:l}}function nf(e,t){S(x.STORAGE,`Storing certificate and private key with options: ${qi(t)}`,t?.verbose);let{certPath:r,keyPath:i}=oo({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});S(x.STORAGE,`Certificate path: ${r}`,t?.verbose),S(x.STORAGE,`Private key path: ${i}`,t?.verbose);let n=Xs.dirname(r);if(!ot.existsSync(n))S(x.STORAGE,`Creating certificate directory: ${n}`,t?.verbose),ot.mkdirSync(n,{recursive:!0});S(x.STORAGE,"Writing certificate file",t?.verbose),ot.writeFileSync(r,e.certificate);let s=Xs.dirname(i);if(!ot.existsSync(s))S(x.STORAGE,`Creating private key directory: ${s}`,t?.verbose),ot.mkdirSync(s,{recursive:!0});return S(x.STORAGE,"Writing private key file",t?.verbose),ot.writeFileSync(i,e.privateKey),S(x.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function sf(e,t){S(x.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=oo({basePath:t?.basePath,caCertPath:t?.caCertPath});S(x.STORAGE,`CA certificate path: ${r}`,t?.verbose);let i=Xs.dirname(r);if(!ot.existsSync(i))S(x.STORAGE,`Creating CA certificate directory: ${i}`,t?.verbose),ot.mkdirSync(i,{recursive:!0});return S(x.STORAGE,"Writing CA certificate file",t?.verbose),ot.writeFileSync(r,e),S(x.STORAGE,"CA certificate stored successfully",t?.verbose),r}function Gi(e){let t;if(e.startsWith("-----BEGIN CERTIFICATE-----"))t=e;else t=zl(e);return new ap.X509Certificate(t)}function Qi(e){return Gi(e).fingerprint256.replace(/:/g,"").toUpperCase()}function uo(e){return of(Gi(e).subject)}function ho(e,t,r=443,i=4000){let n;try{n=t.includes("-----BEGIN")?t:cp.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((s)=>{let o=!1,a=(l)=>{if(o)return;o=!0,s(l)},c=lp.connect({host:e,port:r,servername:e,ca:n,rejectUnauthorized:!0},()=>{a(c.authorized),c.end()});c.setTimeout(i,()=>{c.destroy(),a(!1)}),c.on("error",()=>a(!1))})}function fp(e){let t=[],r=e.split(`
|
|
71
|
-
`);for(let i of r){let[n,...s]=i.split("="),o=s.join("=");if(n&&o)t.push({shortName:n.trim(),value:o.trim()})}return t}function of(e){return fp(e).find((t)=>t.shortName==="CN")?.value||""}function up(e){let t=[],r=of(e.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let i=e.subjectAltName;if(i){let n=i.split(", ");for(let s of n)if(s.startsWith("DNS:"))t.push(s.slice(4))}return[...new Set(t)]}function mo(e,t){let r=Gi(e),i=up(r);for(let n of i){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2);if(t.endsWith(s)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function dp(e,t){if(Hi.platform()!=="darwin")return!1;try{let r=Qi(e);if(!r)return S(x.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(hp("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
72
|
-
`).some((i)=>{let n=i.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!n&&n[1].toUpperCase()===r}))return S(x.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return S(x.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return S(x.TRUST,`Error checking certificate trust: ${r}`,t),!1}}var mp={platform:"darwin",async addCertificate(e,t){if(await dp(e,t?.verbose)){S(x.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),Gt.success("Certificate is already trusted in system keychain");return}S(x.TRUST,"Adding certificate to macOS keychain",t?.verbose),await bt(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${e}`)},async removeCertificate(e,t,r){let i=r||Q.commonName;S(x.TRUST,`Removing certificate ${i} from macOS keychain`,t?.verbose);try{await bt(`sudo security delete-certificate -c "${i}" /Library/Keychains/System.keychain`),S(x.TRUST,`Removed certificate ${i} from macOS keychain`,t?.verbose)}catch(n){throw S(x.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},gp={platform:"win32",async addCertificate(e,t){S(x.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await bt(`certutil -f -v -addstore -enterprise Root ${e}`)},async removeCertificate(e,t,r){let i=r||Q.commonName;S(x.TRUST,`Removing certificate ${i} from Windows certificate store`,t?.verbose);try{await bt(`certutil -delstore -enterprise Root "${i}"`),S(x.TRUST,`Removed certificate ${i} from Windows certificate store`,t?.verbose)}catch(n){throw S(x.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},pp={platform:"linux",async addCertificate(e,t){S(x.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=Hi.homedir(),i=Ue.LINUX_CERT_DB_FILENAME,n=Ue.LINUX_TRUST_ARGS;S(x.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let s=Vs(r,i);if(s.length===0){Gt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let o of s){S(x.TRUST,`Processing certificate database in ${o}`,t?.verbose);try{S(x.TRUST,`Attempting to delete existing cert for ${Q.commonName}`,t?.verbose),await bt(`certutil -d sql:${o} -D -n ${Q.commonName}`)}catch(a){S(x.TRUST,`Warning: Error deleting existing cert: ${a}`,t?.verbose),console.warn(`Error deleting existing cert: ${a}`)}S(x.TRUST,`Adding new certificate to ${o}`,t?.verbose),await bt(`certutil -d sql:${o} -A -t ${n} -n ${Q.commonName} -i ${e}`),Gt.info(`Cert added to ${o}`)}},async removeCertificate(e,t,r){let i=r||Q.commonName;S(x.TRUST,`Removing certificate ${i} from Linux certificate store`,t?.verbose);let n=Hi.homedir(),s=Ue.LINUX_CERT_DB_FILENAME;S(x.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let o=Vs(n,s);if(o.length===0){Gt.warn("No certificate databases found. Cannot remove certificate.");return}for(let a of o){S(x.TRUST,`Processing certificate database in ${a}`,t?.verbose);try{await bt(`certutil -d sql:${a} -D -n "${i}"`),Gt.info(`Cert removed from ${a}`)}catch(c){S(x.TRUST,`Error removing cert from ${a}: ${c}`,t?.verbose),console.warn(`Error removing cert from ${a}: ${c}`)}}}},yp={darwin:mp,win32:gp,linux:pp};async function go(e,t,r){S(x.TRUST,`Adding certificate to system trust store with options: ${qi(r)}`,r?.verbose),S(x.TRUST,"Storing certificate and private key",r?.verbose);let i=nf(e,r);S(x.TRUST,"Storing CA certificate",r?.verbose);let n=sf(t,r),s=Hi.platform();S(x.TRUST,`Detected platform: ${s}`,r?.verbose);let o=yp[s];if(!o){let a=`Unsupported platform: ${s}`;throw S(x.TRUST,`Error: ${a}`,r?.verbose),Error(a)}return await o.addCertificate(n,r),S(x.TRUST,"Certificate successfully added to system trust store",r?.verbose),i}import{homedir as ia}from"node:os";import{join as na,resolve as xx}from"node:path";import{existsSync as af,statSync as cf}from"fs";import{existsSync as wp,mkdirSync as I0,readdirSync as _0,readFileSync as vp,writeFileSync as j0}from"fs";import{homedir as tr}from"os";import{dirname as K0,resolve as Be}from"path";import Dn from"process";import{existsSync as lf,statSync as ff}from"fs";import{existsSync as Bo,mkdirSync as bp,readdirSync as Cp,writeFileSync as Sp}from"fs";import{homedir as rr}from"os";import{dirname as uf,resolve as be}from"path";import Ot from"process";import{join as Ep,relative as xp,resolve as hf}from"path";import bn from"process";import{existsSync as Jf,mkdirSync as Z0,readdirSync as eE,writeFileSync as tE}from"fs";import{homedir as po}from"os";import{dirname as nE,resolve as ve}from"path";import Fr from"process";import{join as $p,relative as Tp,resolve as df}from"path";import Cn from"process";import{existsSync as qf,mkdirSync as lE,readdirSync as fE,writeFileSync as uE}from"fs";import{dirname as dE,resolve as Sn}from"path";import Lo from"process";import{Buffer as Et}from"buffer";import{createCipheriv as Pp,createDecipheriv as Ap,randomBytes as yo}from"crypto";import{closeSync as wo,createReadStream as mf,createWriteStream as Rp,existsSync as vo,fsyncSync as gf,openSync as pf,writeFileSync as kp}from"fs";import{access as Np,constants as yf,mkdir as Op,readdir as Zi,rename as wf,stat as ir,unlink as en,writeFile as bo}from"fs/promises";import{join as nr}from"path";import he from"process";import{pipeline as Dp}from"stream/promises";import{createGzip as vf}from"zlib";import sr from"process";import ut from"process";import{Buffer as ct}from"buffer";import{createCipheriv as Fp,createDecipheriv as Bp,randomBytes as Co}from"crypto";import{closeSync as So,createReadStream as bf,createWriteStream as Lp,existsSync as tn,fsyncSync as Cf,openSync as Sf,writeFileSync as Mp}from"fs";import{access as Ip,constants as Ef,mkdir as _p,readdir as rn,rename as xf,stat as or,unlink as nn,writeFile as Eo}from"fs/promises";import{isAbsolute as jp,join as ar,resolve as Up}from"path";import D from"process";import{pipeline as Wp}from"stream/promises";import{createGzip as $f}from"zlib";import cr from"process";import ht from"process";import sn from"process";import{existsSync as on}from"fs";import{resolve as xo}from"path";import{existsSync as Kp}from"fs";import{existsSync as Hp,readdirSync as Yp}from"fs";import{extname as $o,resolve as Tf}from"path";import Vp from"process";import{join as zp,relative as Xp,resolve as Pf}from"path";import En from"process";import{Buffer as lt}from"buffer";import{createCipheriv as Jp,createDecipheriv as qp,randomBytes as To}from"crypto";import{closeSync as Po,createReadStream as Af,createWriteStream as Gp,existsSync as an,fsyncSync as Rf,openSync as kf,writeFileSync as Qp}from"fs";import{access as Zp,constants as Nf,mkdir as ey,readdir as cn,rename as Of,stat as lr,unlink as ln,writeFile as Ao}from"fs/promises";import{isAbsolute as ty,join as fr,resolve as ry}from"path";import F from"process";import{pipeline as iy}from"stream/promises";import{createGzip as Df}from"zlib";import ur from"process";import dt from"process";import un from"process";import{existsSync as hn}from"fs";import{resolve as Fo}from"path";import{existsSync as Ew}from"fs";class zf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!af(e))return!0;return cf(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=af(r)?cf(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Xf{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var vn=new zf,zo=new Xf;var ny=Object.defineProperty,sy=(e)=>e;function oy(e,t){this[e]=sy.bind(null,t)}var ay=(e,t)=>{for(var r in t)ny(e,r,{get:t[r],enumerable:!0,configurable:!0,set:oy.bind(t,r)})},cy=(e,t)=>()=>(e&&(t=e(e=0)),t),Gf={};ay(Gf,{withErrorRecovery:()=>eu,tryLoadConfig:()=>Ny,loadConfigWithResult:()=>Ry,loadConfig:()=>su,isRetryableError:()=>Ey,isConfigNotFoundError:()=>Sy,isBunfigError:()=>tu,globalPerformanceMonitor:()=>Mr,globalCache:()=>hr,getEnvOrDefault:()=>xy,generateConfigTypes:()=>Oy,defaultGeneratedDir:()=>du,defaultConfigDir:()=>hu,deepMergeWithArrayStrategy:()=>Qo,deepMerge:()=>ru,createLibraryConfig:()=>Dy,config:()=>ky,bunfigPlugin:()=>Fy,applyEnvVarsToConfig:()=>Dr,TypeGenerationError:()=>Ko,SchemaValidationError:()=>Lr,PluginError:()=>Yo,PerformanceMonitor:()=>Jo,FileSystemError:()=>Wo,ErrorFactory:()=>xt,EnvVarError:()=>Rn,EnvProcessor:()=>Fn,ConfigValidator:()=>Zo,ConfigValidationError:()=>jo,ConfigNotFoundError:()=>An,ConfigMergeError:()=>Uo,ConfigLoader:()=>ea,ConfigLoadError:()=>Br,ConfigFileLoader:()=>Bn,ConfigCache:()=>Xo,CacheUtils:()=>au,BunfigError:()=>Re,BrowserConfigError:()=>Ho,ArrayMergeStrategies:()=>fu});class Xo{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!lf(e))return!0;return ff(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=lf(r)?ff(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Jo{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function ly(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function fy(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function uy(e){return e.getStats().size*2}function qo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&z(t[0])&&"id"in t[0]&&t[0].id===3&&z(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(z(t)&&z(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(z(e)&&"arr"in e&&Array.isArray(e.arr)&&z(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&z(t[0])&&z(e[0])){let i=[...t];for(let n of e)if(z(n)&&"name"in n){if(!i.find((o)=>z(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(z(n)&&"path"in n){if(!i.find((o)=>z(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>xn(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!z(t)||!z(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(z(n)&&z(r[i]))r[i]=qo(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&z(n[0])&&z(r[i][0])){let s=[...n];for(let o of r[i])if(z(o)&&"name"in o){if(!s.find((c)=>z(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(z(o)&&"path"in o){if(!s.find((c)=>z(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((a)=>xn(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function xn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!xn(e[r],t[r]))return!1;return!0}if(z(e)&&z(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!xn(e[n],t[n]))return!1}return!0}return!1}function z(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function hy(e,t){if(!qf(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return qo(t,i)}catch{return null}}catch{return null}}async function dy({name:e="",cwd:t,defaultConfig:r}){let i=t||Lo.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of n){let c=Sn(i,`${o}${a}`),l=await hy(c,r);if(l!==null)return l}try{let o=Sn(i,"package.json");if(qf(o)){let c=(await import(o))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return qo(r,c)}catch{}}}catch{}return r}function my(e,t={}){let r=Cn.cwd();while(r.includes("storage"))r=df(r,"..");let i=df(r,e||"");if(t?.relative)return Tp(Cn.cwd(),i);return i}async function gy(){try{let e=await dy({name:"clarity",defaultConfig:gn,cwd:Cn.cwd(),endpoint:"",headers:{}});return{...gn,...e}}catch{return gn}}function q(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function py(){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 e=ut.type;if(e==="renderer"||e==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class Qf{async format(e){let t=await py(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:sr.pid,hostname:t(),environment:sr.env.NODE_ENV||"development",platform:sr.platform,version:sr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:sr.env.NODE_ENV||sr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $n{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(e,t={}){this.name=e,this.config={...Io},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Qf,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??he.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...pn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...pn};return{...pn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Io.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,a=1000;while(s<o)try{try{try{await Np(this.config.logDirectory,yf.F_OK|yf.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Op(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Et.from(e);try{if(!vo(this.currentLogFile))await bo(this.currentLogFile,"",{mode:420});if(n=pf(this.currentLogFile,"a",420),kp(n,c,{flag:"a"}),gf(n),n!==void 0)wo(n),n=void 0;if((await ir(this.currentLogFile)).size===0){if(await bo(this.currentLogFile,c,{flag:"w",mode:420}),(await ir(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=a*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{wo(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(s===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}s++;let l=a*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return nr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return nr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(q())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,c])=>c.createdAt.getTime()-a.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[a]of n.slice(o))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return yo(16).toString("hex")}generateKey(){return yo(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yo(16),i=Pp("aes-256-gcm",t,r),n=Et.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:Et.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=vf(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Et.from(Et.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(q())return;let e=await ir(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Zi(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await ir(r).catch(()=>null))try{if(await wf(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await en(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await bo(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await ir(r).catch(()=>null))await wf(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Zi(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,a)=>a.localeCompare(o));for(let o of s.slice(t.maxFiles))await en(nr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=mf(e),i=Rp(t),n=vf();await Dp(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),vo(this.currentLogFile))try{let e=pf(this.currentLogFile,"r+");gf(e),wo(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Zi(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await en(nr(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=he.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${Y.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!q()){let l=cu[e],f=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:Y.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:Y.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u),a){let h=a.split(`
|
|
73
|
-
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:Y.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!q()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
74
|
-
`;if(a)c+=`${a}
|
|
75
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!q()){let r=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:Y.blue("◐"),tag:r,message:`${Y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
76
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let f=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Y.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!q())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new $n(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!vo(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mf(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Et.isBuffer(e)?e:Et.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),a=Ap("aes-256-gcm",r,n);return a.setAuthTag(s),Et.concat([a.update(o),a.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q()}isServerMode(){return!q()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!q()){let s=e.split(`
|
|
77
|
-
`),o=Math.max(...s.map((f)=>f.length))+2,a=`┌${"─".repeat(o)}┐`,c=`└${"─".repeat(o)}┘`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`│ ${f}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Y.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Y.cyan(a)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:Y.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Y.cyan(c),showTimestamp:!1}))}else if(!q())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
|
|
78
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(q())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Y.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();he.stdin.removeListener("data",r);try{if(typeof he.stdin.setRawMode==="function")he.stdin.setRawMode(!1)}catch{}he.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof he.stdin.setRawMode==="function")he.stdin.setRawMode(!0)}catch{}he.stdin.resume(),he.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,l)=>{if(l==="%")return"%";if(a>=t.length)return c;let f=t[a++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!q()){let o=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",a=Y.blue("◐");console.error(`${a} ${o} ${Y.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
79
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||q()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,a)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),a!==void 0)this.activeProgressBar.message=a;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,a="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;he.stdout.write(`${"\r".padEnd(he.stdout.columns||80)}\r`),this.log(a,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||q()||!he.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=Y.green("━".repeat(i)),o=Y.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?Y.green("✓"):Y.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=he.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,he.stdout.write(e.lastRenderedLine),t)he.stdout.write(`
|
|
80
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||q()||!he.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zi(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=nr(this.config.logDirectory,i);if(e.before)try{if((await ir(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await en(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function mn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.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(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(K(e)&&"arr"in e&&Array.isArray(e.arr)&&K(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&K(t[0])&&K(e[0])){let i=[...t];for(let n of e)if(K(n)&&"name"in n){if(!i.find((o)=>K(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(K(n)&&"path"in n){if(!i.find((o)=>K(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Tn(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!K(t)||!K(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(K(n)&&K(r[i]))r[i]=mn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&K(n[0])&&K(r[i][0])){let s=[...n];for(let o of r[i])if(K(o)&&"name"in o){if(!s.find((c)=>K(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(K(o)&&"path"in o){if(!s.find((c)=>K(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((a)=>Tn(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Go(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:mn(e,t);if(Array.isArray(e))return r==="replace"?t:mn(e,t);if(!K(t)||!K(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=mn(o,s);else if(K(s)&&K(o))i[n]=Go(o,s,r);else i[n]=s}return i}function Tn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Tn(e[r],t[r]))return!1;return!0}if(K(e)&&K(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Tn(e[n],t[n]))return!1}return!0}return!1}function K(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function fn(e,t,r="replace"){if(!Jf(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Go(t,n,r)}catch{return null}}catch{return null}}function yy(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${u.map(h).join("_")}`,y=`${i}_${u.map((g)=>g.toUpperCase()).join("_")}`;if(r)me.info(`Checking environment variable ${d} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))c[l]=s(f,u);else{let g=Fr.env[d]||Fr.env[y];if(g!==void 0){if(r)me.info(`Using environment variable ${g?d:y} for config ${e}.${u.join(".")}`);if(typeof f==="number")c[l]=Number(g);else if(typeof f==="boolean")c[l]=g.toLowerCase()==="true";else if(Array.isArray(f))try{let p=JSON.parse(g);if(Array.isArray(p))c[l]=p;else c[l]=g.split(",").map((w)=>w.trim())}catch{c[l]=g.split(",").map((p)=>p.trim())}else c[l]=g}}}return c}return s(n)}async function wy({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?yy(e,n,s):n,l=r||Fr.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)me.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,ve(l,"config"),ve(l,".config"),i?ve(l,i):void 0].filter(Boolean)));for(let p of g){if(s)me.info(`Searching for configuration in: ${p}`);let v=[ve(l,"config"),ve(l,".config")].concat(i?[ve(l,i)]:[]).includes(p)?[...u,...h,...d,...y]:[...h,...u,...y,...d];for(let E of v)for(let R of f){let T=ve(p,`${E}${R}`),N=await fn(T,c,a);if(N!==null){if(s)me.success(`Configuration loaded from: ${T}`);return N}}}if(e){let p=ve(po(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)me.info(`Checking user config directory: ${p}`);for(let v of w)for(let E of f){let R=ve(p,`${v}${E}`),T=await fn(R,c,a);if(T!==null){if(s)me.success(`Configuration loaded from user config directory: ${R}`);return T}}}if(e){let p=ve(po(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)me.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let E of f){let R=ve(p,`${v}${E}`),T=await fn(R,c,a);if(T!==null){if(s)me.success(`Configuration loaded from user config directory dotfile: ${R}`);return T}}}if(e){let p=po(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)me.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let E of f){let R=ve(p,`${v}${E}`),T=await fn(R,c,a);if(T!==null){if(s)me.success(`Configuration loaded from user home directory: ${R}`);return T}}}try{let p=ve(l,"package.json");if(Jf(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)me.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)me.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return Go(c,v,a)}catch(E){if(s)me.warn("Failed to merge package.json config:",E)}}}catch(p){if(s)me.warn("Failed to load package.json:",p)}if(s)me.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function vy(e,t={}){let r=bn.cwd();while(r.includes("storage"))r=hf(r,"..");let i=hf(r,e||"");if(t?.relative)return xp(bn.cwd(),i);return i}async function by(){try{let e=await wy({name:"clarity",alias:"logging",defaultConfig:yn,cwd:bn.cwd()});return{...yn,...e||{}}}catch{return yn}}function ne(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Cy(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let e=ht.type;if(e==="renderer"||e==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class Zf{async format(e){let t=await Cy(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:cr.pid,hostname:t(),environment:cr.env.NODE_ENV||"development",platform:cr.platform,version:cr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cr.env.NODE_ENV||cr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Pn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={..._o},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zf,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??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...wn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...wn};return{...wn,...e.fingersCrossed}}normalizeOptions(e){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},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ne()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,a=1000;while(s<o)try{try{try{await Ip(this.config.logDirectory,Ef.F_OK|Ef.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await _p(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ct.from(e);try{if(!tn(this.currentLogFile))await Eo(this.currentLogFile,"",{mode:420});if(n=Sf(this.currentLogFile,"a",420),Mp(n,c,{flag:"a"}),Cf(n),n!==void 0)So(n),n=void 0;if((await or(this.currentLogFile)).size===0){if(await Eo(this.currentLogFile,c,{flag:"w",mode:420}),(await or(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=a*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{So(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(s===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}s++;let l=a*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 ar(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 ar(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ar(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ne())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,c])=>c.createdAt.getTime()-a.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[a]of n.slice(o))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Co(16).toString("hex")}generateKey(){return Co(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Co(16),i=Fp("aes-256-gcm",t,r),n=ct.isBuffer(e)?e:ct.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=ct.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=$f(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ct.from(ct.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ne())return;if(!this.shouldWriteToFile())return;let e=await or(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await rn(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await or(r).catch(()=>null))try{if(await xf(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await nn(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Eo(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await or(r).catch(()=>null))await xf(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await rn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,a)=>a.localeCompare(o));for(let o of s.slice(t.maxFiles))await nn(ar(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=bf(e),i=Lp(t),n=$f();await Wp(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),tn(this.currentLogFile))try{let e=Sf(this.currentLogFile,"r+");Cf(e),So(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await rn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await nn(ar(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?L.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ne())return!1;let e=typeof D.env.NO_COLOR<"u",t=D.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=D.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${L.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=L.underline(L.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>L.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>L.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>L.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>L.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>L.strikethrough(i)),t}supportsHyperlinks(){if(ne())return!1;let e=D.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=D.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(jp(t)||t.startsWith("./")||t.startsWith("../"))t=Up(t);else return null;return tn(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":lu[e],h=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:L.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:L.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let y=a.split(`
|
|
81
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:L.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!ne()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
82
|
-
`;if(a)f+=`${a}
|
|
83
|
-
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(a,c)=>{},finish:(a)=>{},interrupt:(a,c)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ne()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(a,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,a),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!ne()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(a)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,a)},interrupt:(a,c="info")=>{if(!ne()&&D.stdout.isTTY)D.stdout.write(`
|
|
84
|
-
`);if(this[c==="warning"?"warn":c](a),this.activeProgressBar&&this.shouldStyleConsole()&&!ne()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":L.blue("◐"),tag:r,message:`${L.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
85
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":L.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ne())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Pn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ne())throw Error("createReadStream is not supported in browser environments");if(!tn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bf(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=ct.isBuffer(e)?e:ct.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=Bp("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=ct.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ne()}isServerMode(){return!ne()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
86
|
-
`),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:L.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(f),showTimestamp:!1}))}else if(!ne())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
87
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${L.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();D.stdin.removeListener("data",r);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(r=e.replace(c,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${L.blue("◐")} `;console.error(`${l}${c} ${L.cyan(i)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
88
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=L.green("━".repeat(i)),o=L.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?L.green("✓"):L.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=D.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,D.stdout.write(e.lastRenderedLine),t)D.stdout.write(`
|
|
89
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ne()||!D.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await rn(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=ar(this.config.logDirectory,i);if(e.before)try{if((await or(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await nn(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function eu(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function tu(e){return e instanceof Re}function Sy(e){return e instanceof An}function Ey(e){if(tu(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Fn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Mr.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=sn.env[c]||(l?sn.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=sn.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof Rn)throw u;throw xt.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw xt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(sn.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
90
|
-
|
|
91
|
-
`;for(let i of e)r+=`${i.key}
|
|
92
|
-
`,r+=` Type: ${i.type}
|
|
93
|
-
`,r+=` Description: ${i.description}
|
|
94
|
-
`,r+=` Example: ${i.example}
|
|
95
|
-
|
|
96
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
97
|
-
|
|
98
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
99
|
-
`,r+=`|----------|------|-------------|----------|
|
|
100
|
-
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
101
|
-
`;return r}}function xy(e,t){let r=ou("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function ru(e,t,r={}){return iu(e,t,r,new WeakMap)}function iu(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return nu(e,t,n,i);if(!Le(t)||!Le(e))return t;return Ay(e,t,r,i)}function nu(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return $y(e,t);case"smart":return Ty(e,t,i);default:return t}return t}function $y(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Mo(n,i)))r.push(i);return r}function Ty(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Le(t[0])&&Le(e[0]))return Py(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Py(e,t,r){let i=[...t];for(let n of e){if(!Le(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((l)=>Le(l)&&(a in l)&&l[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function Ay(e,t,r,i){let n=t;if(Le(n)&&i.has(n))return i.get(n);let s={...e};if(Le(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Le(a)&&Le(c))s[o]=iu(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=nu(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function Qo(e,t,r="replace"){return ru(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Mo(e[r],t[r]))return!1;return!0}if(Le(e)&&Le(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Mo(e[n],t[n]))return!1}return!0}return!1}function Le(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Bn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=hr.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!on(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new Br(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Br(e,Error("Configuration must export a valid object"),"unknown");let p={config:Qo(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)hr.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?xt.configLoad(e,l):xt.configLoad(e,Error(String(l)))}};if(o)return Mr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(xo(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return eu(async()=>on(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!on(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=xo(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=xo(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!on(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Zo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await Mr.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Kp(t))throw new Lr(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Lr(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:uu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ea{fileLoader=new Bn;envProcessor=new Fn;validator=new Zo;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)He.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw He.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Ot.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let y=await this.loadHomeConfiguration(i,n,a,l,f,c);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(be(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw xt.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?Dr(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)He.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)He.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Dr(e,r,n):r,a=[be(rr(),".config",e),be(rr(),".config"),rr()];for(let c of a){if(n)He.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)He.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?Dr(e,i,s):i;try{let c=be(r,"package.json");if(!Bo(c))return null;let l=await import(c),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)He.success(`Configuration loaded from package.json: ${u}`);return{config:Qo(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)He.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Dr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw xt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return hr.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);hr.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,be(e,"config"),be(e,".config"),t?be(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(be(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[be(rr(),".config",e),be(rr(),".config"),rr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ff(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||i}async function Ry(e){return mt.loadConfig({...e,__strictErrorHandling:!0})}async function su(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await mt.loadConfig(e);else i=await mt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)He.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await mt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function ky(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await mt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ff(r)))return(await mt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await mt.loadConfig({...e,cwd:e.cwd||Ot.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ff(t)))return(await mt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Ny(e,t,r="replace"){let i=new Bn;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Dr(e,t,r=!1){let i=new Fn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Ot.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}function Oy(e){let t=be(Ot.cwd(),e.configDir),r=be(Ot.cwd(),e.generatedDir),i=be(r,"config-types.ts");if(!Bo(uf(i)))bp(uf(i),{recursive:!0,mode:511});let n=Bo(t)?Cp(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${aw}
|
|
102
|
-
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
103
|
-
`;Sp(i,s,{mode:438})}function Dy(e){let t=null,r=null,i=()=>{if(!r)r=su(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)He.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let a=n[o];return i(),a},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,a){if(!t)t={...n};return t[o]=a,!0}})}function Fy(e){let t=Tf(Vp.cwd(),e?.configDir||"./config");function r(){if(!Hp(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Yp(t).filter((c)=>n.has($o(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:l}of o){let f=$o(l).toLowerCase(),u=a.get(c);if(!u){a.set(c,l);continue}let h=$o(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))a.set(c,l)}return Array.from(a.entries()).map(([c,l])=>({base:c,file:l})).sort((c,l)=>c.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",a=n.length?`{
|
|
104
|
-
${n.map((l)=>{let f=Tf(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
|
|
105
|
-
`)}
|
|
106
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
107
|
-
export type ConfigByName = ${a}
|
|
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(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var ou,hr,Mr,au,By,Ly,Bf,gn,Io,de,Y,My,Lf,Iy,Mf,_y,jy,Ro,Uy,If,_f,ko,Wy,Ky,Hy,Yy,pn,cu,Vy,me,zy,Xy,jf,yn,_o,se,L,Jy,Uf,qy,Wf,Gy,Qy,No,Zy,Kf,Hf,ew,Oo,tw,rw,iw,nw,sw,wn,lu,ow,aw="0.15.6",Re,An,Br,jo,Uo,Rn,Wo,Ko,Lr,Ho,Yo,xt,fu,uu,He,mt,hu,du,cw=cy(async()=>{ou=import.meta.require,hr=new Xo,Mr=new Jo,au={createKey:ly,isEquivalent:fy,estimateMemoryUsage:uy},By=Sn(Lo.cwd(),"config"),Ly=Sn(Lo.cwd(),"src/generated"),Bf=Cn.env.CLARITY_LOG_DIR||$p(my(),"logs"),gn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Bf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Io=await gy(),de={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Y=de,My=de.red,Lf=de.green,Iy=de.yellow,Mf=de.blue,_y=de.magenta,jy=de.cyan,Ro=de.white,Uy=de.gray,If=de.bgRed,_f=de.bgYellow,ko=de.bold,Wy=de.dim,Ky=de.italic,Hy=de.underline,Yy=de.reset,pn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cu={debug:"\uD83D\uDD0D",info:Mf("ℹ"),success:Lf("✓"),warning:_f(Ro(ko(" WARN "))),error:If(Ro(ko(" ERROR ")))},Vy=new $n("stacks"),me=new $n("bunfig",{showTags:!0}),zy=ve(Fr.cwd(),"config"),Xy=ve(Fr.cwd(),"src/generated"),jf=bn.env.CLARITY_LOG_DIR||Ep(vy(),"logs"),yn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jf,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 by(),se={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},L=se,Jy=se.red,Uf=se.green,qy=se.yellow,Wf=se.blue,Gy=se.magenta,Qy=se.cyan,No=se.white,Zy=se.gray,Kf=se.bgRed,Hf=se.bgYellow,ew=se.bgGray,Oo=se.bold,tw=se.dim,rw=se.italic,iw=se.underline,nw=se.strikethrough,sw=se.reset,wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lu={debug:"\uD83D\uDD0D",info:Wf("ℹ"),success:Uf("✓"),warning:Hf(No(Oo(" WARN "))),error:Kf(No(Oo(" ERROR ")))},ow=new Pn("stacks"),Re=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,i])=>`${r}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},An=class extends Re{code="CONFIG_NOT_FOUND";constructor(t,r,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:i,searchPaths:r,searchPathCount:r.length})}},Br=class extends Re{code="CONFIG_LOAD_ERROR";constructor(t,r,i){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},jo=class extends Re{code="CONFIG_VALIDATION_ERROR";constructor(t,r,i){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Uo=class extends Re{code="CONFIG_MERGE_ERROR";constructor(t,r,i,n){super(`Failed to merge configuration from "${t}" with "${r}": ${i.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Rn=class extends Re{code="ENV_VAR_ERROR";constructor(t,r,i,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${i}`,{envKey:t,envValue:r,expectedType:i,configName:n})}},Wo=class extends Re{code="FILE_SYSTEM_ERROR";constructor(t,r,i){super(`File system ${t} failed for "${r}": ${i.message}`,{operation:t,path:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Ko=class extends Re{code="TYPE_GENERATION_ERROR";constructor(t,r,i){super(`Failed to generate types from "${t}" to "${r}": ${i.message}`,{configDir:t,outputPath:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Lr=class extends Re{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Ho=class extends Re{code="BROWSER_CONFIG_ERROR";constructor(t,r,i,n){super(`Failed to fetch configuration from "${t}": ${r} ${i}`,{endpoint:t,status:r,statusText:i,configName:n})}},Yo=class extends Re{code="PLUGIN_ERROR";constructor(t,r,i){super(`Plugin "${t}" failed during ${r}: ${i.message}`,{pluginName:t,operation:r,originalError:i.name,originalMessage:i.message});this.cause=i}},xt={configNotFound(e,t,r){return new An(e,t,r)},configLoad(e,t,r){return new Br(e,t,r)},configValidation(e,t,r){return new jo(e,t,r)},configMerge(e,t,r,i){return new Uo(e,t,r,i)},envVar(e,t,r,i){return new Rn(e,t,r,i)},fileSystem(e,t,r){return new Wo(e,t,r)},typeGeneration(e,t,r){return new Ko(e,t,r)},schemaValidation(e,t,r){return new Lr(e,t,r)},browserConfig(e,t,r,i){return new Ho(e,t,r,i)},plugin(e,t,r){return new Yo(e,t,r)}},fu={replace:"replace",concat:"concat",smart:"smart"},uu=/^https?:\/\//,He=new Pn("bunfig",{showTags:!0}),mt=new ea,hu=be(Ot.cwd(),"config"),du=be(Ot.cwd(),"src/generated")});function lw(e,t={}){let r=En.cwd();while(r.includes("storage"))r=Pf(r,"..");let i=Pf(r,e||"");if(t?.relative)return Xp(En.cwd(),i);return i}var fw=En.env.CLARITY_LOG_DIR||zp(lw(),"logs"),mu={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fw,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},kn={...mu},ex=(async()=>{try{let{loadConfig:e}=await cw().then(()=>Gf),t=await e({name:"clarity",alias:"logging",defaultConfig:mu,cwd:En.cwd()});if(t)Object.assign(kn,t)}catch{}return kn})();function oe(){if(dt.env.NODE_ENV==="test"||dt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uw(){if(dt.env.NODE_ENV==="test"||dt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dt<"u"){let e=dt.type;if(e==="renderer"||e==="worker")return!1;return!!(dt.versions&&(dt.versions.node||dt.versions.bun))}return!1}class gu{async format(e){let t=await uw(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ur.pid,hostname:t(),environment:ur.env.NODE_ENV||"development",platform:ur.platform,version:ur.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ur.env.NODE_ENV||ur.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ce={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},I=ce,tx=ce.red,hw=ce.green,rx=ce.yellow,dw=ce.blue,ix=ce.magenta,nx=ce.cyan,Yf=ce.white,sx=ce.gray,mw=ce.bgRed,gw=ce.bgYellow,ox=ce.bgGray,Vf=ce.bold,ax=ce.dim,cx=ce.italic,lx=ce.underline,fx=ce.strikethrough,ux=ce.reset,Do={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pw={debug:"\uD83D\uDD0D",info:dw("ℹ"),success:hw("✓"),warning:gw(Yf(Vf(" WARN "))),error:mw(Yf(Vf(" ERROR ")))};class Ln{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(e,t={}){this.name=e,this.config={...kn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new gu,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??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Do,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Do};return{...Do,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:kn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!oe()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,a=1000;while(s<o)try{try{try{await Zp(this.config.logDirectory,Nf.F_OK|Nf.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ey(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:lt.from(e);try{if(!an(this.currentLogFile))await Ao(this.currentLogFile,"",{mode:420});if(n=kf(this.currentLogFile,"a",420),Qp(n,c,{flag:"a"}),Rf(n),n!==void 0)Po(n),n=void 0;if((await lr(this.currentLogFile)).size===0){if(await Ao(this.currentLogFile,c,{flag:"w",mode:420}),(await lr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=a*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Po(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(s===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}s++;let l=a*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 fr(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 fr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return fr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(oe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,c])=>c.createdAt.getTime()-a.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[a]of n.slice(o))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return To(16).toString("hex")}generateKey(){return To(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=To(16),i=Jp("aes-256-gcm",t,r),n=lt.isBuffer(e)?e:lt.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=lt.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Df(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(lt.from(lt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(oe())return;if(!this.shouldWriteToFile())return;let e=await lr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await cn(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await lr(r).catch(()=>null))try{if(await Of(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ln(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Ao(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await lr(r).catch(()=>null))await Of(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await cn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,a)=>a.localeCompare(o));for(let o of s.slice(t.maxFiles))await ln(fr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Af(e),i=Gp(t),n=Df();await iy(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),an(this.currentLogFile))try{let e=kf(this.currentLogFile,"r+");Rf(e),Po(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!oe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await cn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ln(fr(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?I.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||oe())return!1;let e=typeof F.env.NO_COLOR<"u",t=F.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=F.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${I.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=I.underline(I.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>I.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>I.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>I.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>I.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>I.strikethrough(i)),t}supportsHyperlinks(){if(oe())return!1;let e=F.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=F.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ty(t)||t.startsWith("./")||t.startsWith("../"))t=ry(t);else return null;return an(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":pw[e],h=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:I.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:I.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let y=a.split(`
|
|
111
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:I.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!oe()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
112
|
-
`;if(a)f+=`${a}
|
|
113
|
-
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(a,c)=>{},finish:(a)=>{},interrupt:(a,c)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!oe()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(a,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,a),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!oe()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(a)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,a)},interrupt:(a,c="info")=>{if(!oe()&&F.stdout.isTTY)F.stdout.write(`
|
|
114
|
-
`);if(this[c==="warning"?"warn":c](a),this.activeProgressBar&&this.shouldStyleConsole()&&!oe()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:r,message:`${I.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
115
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":I.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!oe())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ln(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(oe())throw Error("createReadStream is not supported in browser environments");if(!an(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Af(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=lt.isBuffer(e)?e:lt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=qp("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=lt.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return oe()}isServerMode(){return!oe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
116
|
-
`),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:I.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:I.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:I.cyan(f),showTimestamp:!1}))}else if(!oe())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
117
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(oe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${I.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();F.stdin.removeListener("data",r);try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!1)}catch{}F.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!0)}catch{}F.stdin.resume(),F.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(r=e.replace(c,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${l}${c} ${I.cyan(i)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
118
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=I.green("━".repeat(i)),o=I.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?I.green("✓"):I.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=F.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,F.stdout.write(e.lastRenderedLine),t)F.stdout.write(`
|
|
119
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||oe()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(oe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cn(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=fr(this.config.logDirectory,i);if(e.before)try{if((await lr(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await ln(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var hx=new Ln("stacks");class Ye extends Error{timestamp;context;constructor(e,t={}){super(e);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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class pu extends Ye{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Nn extends Ye{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class yu extends Ye{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class wu extends Ye{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class ta extends Ye{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}}class vu extends Ye{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class bu extends Ye{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class On extends Ye{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Cu extends Ye{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}}class Su extends Ye{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var dr={configNotFound(e,t,r){return new pu(e,t,r)},configLoad(e,t,r){return new Nn(e,t,r)},configValidation(e,t,r){return new yu(e,t,r)},configMerge(e,t,r,i){return new wu(e,t,r,i)},envVar(e,t,r,i){return new ta(e,t,r,i)},fileSystem(e,t,r){return new vu(e,t,r)},typeGeneration(e,t,r){return new bu(e,t,r)},schemaValidation(e,t,r){return new On(e,t,r)},browserConfig(e,t,r,i){return new Cu(e,t,r,i)},plugin(e,t,r){return new Su(e,t,r)}};async function yw(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class ra{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return zo.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=un.env[c]||(l?un.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=un.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof ta)throw u;throw dr.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw dr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(un.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
120
|
-
|
|
121
|
-
`;for(let i of e)r+=`${i.key}
|
|
122
|
-
`,r+=` Type: ${i.type}
|
|
123
|
-
`,r+=` Description: ${i.description}
|
|
124
|
-
`,r+=` Example: ${i.example}
|
|
125
|
-
|
|
126
|
-
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
127
|
-
|
|
128
|
-
`;r+=`| Variable | Type | Description | Example |
|
|
129
|
-
`,r+=`|----------|------|-------------|----------|
|
|
130
|
-
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
131
|
-
`;return r}}function ww(e,t,r={}){return Eu(e,t,r,new WeakMap)}function Eu(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return xu(e,t,n,i);if(!Me(t)||!Me(e))return t;return Sw(e,t,r,i)}function xu(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return vw(e,t);case"smart":return bw(e,t,i);default:return t}return t}function vw(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Vo(n,i)))r.push(i);return r}function bw(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Me(t[0])&&Me(e[0]))return Cw(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Cw(e,t,r){let i=[...t];for(let n of e){if(!Me(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((l)=>Me(l)&&(a in l)&&l[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function Sw(e,t,r,i){let n=t;if(Me(n)&&i.has(n))return i.get(n);let s={...e};if(Me(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Me(a)&&Me(c))s[o]=Eu(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=xu(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function $u(e,t,r="replace"){return ww(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Vo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Vo(e[r],t[r]))return!1;return!0}if(Me(e)&&Me(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Vo(e[n],t[n]))return!1}return!0}return!1}function Me(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Tu{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=vn.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!hn(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new Nn(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Nn(e,Error("Configuration must export a valid object"),"unknown");let p={config:$u(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)vn.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?dr.configLoad(e,l):dr.configLoad(e,Error(String(l)))}};if(o)return zo.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Fo(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return yw(async()=>hn(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!hn(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=Fo(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=Fo(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!hn(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var xw=/^https?:\/\//;class Pu{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await zo.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Ew(t))throw new On(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new On(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:xw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ft=new Ln("bunfig",{showTags:!0});function $w(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Au{fileLoader=new Tu;envProcessor=new ra;validator=new Pu;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)ft.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw ft.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Dn.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let y=await this.loadHomeConfiguration(i,n,a,l,f,c);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(Be(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw dr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${$w(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?dn(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)ft.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)ft.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?dn(e,r,n):r,a=[Be(tr(),".config",e),Be(tr(),".config"),tr()];for(let c of a){if(n)ft.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)ft.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?dn(e,i,s):i;try{let c=Be(r,"package.json");if(!wp(c))return null;let l={};try{l=JSON.parse(vp(c,"utf8"))}catch(h){if(s)ft.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){f=l[d],u=d;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)ft.success(`Configuration loaded from package.json: ${u}`);return{config:$u(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ft.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:dn(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw dr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return vn.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);vn.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Be(e,"config"),Be(e,".config"),t?Be(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Be(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Be(tr(),".config",e),Be(tr(),".config"),tr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}var yx=new Au;function dn(e,t,r=!1){let i=new ra,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Dn.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}var wx=Be(Dn.cwd(),"config"),vx=Be(Dn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Tw={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:na(ia(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:na(ia(),".stacks","ssl","stacks.localhost.crt"),keyPath:na(ia(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Ru=Tw;import{execSync as Ir}from"node:child_process";import{homedir as kw}from"node:os";import{join as Nw}from"node:path";function Pw(e){return(e.includes("=")?e.split("=").pop():e).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Dt(e){try{return Qi(e)}catch{return null}}function sa(e){try{return uo(e)||null}catch{return null}}function oa(e,t){try{return t.every((r)=>mo(e,r))}catch{return!1}}function Aw(e,t,r=443){return ho(e,t,r)}function Rw(e){let t=[];for(let r of e.split(`
|
|
132
|
-
`)){let i=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(i)t.push(i[1].toUpperCase())}return t}var qe="-d -r trustRoot -p ssl -p basic",gt="/Library/Keychains/System.keychain",aa="rpx.localhost";function _r(){return Nw(kw(),"Library/Keychains/login.keychain-db")}function ca(){return[gt,_r()]}function ku(e,t=aa){let r=Ir(`security find-certificate -a -c "${t}" -Z "${e}" 2>/dev/null || true`,{encoding:"utf8"}),i=[];for(let n of r.split(`
|
|
133
|
-
`)){let s=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(s)i.push(s[1].toUpperCase())}return i}function Mn(e){if(process.platform!=="darwin")return;let t=Dt(e.caPath);if(!t)return;let r=e.commonName??aa,i=e.keychains??ca();for(let n of i)for(let s of ku(n,r)){if(s===t)continue;try{if(n.startsWith("/Library"))$t(`security delete-certificate -Z ${s} "${n}"`);else Ir(`security delete-certificate -Z ${s} "${n}"`,{stdio:"ignore"});m("ssl",`Removed stale Root CA ${s} from ${n}`,e.verbose)}catch{}}}function jr(e,t,r){if(process.platform!=="darwin")return Ur(e,r);try{let n=Ir(`security verify-cert -c "${e}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return m("ssl",`verify-cert ${t}: ${n?"trusted":"not trusted"}`,r?.verbose),n}catch{return!1}}function Ur(e,t){let r=Dt(e);if(!r)return!1;for(let i of ca())try{let n=Ir(`security find-certificate -a -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"});for(let s of n.split(`
|
|
134
|
-
`))if(s.toUpperCase().includes("SHA-256")){if(s.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${i}`,t?.verbose),!0}}catch{}return!1}function la(e,t){if(process.platform!=="darwin")return!1;let r=t.serverName;Mn({caPath:e,commonName:t.commonName,verbose:t.verbose});let i=_r();try{Ir(`security add-trusted-cert ${qe} -k "${i}" "${e}"`,{stdio:"ignore"})}catch{}try{$t(`security add-trusted-cert ${qe} -k ${gt} "${e}"`)}catch{return!1}return jr(e,r,{verbose:t.verbose})||Ur(e,{verbose:t.verbose})}var Tt=null,da=X(mr(),".stacks","ssl","rpx.localhost.crt");function Mu(e,t){return[...new Set(e.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function Iu(e,t,r){let i=X(mr(),".stacks","ssl"),n=[...new Set([t,...e,"rpx.localhost"])];return{https:{certPath:da,keyPath:X(i,"rpx.localhost.key"),caCertPath:X(i,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:n.map((s)=>({from:"localhost:1",to:s,cleanUrls:!1}))}}var Ow="rpx-root-ca.crt",Dw="rpx-root-ca.key";function ma(e){return{caCertPath:X(e,Ow),caKeyPath:X(e,Dw)}}function Vx(e){return{certPath:X(e,"rpx.localhost.crt"),keyPath:X(e,"rpx.localhost.key"),caCertPath:X(e,"rpx.localhost.ca.crt"),rootCA:ma(e)}}async function Fw(e,t){try{let[r,i]=await Promise.all([G.readFile(e.caCertPath,"utf8"),G.readFile(e.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!i.includes("PRIVATE KEY-----"))return m("ssl",`Root CA files at ${e.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:i}}catch(r){return m("ssl",`No existing Root CA at ${e.caCertPath} (${r.code||r}), will create one`,t),null}}function Nu(e){let t=new Set;t.add(e);let r=e.split(".");if(r.length>=3){let i=r[r.length-1],n=r[r.length-2],s=new Set(["co","com","org","net","ac","gov","edu"]);if(!(r.length===3&&i.length===2&&s.has(n)))t.add(`*.${r.slice(1).join(".")}`)}return Array.from(t)}function _u(e){let r=ha(e).replace(/\*/g,"wildcard"),i=X(mr(),".stacks","ssl"),n=i;if(typeof e?.https==="object")return n=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:i,{caCertPath:e.https.caCertPath||X(n,`${r}.ca.crt`),certPath:e.https.certPath||X(n,`${r}.crt`),keyPath:e.https.keyPath||X(n,`${r}.key`)};return{caCertPath:X(n,`${r}.ca.crt`),certPath:X(n,`${r}.crt`),keyPath:X(n,`${r}.key`)}}function Ou(e){let t=new Set;if(In(e))e.proxies.forEach((r)=>{let i=r.to||"rpx.localhost";Nu(i).forEach((n)=>t.add(n))});else if(Fu(e)){let r=e.to||"rpx.localhost";Nu(r).forEach((i)=>t.add(i))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function zx(e){m("ssl","Loading SSL configuration",e.verbose);let t={...Ru,...e};if(e.https=ya(t),!e.https?.keyPath&&!e.https?.certPath)return m("ssl","No SSL configuration provided",e.verbose),null;if(e.https?.keyPath&&!e.https?.certPath||!e.https?.keyPath&&e.https?.certPath){let r=!e.https?.keyPath?"keyPath":"certPath";throw m("ssl",`Invalid SSL configuration - missing ${r}`,e.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!e.https?.keyPath||!e.https?.certPath)return null;try{m("ssl","Reading SSL certificate files",e.verbose);let r=await G.readFile(e.https?.keyPath,"utf8"),i=await G.readFile(e.https?.certPath,"utf8");return m("ssl","SSL configuration loaded successfully",e.verbose),{key:r,cert:i}}catch(r){return m("ssl",`Failed to read certificates: ${r}`,e.verbose),null}}catch(r){throw m("ssl",`SSL configuration error: ${r}`,e.verbose),r}}async function Xx(e,t){if(Ve.platform==="darwin")return Bw(e,t);if(Ve.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((i)=>{r(`sudo cp "${e}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(n)=>{if(!n)i(!0);else r(`sudo cp "${e}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(s)=>{i(!s)})})})}catch{return!1}return!1}async function Bw(e,t){if(Ve.platform!=="darwin")return!1;let r=t?.serverName??"rpx.localhost",i=t?.verbose??!1;try{if(jr(e,r,{verbose:i}))return m("ssl","Root CA already trusted for SSL, skipping trust operation",i),!0;return m("ssl","Trusting Root CA for browsers (login + system keychains)",i),la(e,{serverName:r,verbose:i})}catch{return!1}}async function ju(e){if(Tt&&!e.forceRegenerate){m("ssl","Using cached SSL configuration",e.verbose);return}ga();let t=In(e)?e.proxies.map((f)=>f.to):[e.to];m("ssl",`Generating certificate for domains: ${t.join(", ")}`,e.verbose);let r=ya(e,e.verbose),i=r.basePath||X(mr(),".stacks","ssl");await G.mkdir(i,{recursive:!0});let n=ma(i),s=await Fw(n,e.verbose),o=!1;if(!s){if(e.verbose)A.info("Generating Root CA certificate (one-time)...");s=await lo(r);try{await Promise.all([G.writeFile(n.caCertPath,s.certificate),G.writeFile(n.caKeyPath,s.privateKey,{mode:384})]),o=!0,m("ssl",`Persisted Root CA at ${n.caCertPath}`,e.verbose)}catch(f){throw m("ssl",`Error saving Root CA files: ${f}`,e.verbose),Error(`Failed to save Root CA files: ${f}`)}}else m("ssl",`Reusing existing Root CA from ${n.caCertPath}`,e.verbose);if(e.verbose)A.info(`Generating host certificate for: ${t.join(", ")}`);let a=await fo({...r,rootCA:{certificate:s.certificate,privateKey:s.privateKey}});try{await Promise.all([G.writeFile(r.certPath,a.certificate),G.writeFile(r.keyPath,a.privateKey),G.writeFile(r.caCertPath,s.certificate)]),m("ssl","Certificate files saved successfully",e.verbose)}catch(f){throw m("ssl",`Error saving certificate files: ${f}`,e.verbose),Error(`Failed to save certificate files: ${f}`)}if(o?!1:await Uu(n.caCertPath,{verbose:e.verbose,regenerateUntrustedCerts:!0})){if(m("ssl","Root CA already trusted, skipping trust store update",e.verbose),e.verbose)A.success("Root CA is already trusted in system trust store");if(Tt={key:a.privateKey,cert:a.certificate,ca:s.certificate},e.verbose)A.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(e.verbose)A.info("Adding certificate to system trust store (may require sudo permission)...");let l=!1;if(Ve.platform==="darwin")try{Mn({caPath:n.caCertPath,verbose:e.verbose});let f=_r();try{fa(`security add-trusted-cert ${qe} -k "${f}" "${n.caCertPath}"`,{stdio:"ignore"})}catch{}if($t(`security add-trusted-cert ${qe} -k ${gt} "${n.caCertPath}"`),e.verbose)A.success("Successfully added Root CA to system trust store");l=!0;let u=X(i,"trust-rpx-cert.sh"),h=`#!/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 ${qe} -k ${gt} "${n.caCertPath}"
|
|
142
|
-
else
|
|
143
|
-
sudo security add-trusted-cert ${qe} -k ${gt} "${n.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 G.writeFile(u,h,{mode:493})}catch(f){if(e.verbose)A.warn(`Could not add Root CA to trust store automatically: ${f}`);let u=X(i,"trust-rpx-cert.sh"),h=`#!/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 ${qe} -k ${gt} "${n.caCertPath}"
|
|
155
|
-
else
|
|
156
|
-
sudo security add-trusted-cert ${qe} -k ${gt} "${n.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 G.writeFile(u,h,{mode:493}),e.verbose)A.info(`Created a trust helper script at: ${u}`),A.info(`If you're still having certificate issues, run: sh ${u}`)}else if(Ve.platform==="linux")try{let{exec:f}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",h=`
|
|
161
|
-
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
162
|
-
cp "${n.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
163
|
-
update-ca-certificates
|
|
164
|
-
echo "RPX Root CA installed. Please restart your browser."
|
|
165
|
-
`,d=X(ua.tmpdir(),`rpx-trust-${Date.now()}.sh`);await G.writeFile(d,h,{mode:493}),await new Promise((y)=>{f(`sudo bash "${d}"`,(g)=>{if(g){if(e.verbose)A.warn(`Could not trust certificates: ${g}`);y(!1)}else{if(e.verbose)A.success("Successfully added certificates to system trust store");y(!0)}})}),await G.unlink(d).catch(()=>{}),l=!0}catch(f){if(e.verbose)A.warn(`Failed to trust certificates: ${f}`)}else if(Ve.platform==="win32")try{let f=`
|
|
166
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${n.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
|
-
`,u=X(ua.tmpdir(),"rpx-trust.ps1");if(await G.writeFile(u,f),fa(`powershell -ExecutionPolicy Bypass -File "${u}"`),e.verbose)A.success("Successfully added certificate to Windows trust store");l=!0}catch(f){if(e.verbose)A.warn(`Could not trust certificate: ${f}`)}else try{await go(a,s.certificate,r),l=!0}catch(f){if(e.verbose)A.warn(`Could not add certificate to trust store: ${f}`)}if(Tt={key:a.privateKey,cert:a.certificate,ca:s.certificate},e.verbose)A.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!l&&e.verbose)A.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),A.warn("This will bypass the warning and you should only need to do it once")}function ga(){Tt=null}async function pa(e){if(!e)return null;if(Tt)return Tt;let t=ya(e);try{let[r,i,n]=await Promise.all([G.access(t.keyPath).then(()=>!0).catch(()=>!1),G.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?G.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!i)return m("ssl",`Certificate files don't exist: key=${r}, cert=${i}, paths: ${t.keyPath}, ${t.certPath}`,e.verbose),null;let s="regenerateUntrustedCerts"in e,o=e.regenerateUntrustedCerts,a=s?o!==!1:!0;m("ssl",`Trust check: hasFlag=${s}, flagValue=${o}, shouldCheckTrust=${a}`,e.verbose);let c=t.basePath||X(mr(),".stacks","ssl"),l=ma(c);if(!(a?await Uu(l.caCertPath,e):!0))return m("ssl","Root CA exists but is not trusted, will regenerate",e.verbose),null;let[u,h,d]=await Promise.all([G.readFile(t.keyPath,"utf8"),G.readFile(t.certPath,"utf8"),n&&t.caCertPath?G.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(d&&!d.includes("-----BEGIN CERTIFICATE-----"))return m("ssl","Invalid root CA certificate content, will regenerate",e.verbose),null;if(In(e))try{let{X509Certificate:y}=await import("node:crypto"),p=new y(h).subjectAltName||"",v=e.proxies.map((E)=>E.to).filter((E)=>!p.includes(`DNS:${E}`));if(v.length>0)return m("ssl",`Certificate missing SANs for: ${v.join(", ")}, will regenerate`,e.verbose),null}catch(y){m("ssl",`Could not verify cert SANs: ${y}`,e.verbose)}return m("ssl","Successfully loaded existing certificates",e.verbose),Tt={key:u,cert:h,ca:d},Tt}catch(r){return m("ssl",`Error checking existing certificates: ${r}`,e.verbose),null}}function ya(e,t){let r=ha(e);m("ssl",`Primary domain: ${r}`,t);let i=_u(e),n=X(mr(),".stacks","ssl");if(typeof e.https==="object"){let s=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:n,o={domain:r,hostCertCN:r,basePath:s,caCertPath:e.https.caCertPath||i.caCertPath,certPath:e.https.certPath||i.certPath,keyPath:e.https.keyPath||i.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:e.https.commonName||r,organizationName:e.https.organizationName||"Local Development",countryName:e.https.countryName||"US",stateName:e.https.stateName||"California",localityName:e.https.localityName||"Playa Vista",validityDays:e.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(Ou(e)).map((a)=>({type:2,value:a}))};if(Du(e.https.rootCA))o.rootCA=e.https.rootCA;return o}return{domain:r,hostCertCN:r,basePath:n,...i,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Ou(e)).map((s)=>({type:2,value:s}))}}async function Jx(e,t){let r=_u({to:e,verbose:t}),i=[r.caCertPath,r.certPath,r.keyPath];m("certificates","Attempting to clean up relating certificates",t),await Promise.all(i.map((n)=>Bu(n,t)))}async function Uu(e,t){try{if(m("ssl",`Checking if certificate is trusted: ${e}`,t?.verbose),Ve.platform==="darwin"){if(t?.serverName)return jr(e,t.serverName,{verbose:t?.verbose});return Ur(e,{verbose:t?.verbose})}else if(Ve.platform==="win32")try{let r=sa(e)||"";if(!r)return m("ssl","Could not extract certificate subject",t?.verbose),!1;let i=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(fa(i).toString().includes(r))return m("ssl","Certificate found in trusted root store",t?.verbose),!0;return m("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(Ve.platform==="linux")try{let r=Dt(e);if(!r)return m("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let i=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let n of i){let s;try{s=await G.readdir(n)}catch{continue}for(let o of s){let a=Dt(Lu.join(n,o));if(a&&a===r)return m("ssl",`Certificate fingerprint found in ${n}`,t?.verbose),!0}}return m("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return m("ssl",`Platform ${Ve.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return m("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}function Lw(e){return{enabled:e?.enabled??!1,path:e?.path??"/",interval:e?.interval??1e4,timeout:e?.timeout??2000,healthyThreshold:e?.healthyThreshold??2,unhealthyThreshold:e?.unhealthyThreshold??3}}function Mw(e){return(Array.isArray(e)?e:[e]).map((r)=>{let i=typeof r==="string"?{url:r}:r;return{url:i.url,weight:i.weight&&i.weight>0?i.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Wu(e){return(Array.isArray(e)?e:[e]).map((r)=>typeof r==="string"?r:r.url)}function Ku(e){if(!e)return"localhost:5173";let t=Array.isArray(e)?e[0]:e;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function Hu(e,t){return{upstreams:Mw(e),strategy:t?.strategy??"round-robin",healthCheck:Lw(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function Iw(e){let t=e.upstreams.filter((r)=>r.healthy);if(t.length===0&&e.upstreams.length===1)return e.upstreams;return t}function _w(e,t){let r=e.cursor%t.length;return e.cursor=(e.cursor+1)%t.length,t[r]}function jw(e,t){if(e.wrrCurrentWeights.length!==t.length)e.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((n,s)=>n+s.weight,0),i=0;for(let n=0;n<t.length;n++)if(e.wrrCurrentWeights[n]+=t[n].weight,e.wrrCurrentWeights[n]>e.wrrCurrentWeights[i])i=n;return e.wrrCurrentWeights[i]-=r,t[i]}function Uw(e){let t=e[0];for(let r=1;r<e.length;r++)if(e[r].activeConnections<t.activeConnections)t=e[r];return t}function Yu(e){let t=Iw(e);if(t.length===0)return;if(t.length===1)return t[0];switch(e.strategy){case"weighted-round-robin":return jw(e,t);case"least-connections":return Uw(t);case"round-robin":default:return _w(e,t)}}function _n(e,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=e.healthCheck.healthyThreshold)t.healthy=!0}function Wr(e,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=e.healthCheck.unhealthyThreshold)t.healthy=!1}function Ww(e){let t=e.lastIndexOf(":");if(t===-1)return{hostname:e,port:80};let r=Number(e.slice(t+1));return{hostname:e.slice(0,t),port:Number.isFinite(r)?r:80}}async function Kw(e,t){let{hostname:r,port:i}=Ww(t.url),n=new AbortController,s=setTimeout(()=>n.abort(),e.healthCheck.timeout);try{(await fetch(`http://${r}:${i}${e.healthCheck.path}`,{signal:n.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),_n(e,t)}catch{Wr(e,t)}finally{clearTimeout(s)}}function Vu(e){if(!e.healthCheck.enabled||e.healthCheckTimer||e.upstreams.length<2)return;let t=setInterval(()=>{for(let r of e.upstreams)Kw(e,r)},e.healthCheck.interval);t.unref?.(),e.healthCheckTimer=t}function wa(e){if(e.healthCheckTimer)clearInterval(e.healthCheckTimer),e.healthCheckTimer=null}import{createHash as Xu,timingSafeEqual as zu}from"node:crypto";import{readFileSync as Hw}from"node:fs";var Yw="/.well-known/acme-challenge/";function Kr(e,t){let r=Buffer.from(e,"utf8"),i=Buffer.from(t,"utf8");if(r.length!==i.length)return zu(r,r),!1;return zu(r,i)}function Vw(e,t){let r=(h)=>Xu("md5").update(h).digest(),i=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8"),s=r(Buffer.concat([i,n,i])),o=[i,Buffer.from("$apr1$","utf8"),n];for(let h=i.length;h>0;h-=16)o.push(s.subarray(0,Math.min(h,16)));for(let h=i.length;h>0;h>>=1)o.push(h&1?Buffer.from([0]):i.subarray(0,1));let a=r(Buffer.concat(o));for(let h=0;h<1000;h++){let d=[];if(d.push(h&1?i:a.subarray(0,16)),h%3)d.push(n);if(h%7)d.push(i);d.push(h&1?a.subarray(0,16):i),a=r(Buffer.concat(d))}let c="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",l=(h,d)=>{let y="",g=h;for(let p=0;p<d;p++)y+=c[g&63],g>>=6;return y},f=a,u="";return u+=l(f[0]<<16|f[6]<<8|f[12],4),u+=l(f[1]<<16|f[7]<<8|f[13],4),u+=l(f[2]<<16|f[8]<<8|f[14],4),u+=l(f[3]<<16|f[9]<<8|f[15],4),u+=l(f[4]<<16|f[10]<<8|f[5],4),u+=l(f[11],2),`$apr1$${t}$${u}`}function zw(e,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(e,t)}catch{return!1}if(t.startsWith("$apr1$")){let i=t.split("$")[2]??"";return Kr(Vw(e,i),t)}if(t.startsWith("{SHA}")){let r=Xu("sha1").update(e,"utf8").digest("base64");return Kr(`{SHA}${r}`,t)}return Kr(e,t)}function Xw(e){let t=new Map;for(let r of e.split(`
|
|
173
|
-
`)){let i=r.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf(":");if(n<=0)continue;t.set(i.slice(0,n),i.slice(n+1))}return t}function Ju(e){if(!e)return;let t=(e.realm??"").trim()||"Restricted",r=[];if(e.username)r.push({username:e.username,password:e.password??""});for(let s of e.users??[])if(s?.username)r.push({username:s.username,password:s.password??""});let i;if(e.htpasswdFile)try{i=Xw(Hw(e.htpasswdFile,"utf8"))}catch{i=void 0}if(r.length===0&&(!i||i.size===0))return;return{realm:t,verify:(s,o)=>{let a=!1;for(let c of r)if(Kr(s,c.username)&&Kr(o,c.password))a=!0;if(i){let c=i.get(s);if(c&&zw(o,c))a=!0}return a}}}function qu(e,t,r){if(t.startsWith(Yw))return;let i=e.headers.get("authorization")??"",n=i.indexOf(" "),s=n===-1?i:i.slice(0,n),o=n===-1?"":i.slice(n+1).trim();if(s.toLowerCase()==="basic"&&o){let c="";try{c=Buffer.from(o,"base64").toString("utf8")}catch{c=""}let l=c.indexOf(":");if(l>=0&&r.verify(c.slice(0,l),c.slice(l+1)))return}let a=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${a}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:Jw}=Bun,Hr=Symbol("rpx.pool.fallback"),jn=Symbol("rpx.pool.stale");var qw=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function Gw(e){return qw.has(e.toUpperCase())}var ba=Symbol("rpx.pool.timeout"),Ft=Symbol("rpx.pool.busy");function Qw(){let e=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(e)&&e>0?e:30000}function Zw(e){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:e*8}function ev(){let e=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(e)&&e>0?e:0}function tv(){let e=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(e)&&e>0?e:0}var Qu=1048576;function rv(){let e=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(e)&&e>0?e:256}var va=30000,iv=16384,Zu=262144,nv=2097152,sv=524288,ov=8192,av=4096,cv=new TextEncoder,eh=new TextDecoder,lv=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"]);class th{socket=null;buf=new Uint8Array(iv);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(e){let t=this.socket,r=t.write(e);while(r<e.length){if(this.closed)throw jn;await new Promise((i)=>{this.drainWaiter=i}),r+=t.write(e.subarray(r))}}wakeDrain(){let e=this.drainWaiter;if(e)this.drainWaiter=null,e()}push(e){if(this.bodyQueue){let t=e.length<=this.bodyRemaining?e.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(e.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<e.length)this.appendToBuf(e.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(e),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()>nv)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=sv)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(e){let t=this.len+e.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(e,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let e=this.waiter;if(e)this.waiter=null,e()}waitForData(e){if(this.len>e||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((e)=>{this.waiter=e})}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 rh{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=Qw();maxWaiters;checkoutIdleMs=ev();inUse=new Set;constructor(e,t,r,i=""){this.host=e;this.port=t;this.maxTotal=r;this.key=i;this.maxWaiters=Zw(r)}trackCheckout(e){if(e.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(e),this.ensureSweeper()}dial(){let e=new th;return Jw({hostname:this.host,port:this.port,socket:{data:(t,r)=>e.push(r),drain:()=>e.wakeDrain(),close:()=>e.markClosed(),end:()=>e.markClosed(),error:()=>e.markClosed(),connectError:()=>e.markClosed(),timeout:()=>e.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let i=tv();if(i>0)r.timeout?.(i);return e.socket=t,e})}acquireIdleSync(){while(this.idle.length){let e=this.idle.pop();if(!e.closed)return e.socket?.ref(),e.pos=0,e.len=0,this.trackCheckout(e),e;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Ft;let e=await this.waitForSlot();if(e===Ft)throw Ft;if(e)return e.pos=0,e.len=0,this.trackCheckout(e),e}this.open++;try{let e=await this.dial();return this.trackCheckout(e),e}catch(e){throw this.open--,this.wakeWaiter(),e}}waitForSlot(){return new Promise((e)=>{let t=!1,r=(s)=>{if(t)return;t=!0,clearTimeout(n),e(s)},i=(s)=>r(s),n=setTimeout(()=>{let s=this.waiters.indexOf(i);if(s!==-1)this.waiters.splice(s,1);r(Ft)},this.queueWaitMs);n.unref?.(),this.waiters.push(i)})}release(e){if(this.inUse.delete(e),e.closed){this.open--,this.wakeWaiter();return}e.clearStreaming(),e.compact(),e.fresh=!1;let t=this.waiters.shift();if(t){e.socket?.ref(),this.trackCheckout(e),t(e);return}e.idleSince=Date.now(),e.socket?.unref(),this.idle.push(e),this.ensureSweeper()}destroy(e){this.inUse.delete(e),e.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let e=this.waiters.shift();if(e)e(null)}ensureSweeper(){if(this.sweeper)return;let e=this.checkoutIdleMs>0?Math.min(va,this.checkoutIdleMs):va;this.sweeper=setInterval(()=>this.sweep(),e),this.sweeper.unref?.()}sweep(){let e=Date.now(),t=e-va;if(this.idle.length){let r=[];for(let i of this.idle)if(i.closed||i.idleSince<=t)i.destroy(),this.open--;else r.push(i);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=e-this.checkoutIdleMs;for(let i of this.inUse)if(!i.closed&&i.lastActivityAt>0&&i.lastActivityAt<=r)i.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&Un.get(this.key)===this)Un.delete(this.key)}}}var Un=new Map;function fv(e,t){let r=Un.get(e);if(!r){let i=e.lastIndexOf(":"),n=i===-1?e:e.slice(0,i),s=i===-1?80:Number(e.slice(i+1));r=new rh(n,s,t??rv(),e),Un.set(e,r)}return r}function Gu(e,t,r){for(let i=r+3;i<t;i++)if(e[i]===10&&e[i-1]===13&&e[i-2]===10&&e[i-3]===13)return i-3;return-1}function uv(e,t,r){let i=eh.decode(e.subarray(t,r)),n=i.indexOf(`\r
|
|
174
|
-
`),s=n===-1?i:i.slice(0,n),o=s.indexOf(" "),a=Number.parseInt(s.slice(o+1,o+5),10),c=s.startsWith("HTTP/1.0"),l=[],f=-1,u=!1,h=c,d=!1,y=!1,g=n===-1?i.length:n+2;while(g<i.length){let p=i.indexOf(`\r
|
|
175
|
-
`,g);if(p===-1)p=i.length;let w=i.slice(g,p);if(g=p+2,w==="")continue;let v=w.indexOf(":");if(v===-1)continue;let E=w.slice(0,v),R=w.slice(v+1).trim(),T=E.charCodeAt(0)|32;if(T===99||T===116||T===107){let N=E.toLowerCase();if(N==="content-length"){let P=/^\d+$/.test(R)?Number(R):Number.NaN;if(!Number.isSafeInteger(P)||f>=0&&f!==P)y=!0;else f=P;continue}if(N==="transfer-encoding"){if(R.toLowerCase().includes("chunked"))u=!0;continue}if(N==="connection"){let P=R.toLowerCase();if(P.includes("close"))h=!0;if(P.includes("keep-alive"))d=!0;continue}if(N==="keep-alive")continue}l.push([E,R])}if(c&&d)h=!1;if(u&&f>=0)f=-1;return{status:a,headerEnd:r,headers:l,contentLength:f,chunked:u,closeConn:h,malformed:y}}function hv(e,t){return t||e===204||e===304}async function ih(e){let{hostPort:t,method:r,path:i,reqHeaders:n,forwardedHost:s,clientIp:o,originOverride:a,body:c}=e,l=r==="HEAD",f=n.get("accept")?.toLowerCase()??"";if(n.get("expect")||n.get("upgrade")||f.includes("text/event-stream"))throw Hr;let u=null;if(c){let g=n.get("content-length"),p=g?Number.parseInt(g,10):Number.NaN;if(Number.isNaN(p)||p>Qu)throw Hr;if(u=await vv(c),u===null)throw Hr}let h=wv(r,i,n,t,s,o,a,u),d=h;if(u&&u.length)d=new Uint8Array(h.length+u.length),d.set(h),d.set(u,h.length);let y=fv(t,e.maxPerHost);for(let g=0;;g++){if(g>0)await new Promise((w)=>{setTimeout(w,g)});let p;try{p=y.acquireIdleSync()??await y.acquireOrDial()}catch(w){if(w!==Ft&&g<4)continue;throw w}try{let w=p.socket.write(d);if(w<d.length)await p.writeAll(d.subarray(w));return await mv(y,p,l,e.signal)}catch(w){let v=w===jn&&g<4&&(p.fresh||Gw(r));if(y.destroy(p),v)continue;if(w===jn)throw Error("upstream closed connection");throw w}}}async function dv(e){let t=Gu(e.buf,e.len,e.pos);while(t===-1){if(e.closed){if(e.timedOut)throw ba;if(e.len===e.pos)throw jn;throw Error("upstream closed mid-header")}if(e.len-e.pos>Zu)throw Error("upstream header block too large");await e.waitForData(e.len),t=Gu(e.buf,e.len,e.pos)}return t}async function mv(e,t,r,i){let n;for(;;){let o=await dv(t);if(n=uv(t.buf,t.pos,o),t.pos=o+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw e.destroy(t),Error("upstream sent malformed response framing");let s=n.headers;if(hv(n.status,r))return nh(e,t,n.closeConn),new Response(null,{status:n.status,headers:s});if(n.chunked)return new Response(yv(e,t,n.closeConn,i),{status:n.status,headers:s});if(n.contentLength>=0){if(t.len-t.pos>=n.contentLength){let a=t.pos+n.contentLength,c=t.len>a,l=null;if(n.contentLength>=ov)l=t.buf.subarray(t.pos,a),t.buf=new Uint8Array(av);else if(n.contentLength>0)l=t.buf.slice(t.pos,a);if(t.pos=0,t.len=0,n.closeConn||c)e.destroy(t);else e.release(t);return new Response(l,{status:n.status,headers:s})}return new Response(gv(e,t,n.contentLength,n.closeConn),{status:n.status,headers:s})}return new Response(pv(t),{status:n.status,headers:s})}function nh(e,t,r){if(r||t.pos!==t.len)e.destroy(t);else e.release(t)}function gv(e,t,r,i){let n=t.len-t.pos,s=n>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-n,t.queuedBytes=0,t.streamingBody=!0;let o=(a)=>{if(t.bodyQueue=null,i||t.len>0)e.destroy(t);else e.release(t);a.close()};return new ReadableStream({start(a){if(s)a.enqueue(s);if(t.bodyRemaining===0&&t.bodyQueue.length===0)o(a)},async pull(a){for(;;){let c=t.bodyQueue;if(c&&c.length>0){let l=c.shift();if(t.queuedBytes-=l.length,t.resumeIfDrained(),a.enqueue(l),t.bodyRemaining===0&&c.length===0)o(a);return}if(t.bodyRemaining===0){if(t.bodyQueue)o(a);return}if(t.closed){t.bodyQueue=null,e.destroy(t),a.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,e.destroy(t)}})}function pv(e){return e.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(e.len>e.pos){t.enqueue(e.buf.slice(e.pos,e.len)),e.pos=e.len,e.resumeIfDrained();return}if(e.closed){e.destroy(),t.close();return}await e.waitForData(e.len)}},cancel(){e.destroy()}})}function yv(e,t,r,i){t.streamingBody=!0;let n=0,s=!1,o=!1,a,c=()=>i?.removeEventListener("abort",l),l=()=>{if(o)return;o=!0,e.destroy(t);try{a?.close()}catch{}};async function f(u=!1){for(;;){for(let h=t.pos;h+1<t.len;h++)if(t.buf[h]===13&&t.buf[h+1]===10){let d=eh.decode(t.buf.subarray(t.pos,h));return t.pos=h+2,d}if(t.closed){if(u&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>Zu)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start(u){if(a=u,i?.aborted)l();else i?.addEventListener("abort",l,{once:!0})},async pull(u){try{for(;;){if(n>0){if(t.len===t.pos){if(t.closed){e.destroy(t),u.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let g=Math.min(n,t.len-t.pos);if(u.enqueue(t.buf.slice(t.pos,t.pos+g)),t.pos+=g,n-=g,t.resumeIfDrained(),n===0)s=!0;return}if(s)await f(),s=!1;let h=await f(!0);if(h===null){e.destroy(t),c(),u.close();return}let d=h.indexOf(";"),y=Number.parseInt(d===-1?h:h.slice(0,d),16);if(!Number.isInteger(y)||y<0){e.destroy(t),u.error(Error("upstream sent malformed chunk size"));return}if(y===0){for(;;)if(await f()==="")break;nh(e,t,r),c(),u.close();return}n=y}}catch(h){if(e.destroy(t),c(),!o)u.error(h)}},cancel(){o=!0,c(),e.destroy(t)}})}function wv(e,t,r,i,n,s,o,a){let c=s||"127.0.0.1",l=`${e} ${t} HTTP/1.1\r
|
|
176
|
-
host: ${i}\r
|
|
177
|
-
x-forwarded-for: ${c}\r
|
|
178
|
-
x-real-ip: ${c}\r
|
|
179
|
-
x-forwarded-proto: https\r
|
|
180
|
-
x-forwarded-host: ${n}\r
|
|
181
|
-
`;if(o!==void 0)l+=`origin: ${o}\r
|
|
182
|
-
`;let f=!1;for(let[u,h]of r){let d=u.toLowerCase();if(lv.has(d))continue;if(o!==void 0&&d==="origin")continue;if(d==="content-length")f=!0;l+=`${u}: ${h}\r
|
|
183
|
-
`}if(l+=`connection: keep-alive\r
|
|
184
|
-
`,a&&!f)l+=`content-length: ${a.length}\r
|
|
185
|
-
`;return l+=`\r
|
|
186
|
-
`,cv.encode(l)}async function vv(e){let t=e.getReader(),r=[],i=0;for(;;){let{done:o,value:a}=await t.read();if(o)break;if(a){if(i+=a.length,i>Qu)return t.cancel().catch(()=>{}),null;r.push(a)}}if(r.length===1)return r[0];let n=new Uint8Array(i),s=0;for(let o of r)n.set(o,s),s+=o.length;return n}function n$(e){let t=typeof e==="string"?{to:e}:e,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function sh(e,t,r){if(!e.preservePath)return e.to||"/";let i=`${t}${r}`;return i==="/"?`${e.to}/`:`${e.to}${i}`}import*as Ie from"node:path";function oh(e,t){if(typeof e==="string")return{dir:e,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:e.dir,spa:e.spa??!1,pathRewriteStyle:e.pathRewriteStyle??"directory",maxAge:e.maxAge??0,cleanUrls:t}}var bv={".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 Cv(e){let t=Ie.extname(e).toLowerCase();return bv[t]??"application/octet-stream"}function Sv(e){let t;try{t=decodeURIComponent(e)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ie.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function Ev(e,t){let r=Sv(e);if(r===null)return null;let i=Ie.posix.extname(r);if(t.cleanUrls&&i===".html"){let n=e.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ie.join(t.dir,r),redirectTo:n||"/"}}if(r===""||e.endsWith("/"))return{filePath:Ie.join(t.dir,r,"index.html")};if(i!=="")return{filePath:Ie.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ie.join(t.dir,`${r}.html`)};return{filePath:Ie.join(t.dir,r,"index.html")}}async function ah(e,t){let r=Ev(e,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let i=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",n=Bun.file(r.filePath);if(await n.exists())return new Response(n,{status:200,headers:{"Content-Type":Cv(r.filePath),"Cache-Control":i}});if(t.spa){let s=Ie.join(t.dir,"index.html"),o=Bun.file(s);if(await o.exists())return new Response(o,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var Ca="127.0.0.1";function xv(e,t){let r;try{r=t?.requestIP?.(e)?.address}catch{return Ca}if(!r)return Ca;return/^[0-9a-f.:]{1,45}$/i.test(r)?r:Ca}function $v(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var Tv=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),Pv=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],Av=1024;function Rv(e){if(!e)return!1;let t=null;for(let r of e.split(",")){let[i,...n]=r.trim().split(";"),s=i.trim().toLowerCase();if(s!=="gzip"&&s!=="*")continue;let o=1;for(let a of n){let c=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(a);if(c)o=Number.parseFloat(c[1])}if(s==="gzip")return Number.isFinite(o)&&o>0;t=o}return t!==null&&Number.isFinite(t)&&t>0}function kv(e){let t=e.get("vary");if(!t){e.set("vary","Accept-Encoding");return}if(!t.split(",").some((r)=>r.trim().toLowerCase()==="accept-encoding"))e.set("vary",`${t}, Accept-Encoding`)}function Nv(e,t){if(e.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||e.headers.has("range")||!Rv(e.headers.get("accept-encoding")))return t;let r=t.headers.get("content-type")?.toLowerCase()??"";if(!Pv.some((s)=>r.startsWith(s)))return t;let i=t.headers.get("content-length");if(i!==null){let s=Number.parseInt(i,10);if(Number.isFinite(s)&&s<Av)return t}let n=new Headers(t.headers);return n.set("content-encoding","gzip"),kv(n),n.delete("content-length"),n.delete("content-md5"),n.delete("content-digest"),n.delete("accept-ranges"),n.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:n})}function Ov(e){let t=e.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function uh(e,t){if(!t||t==="/")return e;if(e===t)return"/";if(e.startsWith(`${t}/`)){let r=e.slice(t.length);return r===""?"/":r}return e}function ch(e){if(e.upstreamPool)return Yu(e.upstreamPool);if(e.sourceHost)return{url:e.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function lh(e,t,r,i){let n=r?.url??t.sourceHost??"",o=t.stripBasePathPrefix??!1?uh(e,t.basePath):e,a=fh(o,t.pathRewrites);if(a)n=a.targetHost,o=a.targetPath,m("request",`Path rewrite: ${e} → ${n}${o}`,i);return{targetHost:n,targetPath:o}}function Dv(e){let t=e.indexOf("://"),r=t===-1?e.indexOf("/"):e.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let i=e.indexOf("?",r);if(i===-1)return{pathname:e.slice(r),search:""};return{pathname:e.slice(r,i),search:e.slice(i)}}function Sa(e,t,r){let i=async(n,s)=>{let{pathname:o,search:a}=Dv(n.url),c=Ov(n),l=xv(n,s),f=e(c,o);if(!f&&r){let w=await r(c,o,n);if(w instanceof Response)return w;if(w&&w.retry)f=e(c,o)}if(!f)return m("request",`No route found for host: ${c}`,t),new Response(`No proxy configured for ${c}`,{status:404});if(f.auth){let w=qu(n,o,f.auth);if(w)return m("request",`401 challenge for ${c}${o}`,t),w}if(f.redirect){let w=sh(f.redirect,o,a);return m("request",`${f.redirect.status} redirect ${c}${o} → ${w}`,t),new Response(null,{status:f.redirect.status,headers:{location:w}})}if(f.static){let v=f.stripBasePathPrefix??!0?uh(o,f.basePath):o;return ah(v,f.static)}if(n.headers.get("upgrade")?.toLowerCase()==="websocket"){let w=ch(f);if(!s||!w)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:v,targetPath:E}=lh(o,f,w,t),R=`ws://${v}${E}${a}`,T={};for(let[Z,ee]of n.headers)if(!Tv.has(Z.toLowerCase())&&Z.toLowerCase()!=="host")T[Z]=ee;T.host=v,T["x-forwarded-for"]=l,T["x-real-ip"]=l,T["x-forwarded-proto"]="https",T["x-forwarded-host"]=c;let N={targetUrl:R,forwardHeaders:T};if(s.upgrade(n,{data:N})){m("ws",`upgraded ${c}${E} → ${R}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let u=ch(f);if(!u)return new Response(`No upstream configured for ${c}`,{status:502});if(f.cleanUrls&&o.endsWith(".html")){let w=o.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:w}})}let{targetHost:h,targetPath:d}=lh(o,f,u,t),y=f.changeOrigin?`http://${h}`:void 0,g=n.body!=null&&n.method!=="GET"&&n.method!=="HEAD",p=f.upstreamPool;if(p)u.activeConnections++;try{let w=await ih({hostPort:h,method:n.method,path:`${d}${a}`,reqHeaders:n.headers,forwardedHost:c,clientIp:l,originOverride:y,body:n.body,signal:n.signal});if(p)_n(p,u);return w}catch(w){if(w===ba){if(m("request",`Upstream timeout for ${c}`,t),p)Wr(p,u);return new Response("Gateway Timeout",{status:504})}if(w===Ft)return m("request",`Upstream pool saturated for ${c}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(w===Hr||!g)try{let v=new Headers(n.headers);if(v.set("host",h),v.set("x-forwarded-for",l),v.set("x-real-ip",l),v.set("x-forwarded-proto","https"),v.set("x-forwarded-host",c),y!==void 0)v.set("origin",y);let E=await fetch(`http://${h}${d}${a}`,{method:n.method,headers:v,body:n.body,redirect:"manual"});if(p)_n(p,u);return E}catch(v){if(m("request",`Proxy error for ${c}: ${v}`,t),p)Wr(p,u);return new Response(`Proxy Error: ${v}`,{status:502})}if(m("request",`Proxy error for ${c}: ${w}`,t),p)Wr(p,u);return new Response(`Proxy Error: ${w}`,{status:502})}finally{if(p)u.activeConnections--}};return async(n,s)=>{try{let o=await i(n,s);return o?Nv(n,o):o}catch(o){return m("request",`Unhandled proxy handler error: ${o}`,t),new Response("Bad Gateway",{status:502})}}}function Ea(e){let t=new WeakMap,r=$v();return{open(i){let{targetUrl:n,forwardHeaders:s}=i.data,o;try{o=new WebSocket(n,{headers:s})}catch(c){m("ws",`failed to open upstream ${n}: ${c}`,e),i.close(1011,"upstream connect failed");return}o.binaryType="arraybuffer";let a={upstream:o,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(i,a),o.addEventListener("open",()=>{a.upstreamOpen=!0;for(let c of a.pending)o.send(c);a.pending=[],a.pendingBytes=0}),o.addEventListener("message",(c)=>{i.send(c.data)}),o.addEventListener("close",(c)=>{try{i.close(c.code||1000,c.reason||"")}catch{}}),o.addEventListener("error",()=>{m("ws",`upstream error for ${n}`,e);try{i.close(1011,"upstream error")}catch{}})},message(i,n){let s=t.get(i);if(!s)return;let o=typeof n==="string"?n:new Uint8Array(n);if(s.upstreamOpen){s.upstream.send(o);return}let a=typeof o==="string"?Buffer.byteLength(o):o.byteLength;if(s.pendingBytes+a>r){m("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,e);try{i.close(1009,"buffer limit")}catch{}try{s.upstream.close(1011,"client buffer overflow")}catch{}t.delete(i);return}s.pending.push(o),s.pendingBytes+=a},close(i,n,s){let o=t.get(i);if(!o)return;t.delete(i);try{o.upstream.close(n||1000,s||"")}catch{}}}}import*as dh from"node:fs";import*as mh from"node:path";var hh="/.well-known/acme-challenge/";function gh(e,t){if(!e||!t.startsWith(hh))return null;let r=t.slice(hh.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return dh.readFileSync(mh.join(e,r),"utf8")}catch{return null}}function Wn(e){return e.startsWith("*.")}function xa(e,t){if(!Wn(t))return!1;let r=t.slice(1);return e.length>r.length&&e.endsWith(r)}function ph(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!Wn(s))continue;if(xa(t,s)){let a=s.length-1;if(a>n)n=a,i=o}}return i}function Bt(e){if(!e||e==="/")return"/";let t=e.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function Fv(e,t){if(t==="/")return!0;if(e===t)return!0;return e.startsWith(`${t}/`)}function $a(e){let t=new Map;for(let i of e){let n=Bt(i.path),s=t.get(i.host);if(!s)s=new Map,t.set(i.host,s);s.set(n,i.route)}let r=new Map;for(let[i,n]of t){let s=[];for(let[o,a]of n)s.push({path:o,route:a});s.sort((o,a)=>a.path.length-o.path.length),r.set(i,s)}return r}function Ta(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!Wn(s))continue;if(xa(t,s)){let a=s.length-1;if(a>n)n=a,i=o}}return i}function Pa(e,t,r){let i=Ta(e,t);if(!i)return;for(let n of i)if(Fv(r,n.path))return n.route;return}import*as Yr from"node:fs/promises";import*as Aa from"node:path";function Vr(e){if(Array.isArray(e))return e.map((t)=>({...t,lowMemoryMode:!0}));return{...e,lowMemoryMode:!0}}function Bv(e){if(!e.endsWith(".crt"))return null;let t=e.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function Lv(e,t,r,i){try{let[n,s]=await Promise.all([Yr.readFile(t,"utf8"),Yr.readFile(r,"utf8")]);return{serverName:e,cert:n,key:s}}catch(n){return m("sni",`skipping ${e}: ${n.message}`,i),null}}async function Ra(e,t){let r=new Map,i=e.certsDirServerNames?new Set(e.certsDirServerNames):void 0;if(e.certsDir){let s=[];try{s=await Yr.readdir(e.certsDir)}catch(o){m("sni",`certsDir read failed (${e.certsDir}): ${o.message}`,t)}for(let o of s){let a=Bv(o);if(!a)continue;if(i&&!i.has(a))continue;let c=o.slice(0,-4);r.set(a,{certPath:Aa.join(e.certsDir,o),keyPath:Aa.join(e.certsDir,`${c}.key`)})}}if(e.domains)for(let[s,o]of Object.entries(e.domains))r.set(s,o);let n=[];for(let[s,o]of r){let a=await Lv(s,o.certPath,o.keyPath,t);if(a)n.push(a)}return n}import*as ze from"node:fs/promises";import*as Kn from"node:path";function ka(e=process.env){let t=e.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return e.INVOCATION_ID?"restart":"rebind"}var Mv="acme-account.key",Iv=60000,yh=4096;function _v(e,t){if(!t||t.length===0)return!1;return t.some((r)=>{let i=r.startsWith(".")?r.slice(1):r;return e===i||e.endsWith(`.${i}`)})}function wh(e){if(!e||e.length>253)return!1;if(e.includes("/")||e.includes(":")||e.includes(" "))return!1;if(e.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)}class Hn{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(e){this.config=e.config,this.certsDir=e.certsDir,this.onCertAdded=e.onCertAdded,this.http01Store=e.http01Store??Yi,this.issuer=e.issuer??Js,this.verbose=e.verbose??!1,this.negativeCacheMs=e.negativeCacheMs??Iv;for(let t of e.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(e){return this.certs.has(e)}async isApproved(e){if(!wh(e))return!1;if(_v(e,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(e)}catch(t){return m("on-demand",`ask(${e}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(e){if(!this.config.enabled)return!1;if(this.certs.has(e))return!0;if(!wh(e))return!1;let t=this.inFlight.get(e);if(t)return t;let r=this.negativeCache.get(e);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(e))return this.negativeCache.delete(e),!0;return m("on-demand",`${e} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let i=this.issue(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,i),i}async issue(e){if(this.certs.has(e))return!0;if(await this.loadFromDisk(e))return!0;if(!await this.isApproved(e))return m("on-demand",`refused issuance for ${e} (not approved)`,this.verbose),this.cacheNegative(e),!1;try{m("on-demand",`issuing cert for ${e} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[e],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(e,t.fullChainPem,t.keyPem);let r={serverName:e,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(e,r),this.negativeCache.delete(e),m("on-demand",`issued + installed cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(e),m("on-demand",`issuance for ${e} failed: ${t.message}`,this.verbose),!1}}cacheNegative(e){if(this.negativeCache.size>=yh){let t=Date.now();for(let[r,i]of this.negativeCache)if(i<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=yh){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(e,Date.now()+this.negativeCacheMs)}async loadFromDisk(e){let{certPath:t,keyPath:r}=this.pathsFor(e);try{let[i,n]=await Promise.all([ze.readFile(t,"utf8"),ze.readFile(r,"utf8")]),s={serverName:e,cert:i,key:n};return this.certs.set(e,s),m("on-demand",`adopted existing on-disk cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(e){return{certPath:Kn.join(this.certsDir,`${e}.crt`),keyPath:Kn.join(this.certsDir,`${e}.key`)}}async persist(e,t,r){await ze.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:i,keyPath:n}=this.pathsFor(e);await Promise.all([ze.writeFile(i,t,"utf8"),ze.writeFile(n,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Kn.join(this.certsDir,Mv)}async loadAccountKey(){try{return await ze.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(e){if(!e||this.accountKeyPem===e)return;this.accountKeyPem=e,await ze.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await ze.writeFile(this.accountKeyPath,e,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as jv,readdirSync as Uv,readFileSync as Wv,statSync as Kv}from"node:fs";import{homedir as Ch}from"node:os";import{isAbsolute as Hv,join as gr}from"node:path";var Sh=["~/Code"],Eh=["localhost","test"],Yv=1800000,Na={dirExists:(e)=>{try{return Kv(e).isDirectory()}catch{return!1}},fileExists:(e)=>{try{return jv(e)}catch{return!1}},readText:(e)=>{try{return Wv(e,"utf8")}catch{return null}}};function Oa(e,t){if(e==="~")return t;if(e.startsWith("~/"))return gr(t,e.slice(2));return e}function Vv(e){let t=e.indexOf(":");return(t===-1?e:e.slice(0,t)).toLowerCase()}function vh(e){return e.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function zv(e,t){for(let r of t){let i=`.${r}`;if(e.endsWith(i)){let n=e.slice(0,-i.length);if(n.length>0&&!n.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(n))return n}}return null}function Xv(e,t){let r=t.readText(gr(e,"rpx.site.json"));if(r)try{let n=JSON.parse(r);if(n&&typeof n==="object")return n}catch{}let i=t.readText(gr(e,"package.json"));if(i)try{let n=JSON.parse(i);if(n.rpx&&typeof n.rpx==="object")return n.rpx}catch{}return null}function Jv(e){let t=e.selfRegisters??!1;return{command:e.command,env:e.env,urlEnv:e.urlEnv,selfRegisters:t,routes:e.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function qv(e,t){let r=Xv(e,t);if(r?.command)return Jv(r);let i=t.fileExists(gr(e,"buddy")),n=t.readText(gr(e,"package.json")),s=null;if(n)try{s=JSON.parse(n)}catch{s=null}let o={...s?.dependencies??{},...s?.devDependencies??{}};if(i||Object.keys(o).some((c)=>c==="stacks"||c.startsWith("@stacksjs/")))return{command:i?"./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(s?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Da(e,t={}){let r={dirExists:t.dirExists??Na.dirExists,fileExists:t.fileExists??Na.fileExists,readText:t.readText??Na.readText},i=t.detect??qv,n=t.homeDir??Ch(),s=e.tlds??Eh,o=(e.roots??Sh).map((h)=>Oa(h,n)),a=e.idleTimeoutMs??Yv,c=new Map;for(let h of e.sites??[])c.set(h.to,h);let l=(h)=>h.idleTimeoutMs??a;function f(h){let d=ph(c,h);if(!d)return null;let y=Hv(d.dir)?d.dir:Oa(d.dir,n),g=d.selfRegisters??!1,p=d.routes??[];if(!g&&p.length===0)p=i(y,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let w=bh({...d.env??{}},void 0,h);return{host:h,id:vh(h),dir:y,command:d.command,env:w,routes:p,selfRegisters:g,idleTimeoutMs:l(d),source:"config"}}function u(h){let d=zv(h,s);if(!d)return null;for(let y of o){let g=gr(y,d);if(!r.dirExists(g))continue;let p=i(g,r);if(!p)continue;let w=p.selfRegisters??!1;return{host:h,id:vh(h),dir:g,command:p.command,env:bh({...p.env??{}},p.urlEnv,h),routes:w?[]:p.routes??[],selfRegisters:w,idleTimeoutMs:a,source:"discovered"}}return null}return{resolve(h){let d=Vv(h);if(!d)return null;return f(d)??u(d)}}}function Gv(e){try{return Uv(e,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function P$(e,t={}){let r=t.homeDir??Ch(),i=e.tlds??Eh,n=(e.roots??Sh).map((u)=>Oa(u,r)),s=t.readdir??Gv,o=Da(e,t),a=[],c=new Set,l=(u)=>{if(u&&!c.has(u.host))c.add(u.host),a.push(u)};for(let u of e.sites??[])if(!u.to.includes("*"))l(o.resolve(u.to));let f=i[0]??"localhost";for(let u of n)for(let h of s(u))l(o.resolve(`${h}.${f}`));return a}function bh(e,t,r){if(!t)return e;let i=`https://${r}`;for(let n of t)if(e[n]===void 0)e[n]=i;return e}import{closeSync as Rh,openSync as rb,readFileSync as ib}from"node:fs";import*as kh from"node:fs/promises";import{spawn as nb}from"node:child_process";import{homedir as sb}from"node:os";import*as Xr from"node:path";import*as Xe from"node:process";import*as Yn from"node:net";function $h(e,t,r){return m("port",`Checking if port ${e} is in use on ${t}`,r),new Promise((i)=>{let n=Yn.createServer(),s=setTimeout(()=>{m("port",`Checking port ${e} timed out, assuming it's in use`,r),n.close(),i(!0)},3000);n.once("error",(o)=>{if(clearTimeout(s),o.code==="EADDRINUSE")m("port",`Port ${e} is in use`,r),i(!0);else m("port",`Error checking port ${e}: ${o.message}`,r),i(!0)}),n.once("listening",()=>{clearTimeout(s),m("port",`Port ${e} is available`,r),n.close(),i(!1)});try{n.listen(e,t)}catch(o){clearTimeout(s),m("port",`Exception checking port ${e}: ${o}`,r),i(!0)}})}async function Fa(e,t,r,i=50){m("port",`Finding available port starting from ${e} (max attempts: ${i})`,r);let n=e,s=0;while(s<i){if(s++,!await $h(n,t,r))return m("port",`Found available port: ${n} after ${s} attempts`,r),n;m("port",`Port ${n} is in use, trying ${n+1} (attempt ${s}/${i})`,r),n++}throw Error(`Unable to find available port after ${i} attempts starting from ${e}`)}function xh(e,t,r=5000,i){return m("port",`Testing connection to ${t}:${e}`,i),new Promise((n)=>{let s=Yn.connect({host:t,port:e,timeout:r});s.once("connect",()=>{m("port",`Successfully connected to ${t}:${e}`,i),s.end(),n(!0)}),s.once("timeout",()=>{m("port",`Connection to ${t}:${e} timed out`,i),s.destroy(),n(!1)}),s.once("error",(o)=>{m("port",`Failed to connect to ${t}:${e}: ${o.message}`,i),s.destroy(),n(!1)})})}class Th{usedPorts=new Set;hostname;verbose;maxRetries;constructor(e="0.0.0.0",t,r=50){this.hostname=e,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(e,t=!1){if(this.usedPorts.has(e))return this.findNextAvailablePort(e+1,t);if(await $h(e,this.hostname,this.verbose))return this.findNextAvailablePort(e+1,t);if(t){if(!await xh(e,this.hostname,3000,this.verbose))return m("port",`Port ${e} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(e+1,t)}return this.usedPorts.add(e),e}async findNextAvailablePort(e,t=!1){let r=await Fa(e,this.hostname,this.verbose,this.maxRetries);if(t){if(!await xh(r,this.hostname,3000,this.verbose))if(r<e+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(e){m("port",`Releasing port ${e}`,this.verbose),this.usedPorts.delete(e)}}var k$=new Th;import*as Vn from"node:fs";import*as Ce from"node:fs/promises";import{homedir as Qv}from"node:os";import*as Ba from"node:path";import*as zn from"node:process";var Zv=/^[a-zA-Z0-9._-]+$/;function Pt(){return Ba.join(Qv(),".stacks","rpx","registry.d")}function La(e){return typeof e==="string"&&e.length>0&&e.length<=128&&Zv.test(e)}function Ma(e,t){if(!La(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Ba.join(e,`${t}.json`)}function Se(e){if(!Number.isInteger(e)||e<=0)return!1;try{return zn.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Ph(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,i=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,n=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",s=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&La(t.id)&&(i||n)&&typeof t.to==="string"&&t.to.length>0&&s&&r&&typeof t.createdAt==="string"}async function eb(e){await Ce.mkdir(e,{recursive:!0})}async function Ah(e,t=Pt(),r){if(!Ph(e))throw Error(`invalid registry entry: ${JSON.stringify(e)}`);await eb(t);let i=Ma(t,e.id),n=`${i}.tmp.${zn.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{await Ce.writeFile(n,s,{encoding:"utf8",mode:420}),await Ce.rename(n,i),m("registry",`wrote entry ${e.id} → ${i}`,r)}catch(o){throw await Ce.unlink(n).catch(()=>{}),o}}async function Ia(e,t=Pt(),r){let i=Ma(t,e);try{await Ce.unlink(i),m("registry",`removed entry ${e}`,r)}catch(n){if(n.code!=="ENOENT")throw n}}async function tb(e,t=Pt(),r){let i=Ma(t,e);try{let n=await Ce.readFile(i,"utf8"),s=JSON.parse(n);if(!Ph(s))return m("registry",`entry ${e} failed validation, removing`,r),await Ce.unlink(i).catch(()=>{}),null;return s}catch(n){if(n.code==="ENOENT")return null;if(n instanceof SyntaxError)return m("registry",`entry ${e} has invalid JSON, removing`,r),await Ce.unlink(i).catch(()=>{}),null;throw n}}async function pt(e=Pt(),t){let r;try{r=await Ce.readdir(e)}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.endsWith(".json"))continue;let s=n.slice(0,-5);if(!La(s))continue;let o=await tb(s,e,t);if(o)i.push(o)}return i}async function zr(e=Pt(),t){let r=await pt(e,t),i=0;for(let n of r){if(n.pid===void 0)continue;if(!Se(n.pid))m("registry",`GC: pid ${n.pid} for ${n.id} is dead, removing`,t),await Ia(n.id,e,t).catch(()=>{}),i++}return i}function Xn(e,t={}){let r=t.dir??Pt(),i=t.debounceMs??100,n=t.pollMs??Math.max(i*2,250),s=t.verbose;Vn.mkdirSync(r,{recursive:!0});let o=null,a=!1,c=null,l=!1,f=(p)=>JSON.stringify(p.map((w)=>({id:w.id,from:w.from,to:w.to,path:w.path,pid:w.pid,pathRewrites:w.pathRewrites,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,static:w.static,loadBalancer:w.loadBalancer})).sort((w,v)=>w.id.localeCompare(v.id))),u=()=>{if(o=null,a)return;pt(r,s).then((p)=>(c=f(p),e(p))).catch((p)=>{m("registry",`watcher onChange failed: ${p}`,s)})},h=()=>{if(a)return;if(o)clearTimeout(o);o=setTimeout(u,i)},y=setInterval(()=>{if(a||l)return;l=!0,pt(r,s).then((p)=>{if(f(p)!==c)h()}).catch((p)=>{m("registry",`watcher poll failed: ${p}`,s)}).finally(()=>{l=!1})},n),g=Vn.watch(r,{persistent:!0},(p,w)=>{if(w&&/\.tmp\.\d+\.\d+$/.test(w))return;h()});return g.on("error",(p)=>{m("registry",`watcher error: ${p}`,s)}),h(),{close:()=>{if(a=!0,o)clearTimeout(o);clearInterval(y),g.close()}}}var ob=120000,ab=200,cb=30000,lb=3000,fb=4000;class ja{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(e){this.resolver=e.resolver,this.registryDir=e.registryDir??Pt(),this.rpxDir=e.rpxDir??Xr.join(sb(),".stacks","rpx"),this.verbose=e.verbose??!1,this.startupTimeoutMs=e.startupTimeoutMs??ob,this.pollIntervalMs=e.pollIntervalMs??ab,this.restartDelayMs=e.restartDelayMs??lb,this.killGraceMs=e.killGraceMs??fb,this.launch=e.launcher??hb(this.verbose),this.probePort=e.probePort??ub,this.pickPort=e.pickPort??((r)=>Fa(r,"127.0.0.1")),this.isHostRoutable=e.isHostRoutable??(()=>!1),this.onSiteActivating=e.onSiteActivating,this.now=e.now??Date.now,this.writeEntry=e.writeEntry??Ah,this.removeEntry=e.removeEntry??Ia;let t=e.reapIntervalMs??cb;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(e){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(e);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(e),t=void 0;if(!t){let r=this.resolver.resolve(e);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:e};if(t.status==="failed")return{kind:"failed",host:e,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:e,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(e){try{this.onSiteActivating?.(e.host)}catch{}let t=new Map;if(!e.selfRegisters)for(let a of e.routes){if(t.has(a.portEnv))continue;let c=await this.pickPort(a.defaultPort??3000);t.set(a.portEnv,c)}let r=Xr.join(this.rpxDir,"sites",`${e.id}.log`);await kh.mkdir(Xr.dirname(r),{recursive:!0}).catch(()=>{});let i=this.buildEnv(e,t),n=null,s;try{n=this.launch({command:e.command,cwd:e.dir,env:i,logPath:r})}catch(a){s=`failed to spawn: ${a.message}`}let o={site:e,status:s?"failed":"starting",handle:n,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:s?this.now():0,error:s,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(e.host,o),s)return A.warn(`rpx: site ${e.host} ${s}`),o;return A.info(`rpx: booting ${e.host} → ${e.command} (${e.dir})`),n.exited.then((a)=>this.onProcessExit(o,a)).catch(()=>{}),o.ready=this.driveReadiness(o).catch((a)=>{m("sites",`readiness loop for ${e.host} threw: ${a}`,this.verbose)}),o}async onProcessExit(e,t){if(e.exited=!0,this.stopped||this.sites.get(e.site.host)!==e)return;if(e.status==="ready"){A.warn(`rpx: ${e.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(e.site.host);for(let r of e.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(e.status==="starting")this.fail(e,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(e){let{site:t}=e,r=this.now()+this.startupTimeoutMs,i=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,e.ports);while(this.now()<r&&!this.stopped){if(e.status!=="starting"||e.exited)return;if(await i()){if(await this.publishRoutes(e),e.status==="starting")e.status="ready",A.success(`rpx: ${t.host} ready`);return}await _a(this.pollIntervalMs)}if(e.status==="starting")this.fail(e,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(e,t){let r=e.routes.filter((n)=>n.readyGate??Bt(n.path)==="/").map((n)=>t.get(n.portEnv)).filter((n)=>typeof n==="number"),i=r.length>0?r:[...t.values()];return async()=>{for(let n of i)if(!await this.probePort(n))return!1;return i.length>0}}async publishRoutes(e){let{site:t,ports:r}=e;if(t.selfRegisters||t.routes.length===0)return;let i=t.routes.find((c)=>Bt(c.path)==="/")??t.routes[0],n=r.get(i.portEnv);if(n===void 0)return;let s=[];for(let c of t.routes){if(c===i)continue;let l=r.get(c.portEnv);if(l===void 0)continue;s.push({from:Bt(c.path),to:`localhost:${l}`,stripPrefix:c.stripPrefix??!1})}let o={id:t.id,from:`localhost:${n}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:s.length>0?s:void 0,pid:e.handle?.pid};await this.writeEntry(o,this.registryDir,this.verbose),e.routeIds=[t.id];let a=this.now()+2000;while(this.now()<a&&!this.isHostRoutable(t.host))await _a(50)}fail(e,t){e.status="failed",e.error=t,e.failedAt=this.now(),A.warn(`rpx: site ${e.site.host} failed — ${t}`),this.killProcess(e)}buildEnv(e,t){let r={};for(let[i,n]of Object.entries(Xe.env))if(typeof n==="string")r[i]=n;Object.assign(r,e.env);for(let[i,n]of t)r[i]=String(n);return r.RPX_SITE_HOST=e.host,r.RPX_SITE_URL=`https://${e.host}`,r}readLogTail(e,t=40){try{return ib(e.logPath,"utf8").split(`
|
|
187
|
-
`).slice(-t).join(`
|
|
188
|
-
`).trim()}catch{return""}}async stop(e){let t=this.sites.get(e);if(!t)return;this.sites.delete(e);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),A.info(`rpx: stopped ${e}`)}async killProcess(e){let t=e.handle;if(!t)return;e.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),_a(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let e=this.now();for(let[t,r]of this.sites){let i=r.site.idleTimeoutMs;if(i<=0)continue;let n=e-r.lastAccess;if((r.status==="ready"||e-r.startedAt>this.startupTimeoutMs)&&n>i)m("sites",`reaping ${t} (idle ${Math.round(n/1000)}s)`,this.verbose),await this.stop(t)}}list(){let e=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:e-t.startedAt,idleMs:e-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((e)=>this.stop(e)))}}function _a(e){return new Promise((t)=>setTimeout(t,e))}async function ub(e){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${e}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function hb(e){let t=db();return({command:r,cwd:i,env:n,logPath:s})=>{let o=rb(s,"a");try{let a=nb("sh",["-c",r],{cwd:i,env:n,detached:!0,stdio:["ignore",o,o],...t?{uid:t.uid,gid:t.gid}:{}}),c=a.pid;if(c===void 0)throw Error("spawn returned no pid");let l=new Promise((f)=>{a.once("exit",(u)=>{f(u)}),a.once("error",()=>{f(null)})}).finally(()=>{try{Rh(o)}catch{}});return m("sites",`spawned pid ${c}: sh -c ${r} (cwd ${i})`,e),{pid:c,exited:l,stop:(f="SIGTERM")=>{try{Xe.kill(-c,f)}catch{try{a.kill(f)}catch{}}}}}catch(a){try{Rh(o)}catch{}throw a}}}function db(){if(Xe.platform==="win32")return null;if(!(typeof Xe.getuid==="function"&&Xe.getuid()===0))return null;let t=Number.parseInt(Xe.env.SUDO_UID??"",10),r=Number.parseInt(Xe.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}function pr(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var mb=`
|
|
189
|
-
:root { color-scheme: light dark }
|
|
190
|
-
* { box-sizing: border-box }
|
|
191
|
-
body {
|
|
192
|
-
margin: 0; min-height: 100vh; display: grid; place-items: center;
|
|
193
|
-
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
194
|
-
background: #0b0c0f; color: #e7e9ee;
|
|
195
|
-
}
|
|
196
|
-
.card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
|
|
197
|
-
.row { display: flex; align-items: center; gap: .75rem; }
|
|
198
|
-
h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
|
|
199
|
-
p { margin: .5rem 0 0; color: #9aa1ad }
|
|
200
|
-
code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
|
|
201
|
-
pre {
|
|
202
|
-
margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
|
|
203
|
-
background: #16181d; border: 1px solid #23262d; border-radius: 8px;
|
|
204
|
-
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
|
|
205
|
-
white-space: pre-wrap; word-break: break-word;
|
|
206
|
-
}
|
|
207
|
-
.spinner {
|
|
208
|
-
width: 16px; height: 16px; border-radius: 50%;
|
|
209
|
-
border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
|
|
210
|
-
animation: spin .8s linear infinite;
|
|
211
|
-
}
|
|
212
|
-
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
213
|
-
@keyframes spin { to { transform: rotate(360deg) } }
|
|
214
|
-
`;function Nh(e,t,r){return`<!doctype html>
|
|
215
|
-
<html lang="en">
|
|
216
|
-
<head>
|
|
217
|
-
<meta charset="utf-8">
|
|
218
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
219
|
-
${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
|
|
220
|
-
<title>${pr(e)}</title>
|
|
221
|
-
<style>${mb}</style>
|
|
222
|
-
</head>
|
|
223
|
-
<body><main class="card">${t}</main></body>
|
|
224
|
-
</html>`}function Oh(e){let t=Math.max(1,Math.round(e.sinceMs/1000)),r=e.logTail?`<pre>${pr(e.logTail)}</pre>`:"",i=`
|
|
225
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${pr(e.host)}…</h1></div>
|
|
226
|
-
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
227
|
-
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
228
|
-
<p>Booting for ${t}s.</p>
|
|
229
|
-
${r}`;return new Response(Nh(`Starting ${e.host}`,i,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function Dh(e){let t=e.logTail?`<pre>${pr(e.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
|
|
230
|
-
<div class="row"><div class="dot"></div><h1>${pr(e.host)} failed to start</h1></div>
|
|
231
|
-
<p>${pr(e.error)}</p>
|
|
232
|
-
${t}
|
|
233
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(Nh(`${e.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as gb}from"node:child_process";import qr from"node:fs";import pb from"node:os";import Mh from"node:path";import*as Lt from"node:process";import{promisify as yb}from"node:util";var Jr=yb(gb);function Fh(e){let t=e.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var Ge=Lt.platform==="win32"?Mh.join(Lt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Bh="# rpx",wb="# Added by rpx",Gr=new Set(["127.0.0.1","::1"]),Ua=!1;async function Ih(e){if(Lt.platform==="win32")throw Error("Administrator privileges required on Windows");if(Lh()){let{stdout:i}=await Jr(e);return i}let t=Wa(),r=e.replace(/'/g,"'\\''");try{if(t){let{stdout:i}=await Jr(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`);return Ua=!0,i}if(Ua)try{let{stdout:i}=await Jr(`sudo -n sh -c '${r}'`);return i}catch(i){m("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:i}=await Jr(`sudo -n sh -c '${r}'`);return Ua=!0,i}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(i){throw Error(`Failed to execute sudo command: ${i.message}`)}}function Qr(e){let t=e.indexOf("#"),r=(t===-1?e:e.slice(0,t)).trim();if(!r)return null;let i=t===-1?"":e.slice(t+1).trim(),[n,...s]=r.split(/\s+/);if(!n||s.length===0)return null;let o=/^rpx(?::pid=(\d+))?$/.exec(i);return{address:n,names:s,comment:i,rpxPid:o?.[1]?Number.parseInt(o[1],10):null,rpxManaged:o!==null}}function _h(e,t){let r=Qr(e);return r!==null&&Gr.has(r.address)&&r.names.includes(t)}function vb(e,t){let r=new Set(t),i=new Set,n=e.split(`
|
|
234
|
-
`),s=[],o=0;while(o<n.length){let a=n[o];if(a.trim()===wb){let l=[],f=o+1;while(f<n.length){let h=n[f];if(h.trim()===""||h.trim().startsWith("#"))break;l.push(h),f++}let u=l.filter((h)=>{let d=Qr(h),y=d!==null&&Gr.has(d.address)&&d.names.some((g)=>r.has(g));if(y){for(let g of d.names)if(r.has(g))i.add(g)}return!y});if(u.length>0||l.length===0)s.push(a,...u);o=f;continue}let c=Qr(a);if(c?.rpxManaged&&Gr.has(c.address)&&c.names.some((l)=>r.has(l))){for(let l of c.names)if(r.has(l))i.add(l);o++;continue}s.push(a),o++}while(s.length>0&&s[s.length-1].trim()==="")s.pop();return{content:`${s.join(`
|
|
235
|
-
`)}
|
|
236
|
-
`,removed:[...i]}}function bb(e,t){let r=[],i=new Set,n=[];for(let s of e.split(`
|
|
237
|
-
`)){let o=Qr(s);if(o?.rpxManaged&&o.rpxPid!==null&&Gr.has(o.address)&&!t(o.rpxPid)){r.push(...o.names),i.add(o.rpxPid);continue}n.push(s)}while(n.length>0&&n[n.length-1].trim()==="")n.pop();return{content:`${n.join(`
|
|
238
|
-
`)}
|
|
239
|
-
`,removed:r,stalePids:[...i]}}async function Ka(e){try{return await qr.promises.readFile(Ge,"utf-8")}catch{return m("hosts","Reading hosts file requires elevated permissions, using sudo",e),Ih(`cat "${Ge}"`)}}async function Ha(e,t){let r=Mh.join(pb.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await qr.promises.writeFile(r,e,"utf8"),await Ih(`cat "${r}" | tee "${Ge}" > /dev/null`)}finally{await qr.promises.unlink(r).catch((i)=>{m("hosts",`Failed to remove temporary file: ${i}`,t)})}}async function Q$(e,t){let r=e.filter((n)=>!Fh(n)),i=e.filter((n)=>Fh(n));if(i.length>0)m("hosts",`Skipping /etc/hosts for loopback dev names: ${i.join(", ")}`,t);if(r.length===0)return;m("hosts",`Adding hosts: ${r.join(", ")}`,t),m("hosts",`Using hosts file at: ${Ge}`,t);try{let n;try{n=await Ka(t)}catch(l){throw console.log(" Could not read hosts file — skipping hosts setup"),m("hosts",`sudo read also failed: ${l}`,t),Error(`Cannot read hosts file: ${l}`)}let s=n.split(`
|
|
240
|
-
`),o=r.filter((l)=>!s.some((f)=>_h(f,l)));if(o.length===0){m("hosts","All hosts already exist in hosts file",t);return}let a=Lt.pid,c=o.map((l)=>`
|
|
241
|
-
127.0.0.1 ${l} ${Bh}:pid=${a}
|
|
242
|
-
::1 ${l} ${Bh}:pid=${a}`).join(`
|
|
243
|
-
`);try{await Ha(n+c,t),console.log(` Hosts updated: ${o.join(", ")}`)}catch(l){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),o.forEach((f)=>{console.log(` 127.0.0.1 ${f}`),console.log(` ::1 ${f}`)}),console.log(` Or run: sudo nano ${Ge}`)}}catch(n){m("hosts",`Failed to manage hosts file: ${n.message}`,t)}}async function Z$(e,t){m("hosts",`Removing hosts: ${e.join(", ")}`,t);try{let r;try{r=await Ka(t)}catch(s){throw m("hosts",`sudo read also failed: ${s}`,t),Error(`Cannot read hosts file: ${s}`)}let{content:i,removed:n}=vb(r,e);if(n.length===0){m("hosts","No matching rpx-managed hosts found to remove",t);return}try{await Ha(i,t),m("hosts",`Hosts removed successfully: ${n.join(", ")}`,t)}catch(s){m("hosts","Could not clean up hosts file automatically",t)}}catch(r){m("hosts",`Failed to clean up hosts file: ${r.message}`,t)}}async function eT(e,t){m("hosts",`Checking hosts: ${e}`,t);let r;try{r=await qr.promises.readFile(Ge,"utf-8")}catch(n){m("hosts",`Error reading hosts file: ${n}`,t);try{let s=Wa(),o;if(s)o=`echo '${s}' | sudo -S cat "${Ge}" 2>/dev/null`;else o=`sudo -n cat "${Ge}" 2>/dev/null || cat "${Ge}" 2>/dev/null || echo ""`;let{stdout:a}=await Jr(o);r=a}catch(s){return m("hosts",`Cannot read hosts file, assuming entries don't exist: ${s}`,t),e.map(()=>!1)}}let i=r.split(`
|
|
244
|
-
`);return e.map((n)=>i.some((s)=>_h(s,n)))}async function tT(e=Se){let t;try{t=await qr.promises.readFile(Ge,"utf-8")}catch{return[]}let r=[];for(let i of t.split(`
|
|
245
|
-
`)){let n=Qr(i);if(n?.rpxManaged&&n.rpxPid!==null&&Gr.has(n.address)&&!e(n.rpxPid))r.push(...n.names)}return[...new Set(r)]}async function Zr(e={}){let t=e.isAlive??Se,r;try{r=await Ka(e.verbose)}catch(o){return m("hosts",`stale hosts GC: cannot read hosts file: ${o}`,e.verbose),[]}let{content:i,removed:n,stalePids:s}=bb(r,t);if(n.length===0)return[];try{return await Ha(i,e.verbose),m("hosts",`stale hosts GC: removed ${n.join(", ")} (dead pid(s): ${s.join(", ")})`,e.verbose),[...new Set(n)]}catch(o){return m("hosts",`stale hosts GC: write failed: ${o}`,e.verbose),[]}}var Cb=5000;function Ee(){return Qe.join(Yh(),".stacks","rpx")}function Qn(e=Ee()){return Qe.join(e,"daemon.pid")}async function wr(e=Ee()){try{let t=await ge.readFile(Qn(e),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Sb(e=Ee()){let t=await wr(e);return t!==null&&Se(t)}async function Vh(e=Ee()){await ge.mkdir(e,{recursive:!0});let t=Qn(e);while(!0){try{let i=await ge.open(t,"wx");try{await i.write(`${C.pid}
|
|
246
|
-
`)}finally{await i.close()}return t}catch(i){if(i.code!=="EEXIST")throw i}let r=await wr(e);if(r!==null&&Se(r))throw Error(`rpx daemon already running (pid=${r})`);await ge.unlink(t).catch(()=>{})}}async function yr(e=Ee()){await ge.unlink(Qn(e)).catch(()=>{})}var qn=new Map;function Gn(e){for(let[t,r]of qn)if(!e.has(t))wa(r),qn.delete(t)}function Eb(e,t){let r=Wu(t??"localhost:1");if(e.upstreams.length!==r.length)return!1;return e.upstreams.every((i,n)=>i.url===r[n])}function zh(e){let t=e.cleanUrls??!1,r=Bt(e.path),i=Ju(e.auth);if(e.static)return{static:oh(e.static,t),cleanUrls:t,basePath:r,auth:i};let n=e.from??"localhost:1",s=Ku(n),o=new URL(s.startsWith("http")?s:`http://${s}`),a=qn.get(e.id);if(a&&!Eb(a,n))wa(a),a=void 0;if(!a)a=Hu(n,e.loadBalancer),Vu(a),qn.set(e.id,a);return{sourceHost:o.host,upstreamPool:a,cleanUrls:t,changeOrigin:e.changeOrigin??!1,pathRewrites:e.pathRewrites,basePath:r,auth:i}}function xb(e){return e.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??e[0]??"rpx.localhost"}async function Jn(e,t,r=[],i=!1){let n=await pt(t,e.verbose),s=[...new Set([...n.map((f)=>f.to).filter(Boolean),...r])],o=xb(s),a=[...new Set([o,...s,"rpx.localhost"])],c=Iu(s,o,e.verbose);if(typeof e.https==="object"&&typeof c.https==="object")c.https={...c.https,...e.https};let l=await pa(c);if(l&&(i||!oa(da,a)))m("daemon",`regenerating shared cert for host(s): ${a.join(", ")}`,e.verbose),ga(),l=null;if(!l)m("daemon","no usable cert on disk, generating one via tlsx",e.verbose),await ju({...c,forceRegenerate:!0}),l=await pa(c);if(!l)throw Error("failed to bootstrap TLS for rpx daemon");return l}async function $b(e,t,r,i){let n=C.env.SUDO_PASSWORD,s=C.env.HOME??Yh(),o=[C.execPath,...C.argv.slice(1)],a=[`HOME=${s}`,`PATH=${C.env.PATH??""}`];if(i)a.push("RPX_VERBOSE=1");for(let[y,g]of Object.entries(C.env))if(g!==void 0&&y!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(y))a.push(`${y}=${g}`);let c=n?["-S","-p","","env",...a,...o]:["-n","env",...a,...o];m("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,i);let l=Hh("sudo",c,{detached:!0,stdio:["pipe","ignore","ignore"]}),f=null,u=null;if(l.once("error",(y)=>{f=y}),l.once("exit",(y)=>{u=y??0}),n&&l.stdin)l.stdin.write(`${n}
|
|
247
|
-
`),l.stdin.end();l.unref();let h=Qn(e),d=Date.now()+15000;while(Date.now()<d){if(f)throw f;let y=await wr(e);if(y!==null&&Se(y)){if(i)A.success(`rpx daemon elevated to root (pid=${y}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:h,done:Promise.resolve(),stop:async()=>{try{C.kill(y,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(u!==null&&u!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${u}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((g)=>setTimeout(g,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${e})`)}var jh=!1;function Ya(){if(jh)return;jh=!0,C.on("uncaughtException",(e)=>{A.error(`rpx daemon: uncaught exception (continuing): ${e?.stack??e}`)}),C.on("unhandledRejection",(e)=>{A.error(`rpx daemon: unhandled rejection (continuing): ${e}`)})}function Xh(e,t,r){let i;try{i=new URL(e.url)}catch{return new Response("Bad Request",{status:400})}let n=(e.headers.get("host")??i.hostname).split(":")[0];if(i.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let s=t.challengeStore.handlePath(i.pathname);if(s!==void 0)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(r){let s=gh(r,i.pathname);if(s!=null)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(n))t.ensureCert(n).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${n}${i.pathname}${i.search}`}})}async function ET(e={}){Ya();let t=e.verbose??!1,r=e.rpxDir??Ee(),i=e.registryDir??Qe.join(r,"registry.d"),n=e.httpsPort??443,s=e.httpPort??80,o=e.hostname??"::",a=e.hostname==null,c=e.gcIntervalMs??Cb;if(C.env.RPX_DAEMON_WORKER==="1")return Ab({rpxDir:C.env.RPX_WORKER_RPXDIR??r,registryDir:C.env.RPX_WORKER_REGISTRYDIR??i,httpsPort:Number.parseInt(C.env.RPX_WORKER_HTTPSPORT??"",10)||n,hostname:C.env.RPX_WORKER_HOSTNAME??o,verbose:C.env.RPX_WORKER_VERBOSE==="1"||t});let l=n>0&&n<1024||s>0&&s<1024,f=typeof C.getuid==="function"&&C.getuid()===0;if(C.platform!=="win32"&&l&&!f)return $b(r,n,s,t);let u=Math.max(1,e.workers??(Number.parseInt(C.env.RPX_WORKERS??"",10)||1));if(u>1){if(e.onDemandSites?.enabled)A.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return Rb(e,{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:t,gcIntervalMs:c,workers:u})}let h=await Vh(r),d=new Map,y=(b,k)=>Pa(d,b,k);function g(b){d=$a(b.map(($e)=>({host:$e.to,path:$e.path,route:zh($e)}))),Gn(new Set(b.map(($e)=>$e.id)));let k=Array.from(d.keys());m("daemon",`routing table now covers ${k.length} host(s): ${k.join(", ")||"<empty>"}`,t)}await zr(i,t).catch((b)=>{m("daemon",`initial gc failed: ${b}`,t)}),await Zr({verbose:t}).catch((b)=>{m("daemon",`stale hosts GC on start failed: ${b}`,t)});let p=await pt(i,t);g(p),await br({rpxDir:r,verbose:t}).catch((b)=>{m("daemon",`DNS reconcile on start failed: ${b}`,t)}),await ei(p,{rpxDir:r,verbose:t,ownerPid:C.pid}).catch((b)=>{m("daemon",`DNS setup on start failed: ${b}`,t)});let w=[];if(e.productionCerts){if(w=await Ra(e.productionCerts,t),t&&w.length>0)A.info(`SNI: serving ${w.length} real cert(s): ${w.map((b)=>b.serverName).join(", ")}`)}let v=new Set,E=null,R;if(e.onDemandSites?.enabled){if(E=new ja({resolver:Da(e.onDemandSites),registryDir:i,rpxDir:r,verbose:t,startupTimeoutMs:e.onDemandSites.startupTimeoutMs,isHostRoutable:(b)=>Ta(d,b)!==void 0,onSiteActivating:(b)=>{ni(b)}}),R=async(b)=>{let k=await E.onRequest(b);switch(k.kind){case"ready":return{retry:!0};case"starting":return Oh({host:k.host,sinceMs:k.sinceMs,logTail:k.logTail});case"failed":return Dh({host:k.host,error:k.error,logTail:k.logTail});case"unknown":default:return}},t)A.info("rpx: on-demand sites enabled")}let T=Sa(y,t,R),N=Ea(t),P=null;if(w.length===0)P=await Jn(e,i);let Z=e.onDemandTls,ee=Z?.enabled?new Hn({config:Z,certsDir:Z.certsDir??e.productionCerts?.certsDir??Qe.join(r,"on-demand-certs"),initial:w,verbose:t,onCertAdded:(b)=>{if(ka()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>C.kill(C.pid,"SIGTERM"),10).unref();else O(b)}}):null;function Cr(b){if(b.length>0)return Vr(b.map((k)=>({serverName:k.serverName,cert:k.cert,key:k.key})));return Vr({key:P.key,cert:P.cert,ca:P.ca,requestCert:!1,rejectUnauthorized:!1})}function wt(b){try{return Bun.serve(b)}catch(k){let $e=k instanceof Error?k.message:String(k),Er=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test($e);if(!a||b.hostname!=="::"||!Er)throw k;return m("daemon",`no IPv6 on this host (${$e}); binding 0.0.0.0`,e.verbose),Bun.serve({...b,hostname:"0.0.0.0"})}}function Sr(b){return wt({port:n,hostname:o,reusePort:Kh(),tls:Cr(b),fetch(k,$e){return T(k,$e)},websocket:N,error(k){return m("daemon",`https server error: ${k}`,t),new Response(`Server Error: ${k.message}`,{status:500})}})}let ii=(b)=>[...new Set(b.map((k)=>k.to).filter(Boolean))],Mt=(b)=>{if(!P)return w;return Mu([...ii(b),...v,"rpx.localhost"],P)},Ze=Sr(ee?ee.sniEntries():w.length>0?w:Mt(p)),Rt=null,It=!1;async function O(b){if(Je)return;if(Rt=b,It)return;It=!0;try{while(!Je&&Rt){let k=Rt;Rt=null,m("daemon",`rebuilding :443 with ${k.length} SNI cert(s)`,t),Ze.stop(!1);let $e,Er=!1,rc=60,ld=500;for(let os=0;!Je&&!Er;os++)try{Ze=Sr(k),Er=!0;break}catch(fd){if($e=fd,os>=rc)break;await new Promise((ud)=>setTimeout(ud,Math.min(25*2**Math.min(os,4),ld)))}if(!Er)A.error(`rpx: CRITICAL — could not rebind :443 after ${rc} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${$e?.message}`)}}finally{It=!1}}let ke=null;if(s>0)ke=wt({port:s,hostname:o,fetch(b){return Xh(b,ee,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)A.success(`rpx daemon listening on https://${o}:${n}${ke?` (http→https on :${s})`:""}`),A.info(`pid file: ${h}`),A.info(`registry: ${i}`);async function is(b){if(Je||w.length>0||ee||!P)return;try{P=await Jn(e,i,[...v]),await O(Mt(b))}catch(k){m("daemon",`TLS sync on registry change failed: ${k}`,t)}}async function ni(b){if(Je||w.length>0||ee||!P||!b)return;if(v.has(b))return;v.add(b);try{P=await Jn(e,i,[...v],!0);let k=await pt(i,t);await O(Mt(k))}catch(k){m("daemon",`dev cert refresh for ${b} failed: ${k}`,t)}}let si=Xn((b)=>{g(b),is(b),ei(b,{rpxDir:r,verbose:t,ownerPid:C.pid}).catch((k)=>{m("daemon",`DNS sync on registry change failed: ${k}`,t)})},{dir:i,verbose:t}),_t=setInterval(()=>{zr(i,t).then((b)=>{if(b>0)m("daemon",`gc reaped ${b} stale entries`,t)}).catch((b)=>{m("daemon",`periodic gc failed: ${b}`,t)}),Zr({verbose:t}).then((b)=>{if(b.length>0)m("daemon",`gc reaped stale hosts entries: ${b.join(", ")}`,t)}).catch((b)=>{m("daemon",`periodic hosts gc failed: ${b}`,t)})},c);if(typeof _t.unref==="function")_t.unref();let Je=!1,ns,ss=new Promise((b)=>{ns=b});async function ec(){if(Je)return ss;if(Je=!0,clearInterval(_t),si.close(),await E?.stopAll().catch((b)=>{m("daemon",`site supervisor stopAll failed: ${b}`,t)}),Ze.stop(!1),ke?.stop(!1),await vr({rpxDir:r,verbose:t}).catch((b)=>{m("daemon",`DNS teardown failed: ${b}`,t)}),Gn(new Set),await yr(r),t)A.info("rpx daemon stopped");return ns(),ss}let tc=(b)=>{m("daemon",`received ${b}, shutting down`,t),ec().catch(()=>{})};return C.once("SIGINT",tc),C.once("SIGTERM",tc),{stop:ec,done:ss,httpsPort:typeof Ze.port==="number"?Ze.port:n,httpPort:ke&&typeof ke.port==="number"?ke.port:s,pidPath:h,ensureCert:(b)=>ee?ee.ensureCert(b):Promise.resolve(!1),listSites:()=>E?.list()??[]}}function Va(e){return Qe.join(e,"cluster-sni.json")}async function Uh(e,t,r){let i=Va(e),n=`${i}.${C.pid}.tmp`;await ge.writeFile(n,JSON.stringify({sni:t,dev:r}),"utf8"),await ge.rename(n,i)}async function Wh(e){try{return JSON.parse(await ge.readFile(Va(e),"utf8"))}catch{return{sni:[],dev:null}}}function Tb(e){if(e.sni.length>0)return Vr(e.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(e.dev)return Vr({key:e.dev.key,cert:e.dev.cert,ca:e.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function Pb(){let e=C.execPath,t=C.env.RPX_WORKER_BIN;if(t)return[e,t,"daemon:start"];let r=Qe.basename(e).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&C.argv[1])return[e,C.argv[1],"daemon:start"];return[e,"daemon:start"]}async function Ab(e){Ya();let{rpxDir:t,registryDir:r,httpsPort:i,hostname:n,verbose:s}=e,o=new Map,a=(N,P)=>Pa(o,N,P),c=(N)=>{o=$a(N.map((P)=>({host:P.to,path:P.path,route:zh(P)}))),Gn(new Set(N.map((P)=>P.id)))};c(await pt(r,s));let l=Sa(a,s),f=Ea(s),u=!1,h=(N)=>Bun.serve({port:i,hostname:n,reusePort:!0,tls:Tb(N),fetch(P,Z){return l(P,Z)},websocket:f,error(P){return m("daemon",`worker https error: ${P}`,s),new Response(`Server Error: ${P.message}`,{status:500})}}),d=h(await Wh(t));async function y(){if(u)return;let N=await Wh(t),P=null;for(let ee=0;ee<20&&!u;ee++)try{P=h(N);break}catch{await new Promise((Cr)=>setTimeout(Cr,25))}if(!P){m("daemon","worker reloadTls: could not bind new listener; keeping current",s);return}let Z=d;d=P,Z.stop(!1)}let g=Xn((N)=>c(N),{dir:r,verbose:s}),p=()=>{y().catch(()=>{})};C.on("SIGHUP",p);let w=()=>{let N=C.removeListener??C.off;if(typeof N==="function")N.call(C,"SIGHUP",p)},v,E=new Promise((N)=>{v=N});async function R(){if(u)return E;return u=!0,w(),g.close(),d.stop(!1),Gn(new Set),v(),E}let T=()=>{R().then(()=>C.exit(0)).catch(()=>C.exit(0))};if(C.once("SIGTERM",T),C.once("SIGINT",T),s)A.success(`rpx worker (pid ${C.pid}) serving :${i}`);return{stop:R,done:E,httpsPort:typeof d.port==="number"?d.port:i,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function Rb(e,t){Ya();let{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:a,gcIntervalMs:c,workers:l}=t,f=await Vh(r),u=[];if(e.productionCerts)u=await Ra(e.productionCerts,a);let h=null;if(u.length===0)h=await Jn(e,i);let d=h?{key:h.key,cert:h.cert,ca:Array.isArray(h.ca)?h.ca.join(`
|
|
248
|
-
`):h.ca}:null,y=!1,g=[];function p(O){for(let ke of g)try{ke.kill(O)}catch{}}async function w(O){await Uh(r,O,d),p("SIGHUP")}let v=e.onDemandTls,E=v?.enabled?new Hn({config:v,certsDir:v.certsDir??e.productionCerts?.certsDir??Qe.join(r,"on-demand-certs"),initial:u,verbose:a,onCertAdded:(O)=>{if(ka()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",a),setTimeout(()=>C.kill(C.pid,"SIGTERM"),10).unref();else w(O)}}):null;await Uh(r,E?E.sniEntries():u,d);let R=await pt(i,a);await br({rpxDir:r,verbose:a}).catch((O)=>{m("daemon",`DNS reconcile on start failed: ${O}`,a)}),await ei(R,{rpxDir:r,verbose:a,ownerPid:C.pid}).catch((O)=>{m("daemon",`DNS setup on start failed: ${O}`,a)}),await zr(i,a).catch(()=>{}),await Zr({verbose:a}).catch(()=>{});let T=Xn((O)=>{ei(O,{rpxDir:r,verbose:a,ownerPid:C.pid}).catch((ke)=>{m("daemon",`DNS sync on registry change failed: ${ke}`,a)})},{dir:i,verbose:a}),N=setInterval(()=>{zr(i,a).catch(()=>{}),Zr({verbose:a}).catch(()=>{})},c);N.unref?.();let P=null;if(s>0)P=Bun.serve({port:s,hostname:o,fetch(O){return Xh(O,E,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let Z=10,ee=60000,Cr=30000,wt=0,Sr=Date.now();function ii(){if(y)return;let O={...C.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:i,RPX_WORKER_HTTPSPORT:String(n),RPX_WORKER_HOSTNAME:o,RPX_WORKER_VERBOSE:a?"1":"0"},ke=Bun.spawn(Pb(),{env:O,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(is,ni){if(y)return;let si=g.indexOf(is);if(si!==-1)g.splice(si,1);let _t=Date.now();if(_t-Sr>ee)Sr=_t,wt=0;if(wt++,wt>Z){A.error(`rpx: worker keeps exiting (code ${ni}); giving up after ${Z} restarts in ${Math.round(ee/1000)}s`);return}let Je=Math.min(Cr,100*2**Math.min(wt,8));m("daemon",`worker exited (code ${ni}); respawning in ${Je}ms (restart ${wt}/${Z})`,a),setTimeout(ii,Je).unref?.()}});g.push(ke)}for(let O=0;O<l;O++)ii();if(a)A.success(`rpx coordinator listening on https://${o}:${n} via ${l} worker(s)${P?` (http→https on :${s})`:""}`),A.info(`pid file: ${f}`);let Mt,Ze=new Promise((O)=>{Mt=O});async function Rt(){if(y)return Ze;if(y=!0,clearInterval(N),T.close(),P?.stop(!1),p("SIGTERM"),await Promise.race([Promise.all(g.map((O)=>O.exited)),new Promise((O)=>setTimeout(O,3000))]),p("SIGKILL"),await vr({rpxDir:r,verbose:a}).catch((O)=>{m("daemon",`DNS teardown failed: ${O}`,a)}),await yr(r),await ge.unlink(Va(r)).catch(()=>{}),a)A.info("rpx coordinator stopped");return Mt(),Ze}let It=(O)=>{m("daemon",`coordinator received ${O}, shutting down`,a),Rt().catch(()=>{})};return C.once("SIGINT",It),C.once("SIGTERM",It),{stop:Rt,done:Ze,httpsPort:n,httpPort:s,pidPath:f,ensureCert:(O)=>E?E.ensureCert(O):Promise.resolve(!1),listSites:()=>[]}}function kb(){let e=C.execPath,t=Qe.basename(e).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&C.argv[1])return[e,C.argv[1],"daemon:start"];return[e,"daemon:start"]}async function xT(e={}){let t=e.rpxDir??Ee(),r=e.verbose??!1;await br({rpxDir:t,verbose:r}).catch((f)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${f}`,r)});let i=await wr(t);if(i!==null&&Se(i))return m("daemon",`ensureDaemonRunning: already running pid=${i}`,r),{pid:i,spawned:!1};if(i!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${i}`,r),await yr(t);await ge.mkdir(t,{recursive:!0});let n=e.spawnCommand??kb();if(n.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${n.join(" ")}`,r);let s=Hh(n[0],n.slice(1),{detached:!0,stdio:"ignore",cwd:e.spawnCwd??C.cwd(),env:e.spawnEnv?{...C.env,...e.spawnEnv}:C.env});s.unref();let o=null;s.once("error",(f)=>{o=f});let a=e.startupTimeoutMs??5000,c=e.pollIntervalMs??50,l=Date.now()+a;while(Date.now()<l){if(o)throw o;let f=await wr(t);if(f!==null&&Se(f))return m("daemon",`daemon registered with pid=${f}`,r),{pid:f,spawned:!0};await new Promise((u)=>setTimeout(u,c))}if(o)throw o;throw Error(`rpx daemon failed to start within ${a}ms (rpxDir=${t})`)}async function $T(e={}){let t=e.rpxDir??Ee(),r=e.verbose??!1,i=e.timeoutMs??5000,n=e.pollIntervalMs??50,s=e.forceAfterTimeout??!0,o=await wr(t);if(o===null||!Se(o)){if(o!==null)await yr(t);return await br({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:o,forced:!1}}try{C.kill(o,"SIGTERM")}catch(c){let l=c.code;if(l==="ESRCH")return await yr(t),{stopped:!1,pid:o,forced:!1};if(l==="EPERM")$t(`kill -TERM ${o}`);else throw c}let a=Date.now()+i;while(Date.now()<a){if(!Se(o))return m("daemon",`daemon pid=${o} stopped cleanly`,r),{stopped:!0,pid:o,forced:!1};await new Promise((c)=>setTimeout(c,n))}if(!s)throw Error(`rpx daemon (pid=${o}) did not exit within ${i}ms`);m("daemon",`daemon pid=${o} did not exit, escalating to SIGKILL`,r);try{C.kill(o,"SIGKILL")}catch(c){let l=c.code;if(l==="EPERM")$t(`kill -KILL ${o}`);else if(l!=="ESRCH")throw c}return await yr(t),await vr({rpxDir:t,verbose:r}).catch((c)=>{m("daemon",`DNS teardown after SIGKILL: ${c}`,r)}),{stopped:!0,pid:o,forced:!0}}async function TT(e={}){let t=e.rpxDir??Ee();if(await Sb(t))return;await br({rpxDir:t,verbose:e.verbose})}import*as At from"node:fs/promises";import{homedir as Nb}from"node:os";import*as za from"node:path";var Zn=1,Ob="dns-state.json",Jh=["com","test","dev","app","page","local","localhost","example","invalid"];function qh(){return za.join(Nb(),".stacks","rpx")}function Xa(e=qh()){return za.join(e,Ob)}async function es(e=qh()){try{let t=await At.readFile(Xa(e),"utf8"),r=JSON.parse(t);if(r.version!==Zn||!Array.isArray(r.resolvers))return null;return{version:Zn,resolvers:r.resolvers.filter((i)=>typeof i==="string"),domains:Array.isArray(r.domains)?r.domains.filter((i)=>typeof i==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Gh(e,t){await At.mkdir(e,{recursive:!0}),await At.writeFile(Xa(e),`${JSON.stringify(t,null,2)}
|
|
249
|
-
`,"utf8")}async function Ja(e){await At.rm(Xa(e),{force:!0})}function Qh(e){let t=e.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}var Db=new Set(["test","localhost","local","example","invalid","internal","home","lan"]);function Fb(e){let t=Qh(e);if(!t)return null;let r=t.split(".");if(r.length<2)return null;let i=r[r.length-1];if(Db.has(i))return r.slice(-2).join(".");return t}function qa(e){let t=new Set;for(let r of e){let i=Fb(r);if(i)t.add(i)}return Array.from(t).sort()}function Ga(e){let t=new Set;for(let r of e){let i=Qh(r);if(i)t.add(i)}return Array.from(t).sort()}var rs=15353,Bb="# managed-by: rpx",rd="/etc/resolver",xe=null,ts=new Set;function id(e){return{id:e.readUInt16BE(0),flags:e.readUInt16BE(2),qdcount:e.readUInt16BE(4),ancount:e.readUInt16BE(6),nscount:e.readUInt16BE(8),arcount:e.readUInt16BE(10)}}function nd(e,t,r=0){let i=[],n=t,s=0;while(!0){if(n>=e.length||++s>128)break;let o=e[n];if(o===0){n++;break}if((o&192)===192){if(n+1>=e.length||r>=10)break;let a=e.readUInt16BE(n)&16383,{name:c}=nd(e,a,r+1);if(c)i.push(c);n+=2;break}if(n++,n+o>e.length)break;i.push(e.subarray(n,n+o).toString("ascii")),n+=o}return{name:i.join("."),newOffset:n}}function Lb(e,t){let{name:r,newOffset:i}=nd(e,t),n=e.readUInt16BE(i),s=e.readUInt16BE(i+2);return{question:{name:r,type:n,class:s},newOffset:i+4}}function ti(e){let t=e.split("."),r=[];for(let i of t)r.push(Buffer.from([i.length])),r.push(Buffer.from(i,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function Mb(e,t,r){let i=[],n=Buffer.alloc(12);n.writeUInt16BE(e,0),n.writeUInt16BE(33152,2),n.writeUInt16BE(1,4),n.writeUInt16BE(1,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),i.push(n),i.push(ti(t.name));let s=Buffer.alloc(4);s.writeUInt16BE(t.type,0),s.writeUInt16BE(t.class,2),i.push(s),i.push(ti(t.name));let o=Buffer.alloc(10);if(o.writeUInt16BE(t.type,0),o.writeUInt16BE(1,2),o.writeUInt32BE(300,4),t.type===1){o.writeUInt16BE(4,8),i.push(o);let a=r.split(".").map((c)=>Number.parseInt(c,10));i.push(Buffer.from(a))}else if(t.type===28)o.writeUInt16BE(16,8),i.push(o),i.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return n.writeUInt16BE(33155,2),n.writeUInt16BE(0,6),Buffer.concat([n,ti(t.name),s]);return Buffer.concat(i)}function Ib(e,t){let r=[],i=Buffer.alloc(12);i.writeUInt16BE(e,0),i.writeUInt16BE(33155,2),i.writeUInt16BE(1,4),i.writeUInt16BE(0,6),i.writeUInt16BE(0,8),i.writeUInt16BE(0,10),r.push(i),r.push(ti(t.name));let n=Buffer.alloc(4);return n.writeUInt16BE(t.type,0),n.writeUInt16BE(t.class,2),r.push(n),Buffer.concat(r)}async function _b(e,t){if(yt.platform!=="darwin")return!1;let r=Ga(e);if(r.length===0)return!1;if(xe){for(let i of r)ts.add(i);return m("dns","DNS server already running — merged domains",t),!0}return ts=new Set(r),new Promise((i)=>{xe=Zh.createSocket("udp4"),xe.on("error",(n)=>{m("dns",`DNS server error: ${n.message}`,t),xe?.close(),xe=null,i(!1)}),xe.on("message",(n,s)=>{try{let o=id(n),{question:a}=Lb(n,12);m("dns",`Query for ${a.name} type ${a.type} from ${s.address}`,t);let c=a.name.toLowerCase(),l=!1;for(let u of ts)if(c===u||c.endsWith(`.${u}`)){l=!0;break}let f;if(l&&(a.type===1||a.type===28))f=Mb(o.id,a,"127.0.0.1"),m("dns",`Responding with localhost for ${a.name}`,t);else f=Ib(o.id,a),m("dns",`NXDOMAIN for ${a.name}`,t);xe?.send(f,s.port,s.address)}catch(o){m("dns",`Error processing DNS query: ${o}`,t)}}),xe.on("listening",()=>{let n=xe?.address();m("dns",`DNS server listening on ${n?.address}:${n?.port}`,t),i(!0)});try{xe.bind(rs,"127.0.0.1")}catch(n){m("dns",`Failed to bind DNS server: ${n}`,t),i(!1)}})}function sd(e){if(xe)m("dns","Stopping DNS server",e),xe.close(),xe=null,ts=new Set}function BT(){return xe!==null}async function jb(e,t=500){let r=e.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((i)=>{let n=Zh.createSocket("udp4"),s=setTimeout(()=>{n.close(),i(!1)},t);n.on("message",(a)=>{clearTimeout(s),n.close();try{let c=id(a);i(c.ancount>0)}catch{i(!1)}}),n.on("error",()=>{clearTimeout(s),n.close(),i(!1)});let o=Ub(r,1);n.send(o,rs,"127.0.0.1",(a)=>{if(a)clearTimeout(s),n.close(),i(!1)})})}function Ub(e,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let i=Buffer.concat([ti(e),Buffer.from([0,t,0,1])]);return Buffer.concat([r,i])}function Wb(){return`${Bb}
|
|
250
|
-
nameserver 127.0.0.1
|
|
251
|
-
port ${rs}
|
|
252
|
-
`}function ri(e){return td.join(rd,e)}function Kb(e){return e.includes("127.0.0.1")&&e.includes(String(rs))}async function Hb(e){try{return await ed.readFile(ri(e),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Qa(e){if(yt.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:i}=await import("./chunk-t3s94va5.js");if(!i()&&!r()){m("dns","Cannot flush DNS cache without SUDO_PASSWORD",e);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),m("dns","DNS cache flushed",e)}catch(n){m("dns",`Could not flush DNS cache: ${n}`,e)}}function od(e){if(!/^[a-z0-9.-]+$/.test(e))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(e)}`)}async function Yb(e,t){od(e);let{execSudoSync:r}=await import("./chunk-t3s94va5.js"),i=Wb().replace(/\n/g,"\\n"),n=`bash -c 'mkdir -p ${rd} && printf "%b" "${i}" > ${ri(e)}'`;r(n),m("dns",`Created ${ri(e)}`,t)}async function Vb(e,t){od(e);let{execSudoSync:r}=await import("./chunk-t3s94va5.js");r(`rm -f ${ri(e)}`),m("dns",`Removed ${ri(e)}`,t)}async function LT(e,t){return cd({domains:t??[],verbose:e})}async function zb(e,t){if(yt.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:i}=await import("./chunk-t3s94va5.js");if(!i()&&!r())return m("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let n of e)await Yb(n,t);return await Qa(t),!0}catch(n){return m("dns",`Failed to create resolver file: ${n}`,t),!1}}async function Za(e,t){if(yt.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:i}=await import("./chunk-t3s94va5.js");if(!i()&&!r())return;try{for(let n of e)await Vb(n,t);await Qa(t)}catch(n){m("dns",`Failed to remove resolver files: ${n}`,t)}}async function ad(e){if(yt.platform!=="darwin")return[];let t=[];for(let r of Jh){let i=await Hb(r);if(i&&Kb(i))await Za([r],e),t.push(r)}return t}async function cd(e){let t=e.rpxDir??Ee(),r=Ga(e.domains);if(r.length===0)return!1;let i=qa(r),n=await _b(r,e.verbose);if(!n){let a=r[0];if(a&&await jb(a))n=!0;else m("dns","Dev DNS server not available on 127.0.0.1:15353",e.verbose)}if(!n)return!1;if(!await zb(i,e.verbose))return!1;let o={version:Zn,resolvers:i,domains:r,ownerPid:e.ownerPid??yt.pid,updatedAt:new Date().toISOString()};return await Gh(t,o),!0}async function ei(e,t={}){let r=e.map((c)=>c.to).filter(Boolean),i=t.rpxDir??Ee(),n=qa(r),a=((await es(i))?.resolvers??[]).filter((c)=>!n.includes(c));if(a.length>0)await Za(a,t.verbose);if(n.length===0){sd(t.verbose),await Ja(i);return}await cd({domains:r,rpxDir:i,verbose:t.verbose,ownerPid:t.ownerPid??yt.pid})}async function vr(e={}){let t=e.rpxDir??Ee();sd(e.verbose);let i=(await es(t))?.resolvers??[];await Za(i,e.verbose),await ad(e.verbose),await Ja(t)}async function MT(e){await vr({verbose:e})}async function br(e={}){let t=e.rpxDir??Ee(),r=await es(t),i=r?.ownerPid!=null&&Se(r.ownerPid);if(r&&!i){m("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,e.verbose),await vr(e);return}let n=await ad(e.verbose);if(n.length>0)m("dns",`reconcile: removed legacy TLD resolvers: ${n.join(", ")}`,e.verbose);await Qa(e.verbose)}
|
|
253
|
-
export{A as a,Ru as b,Pw as c,Dt as d,sa as e,oa as f,Aw as g,Rw as h,qe as i,gt as j,aa as k,_r as l,ca as m,ku as n,Mn as o,jr as p,Ur as q,la as r,da as s,Mu as t,Iu as u,ma as v,Vx as w,zx as x,Xx as y,ju as z,ga as A,pa as B,ya as C,Jx as D,Uu as E,Ku as F,Hu as G,Yu as H,_n as I,Wr as J,Vu as K,wa as L,Xw as M,Ju as N,qu as O,n$ as P,sh as Q,oh as R,Cv as S,Sv as T,Ev as U,ah as V,uh as W,Sa as X,Ea as Y,hh as Z,gh as _,Wn as $,xa as aa,ph as ba,Bt as ca,Fv as da,$a as ea,Ta as fa,Pa as ga,Vr as ha,Bv as ia,Ra as ja,ka,_v as la,wh as ma,Hn as na,Oa as oa,vh as pa,zv as qa,Xv as ra,qv as sa,Da as ta,P$ as ua,$h as va,Fa as wa,Th as xa,k$ as ya,Pt as za,La as Aa,Se as Ba,Ah as Ca,Ia as Da,tb as Ea,pt as Fa,zr as Ga,Xn as Ha,ja as Ia,pr as Ja,Oh as Ka,Dh as La,Bh as Ma,Qr as Na,_h as Oa,vb as Pa,bb as Qa,Q$ as Ra,Z$ as Sa,eT as Ta,tT as Ua,Zr as Va,Zn as Wa,Jh as Xa,Qh as Ya,Fb as Za,qa as _a,Ga as $a,rs as ab,Bb as bb,_b as cb,sd as db,BT as eb,jb as fb,ri as gb,Kb as hb,LT as ib,ad as jb,cd as kb,ei as lb,vr as mb,MT as nb,br as ob,Ee as pb,Qn as qb,wr as rb,Sb as sb,Vh as tb,yr as ub,ET as vb,kb as wb,xT as xb,$T as yb,TT as zb};
|