@stacksjs/rpx 0.11.7 → 0.11.9
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 +144 -142
- package/dist/cert-inspect.d.ts +15 -0
- package/dist/daemon-runner.d.ts +3 -0
- package/dist/https.d.ts +32 -2
- package/dist/index.d.ts +23 -0
- package/dist/index.js +81 -78
- package/dist/macos-trust.d.ts +40 -0
- package/package.json +1 -1
- package/src/cert-inspect.ts +69 -0
- package/src/daemon-runner.ts +15 -2
- package/src/daemon.ts +29 -7
- package/src/https.ts +94 -53
- package/src/index.ts +25 -0
- package/src/macos-trust.ts +175 -0
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{a as G,b as Tn,c as Qe,d as a,e as hS,f as fi,g as lS,h as Ws,i as tc,j as ka,k as Pr,l as Ys,m as sS,n as Hs,o as Is}from"./chunk-jpf41gb9.js";import{execSync as u0}from"node:child_process";import*as Ti from"node:http";import*as Vs from"node:http2";import*as gs from"node:net";import*as O from"node:process";var S={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};var _n=(t,i)=>(n)=>`\x1B[${t}m${n}\x1B[${i}m`,jt={bold:_n(1,22),dim:_n(2,22),green:_n(32,39),cyan:_n(36,39)};import{homedir as pf}from"node:os";import{join as Qf,resolve as $m}from"node:path";import{existsSync as Sc,statSync as Rc}from"fs";import{existsSync as Ps,mkdirSync as C0,readdirSync as J0,readFileSync as vs,writeFileSync as _0}from"fs";import{homedir as Si}from"os";import{dirname as d0,resolve as Bt}from"path";import cr from"process";import{existsSync as Bc,statSync as Nc}from"fs";import{existsSync as Wf,mkdirSync as ps,readdirSync as Qs,writeFileSync as t$}from"fs";import{homedir as Ri}from"os";import{dirname as Fc,resolve as $t}from"path";import wi from"process";import{join as i$,relative as n$,resolve as Cc}from"path";import gn from"process";import{existsSync as hh,mkdirSync as q0,readdirSync as D0,writeFileSync as x0}from"fs";import{homedir as wf}from"os";import{dirname as k0,resolve as st}from"path";import en from"process";import{join as r$,relative as f$,resolve as Jc}from"path";import bn from"process";import{existsSync as lh,mkdirSync as X0,readdirSync as P0,writeFileSync as v0}from"fs";import{dirname as Q0,resolve as Xn}from"path";import Yf from"process";import{Buffer as ei}from"buffer";import{createCipheriv as e$,createDecipheriv as c$,randomBytes as yf}from"crypto";import{closeSync as uf,createReadStream as _c,createWriteStream as h$,existsSync as af,fsyncSync as Uc,openSync as jc,writeFileSync as l$}from"fs";import{access as s$,constants as dc,mkdir as $$,readdir as Un,rename as Wc,stat as Bi,unlink as jn,writeFile as Af}from"fs/promises";import{join as Ni}from"path";import nt from"process";import{pipeline as w$}from"stream/promises";import{createGzip as Yc}from"zlib";import Fi from"process";import Ot from"process";import{Buffer as qt}from"buffer";import{createCipheriv as y$,createDecipheriv as u$,randomBytes as mf}from"crypto";import{closeSync as Ef,createReadStream as Ic,createWriteStream as a$,existsSync as dn,fsyncSync as Zc,openSync as Hc,writeFileSync as A$}from"fs";import{access as m$,constants as Mc,mkdir as E$,readdir as Wn,rename as zc,stat as Ci,unlink as Yn,writeFile as Tf}from"fs/promises";import{isAbsolute as T$,join as Ji,resolve as S$}from"path";import _ from"process";import{pipeline as R$}from"stream/promises";import{createGzip as Gc}from"zlib";import _i from"process";import Lt from"process";import In from"process";import{existsSync as Zn}from"fs";import{resolve as Sf}from"path";import{existsSync as B$}from"fs";import{existsSync as N$,readdirSync as F$}from"fs";import{extname as Rf,resolve as Kc}from"path";import C$ from"process";import{join as J$,relative as _$,resolve as qc}from"path";import Pn from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as U$,createDecipheriv as j$,randomBytes as Bf}from"crypto";import{closeSync as Nf,createReadStream as Dc,createWriteStream as d$,existsSync as Hn,fsyncSync as xc,openSync as Oc,writeFileSync as W$}from"fs";import{access as Y$,constants as Lc,mkdir as I$,readdir as Mn,rename as kc,stat as Ui,unlink as zn,writeFile as Ff}from"fs/promises";import{isAbsolute as Z$,join as ji,resolve as H$}from"path";import U from"process";import{pipeline as M$}from"stream/promises";import{createGzip as oc}from"zlib";import di from"process";import kt from"process";import Kn from"process";import{existsSync as qn}from"fs";import{resolve as df}from"path";import{existsSync as iy}from"fs";class eh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Sc(t))return!0;return Rc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Sc(n)?Rc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class ch{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Vn=new eh,Of=new ch;var z$=Object.defineProperty,G$=(t)=>t;function K$(t,i){this[t]=G$.bind(null,i)}var q$=(t,i)=>{for(var n in i)z$(t,n,{get:i[n],enumerable:!0,configurable:!0,set:K$.bind(i,n)})},D$=(t,i)=>()=>(t&&(i=t(t=0)),i),sh={};q$(sh,{withErrorRecovery:()=>yh,tryLoadConfig:()=>sw,loadConfigWithResult:()=>hw,loadConfig:()=>Eh,isRetryableError:()=>iw,isConfigNotFoundError:()=>tw,isBunfigError:()=>uh,globalPerformanceMonitor:()=>ln,globalCache:()=>Wi,getEnvOrDefault:()=>nw,generateConfigTypes:()=>$w,defaultGeneratedDir:()=>Jh,defaultConfigDir:()=>Ch,deepMergeWithArrayStrategy:()=>gf,deepMerge:()=>ah,createLibraryConfig:()=>ww,config:()=>lw,bunfigPlugin:()=>yw,applyEnvVarsToConfig:()=>fn,TypeGenerationError:()=>Kf,SchemaValidationError:()=>hn,PluginError:()=>Df,PerformanceMonitor:()=>kf,FileSystemError:()=>Gf,ErrorFactory:()=>ci,EnvVarError:()=>nr,EnvProcessor:()=>hr,ConfigValidator:()=>bf,ConfigValidationError:()=>Mf,ConfigNotFoundError:()=>ir,ConfigMergeError:()=>zf,ConfigLoader:()=>Xf,ConfigLoadError:()=>cn,ConfigFileLoader:()=>lr,ConfigCache:()=>Lf,CacheUtils:()=>Sh,BunfigError:()=>Et,BrowserConfigError:()=>qf,ArrayMergeStrategies:()=>Nh});class Lf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Bc(t))return!0;return Nc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Bc(n)?Nc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class kf{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function x$(t,i={}){let r=Object.keys(i).sort().map((f)=>`${f}:${i[f]}`).join("|");return r?`${t}:${r}`:t}function O$(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function L$(t){return t.getStats().size*2}function of(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&D(i[0])&&"id"in i[0]&&i[0].id===3&&D(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(D(i)&&D(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(D(t)&&"arr"in t&&Array.isArray(t.arr)&&D(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&D(i[0])&&D(t[0])){let r=[...i];for(let f of t)if(D(f)&&"name"in f){if(!r.find((c)=>D(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(D(f)&&"path"in f){if(!r.find((c)=>D(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>vn(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!D(i)||!D(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(D(f)&&D(n[r]))n[r]=of(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&D(f[0])&&D(n[r][0])){let e=[...f];for(let c of n[r])if(D(c)&&"name"in c){if(!e.find((h)=>D(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(D(c)&&"path"in c){if(!e.find((h)=>D(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((l)=>vn(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function vn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!vn(t[n],i[n]))return!1;return!0}if(D(t)&&D(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!vn(t[f],i[f]))return!1}return!0}return!1}function D(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function k$(t,i){if(!lh(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return of(i,r)}catch{return null}}catch{return null}}async function o$({name:t="",cwd:i,defaultConfig:n}){let r=i||Yf.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let l of f){let h=Xn(r,`${c}${l}`),s=await k$(h,n);if(s!==null)return s}try{let c=Xn(r,"package.json");if(lh(c)){let h=(await import(c))[t];if(h&&typeof h==="object"&&!Array.isArray(h))try{return of(n,h)}catch{}}}catch{}return n}function V$(t,i={}){let n=bn.cwd();while(n.includes("storage"))n=Jc(n,"..");let r=Jc(n,t||"");if(i?.relative)return f$(bn.cwd(),r);return r}async function g$(){try{let t=await o$({name:"clarity",defaultConfig:On,cwd:bn.cwd(),endpoint:"",headers:{}});return{...On,...t}}catch{return On}}function L(){if(Ot.env.NODE_ENV==="test"||Ot.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function b$(){if(Ot.env.NODE_ENV==="test"||Ot.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ot<"u"){let t=Ot.type;if(t==="renderer"||t==="worker")return!1;return!!(Ot.versions&&(Ot.versions.node||Ot.versions.bun))}return!1}class $h{async format(t){let i=await b$(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Fi.pid,hostname:i(),environment:Fi.env.NODE_ENV||"development",platform:Fi.platform,version:Fi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Fi.env.NODE_ENV||Fi.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;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Zf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new $h,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??nt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ln,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ln};return{...Ln,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Zf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await s$(this.config.logDirectory,dc.F_OK|dc.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await $$(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ei.from(t);try{if(!af(this.currentLogFile))await Af(this.currentLogFile,"",{mode:420});if(f=jc(this.currentLogFile,"a",420),l$(f,h,{flag:"a"}),Uc(f),f!==void 0)uf(f),f=void 0;if((await Bi(this.currentLogFile)).size===0){if(await Af(this.currentLogFile,h,{flag:"w",mode:420}),(await Bi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let $=s;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(e<c-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,w);let u=l*2**e;await new Promise((y)=>setTimeout(y,u)),e++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(f!==void 0)try{uf(f)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(h){if(e===c-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}e++;let s=l*2**(e-1);await new Promise(($)=>setTimeout($,s))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ni(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(L())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return yf(16).toString("hex")}generateKey(){return yf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=yf(16),r=e$("aes-256-gcm",i,n),f=ei.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:ei.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Yc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(ei.from(ei.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(L())return;let t=await Bi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Un(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,s)=>{let $=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0")-$}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Bi(n).catch(()=>null))try{if(await Wc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await jn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Af(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Bi(n).catch(()=>null))await Wc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Un(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await jn(Ni(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=_c(t),r=h$(i),f=Yc();await w$(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),af(this.currentLogFile))try{let t=jc(this.currentLogFile,"r+");Uc(t),uf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!L()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Un(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await jn(Ni(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?K.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(c)y.push(i);if(e==="warning")y.push("WARN");else if(e==="error")y.push("ERROR");else if(n)y.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)y.push(r.replace(/[[\]]/g,""));return y.push(f),y.join(" ")}let h=nt.stdout.columns||120,s="";if(e==="warning"||e==="error")s=`${n} ${f}`;else if(e==="info"||e==="success")s=`${n} ${r} ${f}`;else s=`${n} ${r} ${K.cyan(f)}`;if(!c)return s.trim();let $=l(s).trim().length,w=l(i).length,u=Math.max(1,h-2-$-w);return`${s.trim()}${" ".repeat(u)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!L()){let s=Rh[t],$=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:K.gray(c),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:c,level:t}),console.error(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:K.green(c),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:c,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:c,level:t}),console.error(w),l){let u=l.split(`
|
|
2
|
-
`);for(let
|
|
3
|
-
`;if(l
|
|
4
|
-
`;
|
|
5
|
-
|
|
6
|
-
`),c=Math.max(...e.map((
|
|
7
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(L())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${K.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}progress(t,i=""){if(!this.enabled||!this.fancy||L()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,
|
|
9
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||L()||!nt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(L()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Un(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Ni(this.config.logDirectory,r);if(t.before)try{if((await Bi(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await jn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function xn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&Z(i[0])&&"id"in i[0]&&i[0].id===3&&Z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(Z(i)&&Z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(Z(t)&&"arr"in t&&Array.isArray(t.arr)&&Z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&Z(i[0])&&Z(t[0])){let r=[...i];for(let f of t)if(Z(f)&&"name"in f){if(!r.find((c)=>Z(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(Z(f)&&"path"in f){if(!r.find((c)=>Z(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>Qn(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!Z(i)||!Z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(Z(f)&&Z(n[r]))n[r]=xn(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&Z(f[0])&&Z(n[r][0])){let e=[...f];for(let c of n[r])if(Z(c)&&"name"in c){if(!e.find((h)=>Z(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(Z(c)&&"path"in c){if(!e.find((h)=>Z(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((l)=>Qn(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function Vf(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:xn(t,i);if(Array.isArray(t))return n==="replace"?i:xn(t,i);if(!Z(i)||!Z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=xn(c,e);else if(Z(e)&&Z(c))r[f]=Vf(c,e,n);else r[f]=e}return r}function Qn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Qn(t[n],i[n]))return!1;return!0}if(Z(t)&&Z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Qn(t[f],i[f]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Gn(t,i,n="replace"){if(!hh(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Vf(i,f,n)}catch{return null}}catch{return null}}function X$(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,l=[]){let h={...c};for(let[s,$]of Object.entries(c)){let w=[...l,s],u=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${r}_${w.map(u).join("_")}`,E=`${r}_${w.map((A)=>A.toUpperCase()).join("_")}`;if(n)ft.info(`Checking environment variable ${y} for config ${t}.${w.join(".")}`);if(typeof $==="object"&&$!==null&&!Array.isArray($))h[s]=e($,w);else{let A=en.env[y]||en.env[E];if(A!==void 0){if(n)ft.info(`Using environment variable ${A?y:E} for config ${t}.${w.join(".")}`);if(typeof $==="number")h[s]=Number(A);else if(typeof $==="boolean")h[s]=A.toLowerCase()==="true";else if(Array.isArray($))try{let T=JSON.parse(A);if(Array.isArray(T))h[s]=T;else h[s]=A.split(",").map((m)=>m.trim())}catch{h[s]=A.split(",").map((T)=>T.trim())}else h[s]=A}}}return h}return e(f)}async function P$({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let h=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?X$(t,f,e):f,s=n||en.cwd(),$=[".ts",".js",".mjs",".cjs",".json"];if(e)ft.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${s}`);let w=[t,`.${t}`].filter(Boolean),u=[`${t}.config`,`.${t}.config`].filter(Boolean),y=i?[i,`.${i}`]:[],E=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([s,st(s,"config"),st(s,".config"),r?st(s,r):void 0].filter(Boolean)));for(let T of A){if(e)ft.info(`Searching for configuration in: ${T}`);let R=[st(s,"config"),st(s,".config")].concat(r?[st(s,r)]:[]).includes(T)?[...w,...u,...y,...E]:[...u,...w,...E,...y];for(let C of R)for(let J of $){let j=st(T,`${C}${J}`),B=await Gn(j,h,l);if(B!==null){if(e)ft.success(`Configuration loaded from: ${j}`);return B}}}if(t){let T=st(wf(),".config",t),m=["config",`${t}.config`];if(i)m.push(`${i}.config`);if(e)ft.info(`Checking user config directory: ${T}`);for(let R of m)for(let C of $){let J=st(T,`${R}${C}`),j=await Gn(J,h,l);if(j!==null){if(e)ft.success(`Configuration loaded from user config directory: ${J}`);return j}}}if(t){let T=st(wf(),".config"),m=[`.${t}.config`];if(i)m.push(`.${i}.config`);if(e)ft.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of m)for(let C of $){let J=st(T,`${R}${C}`),j=await Gn(J,h,l);if(j!==null){if(e)ft.success(`Configuration loaded from user config directory dotfile: ${J}`);return j}}}if(t){let T=wf(),m=[`.${t}.config`,`.${t}`];if(i)m.push(`.${i}.config`),m.push(`.${i}`);if(e)ft.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of m)for(let C of $){let J=st(T,`${R}${C}`),j=await Gn(J,h,l);if(j!==null){if(e)ft.success(`Configuration loaded from user home directory: ${J}`);return j}}}try{let T=st(s,"package.json");if(hh(T)){let m=await import(T),R=m[t];if(!R&&i){if(R=m[i],R&&e)ft.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)ft.success(`Configuration loaded from package.json: ${R===m[t]?t:i}`);return Vf(h,R,l)}catch(C){if(e)ft.warn("Failed to merge package.json config:",C)}}}catch(T){if(e)ft.warn("Failed to load package.json:",T)}if(e)ft.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return h}function v$(t,i={}){let n=gn.cwd();while(n.includes("storage"))n=Cc(n,"..");let r=Cc(n,t||"");if(i?.relative)return n$(gn.cwd(),r);return r}async function p$(){try{let t=await P$({name:"clarity",alias:"logging",defaultConfig:kn,cwd:gn.cwd()});return{...kn,...t||{}}}catch{return kn}}function g(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Q$(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Lt<"u"){let t=Lt.type;if(t==="renderer"||t==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class wh{async format(t){let i=await Q$(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:_i.pid,hostname:i(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class tr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Hf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new wh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...on,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...on};return{...on,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Hf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!g()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await m$(this.config.logDirectory,Mc.F_OK|Mc.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await E$(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:qt.from(t);try{if(!dn(this.currentLogFile))await Tf(this.currentLogFile,"",{mode:420});if(f=Hc(this.currentLogFile,"a",420),A$(f,h,{flag:"a"}),Zc(f),f!==void 0)Ef(f),f=void 0;if((await Ci(this.currentLogFile)).size===0){if(await Tf(this.currentLogFile,h,{flag:"w",mode:420}),(await Ci(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let $=s;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(e<c-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,w);let u=l*2**e;await new Promise((y)=>setTimeout(y,u)),e++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(f!==void 0)try{Ef(f)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(h){if(e===c-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}e++;let s=l*2**(e-1);await new Promise(($)=>setTimeout($,s))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ji(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 Ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(g())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return mf(16).toString("hex")}generateKey(){return mf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=mf(16),r=y$("aes-256-gcm",i,n),f=qt.isBuffer(t)?t:qt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),s=qt.allocUnsafe(16+l+16);return n.copy(s,0),e.copy(s,16),c.copy(s,16+e.length),h.copy(s,16+l),{encrypted:s,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Gc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(qt.from(qt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(g())return;if(!this.shouldWriteToFile())return;let t=await Ci(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Wn(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,s)=>{let $=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0")-$}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Ci(n).catch(()=>null))try{if(await zc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Yn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Tf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ci(n).catch(()=>null))await zc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Wn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Yn(Ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Ic(t),r=a$(i),f=Gc();await R$(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),dn(this.currentLogFile))try{let t=Hc(this.currentLogFile,"r+");Zc(t),Ef(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Wn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Yn(Ji(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?d.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||g())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(c)y.push(i);if(e==="warning")y.push("WARN");else if(e==="error")y.push("ERROR");else if(n)y.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)y.push(r.replace(/[[\]]/g,""));return y.push(f),y.join(" ")}let h=_.stdout.columns||120,s="";if(e==="warning"||e==="error")s=`${n} ${f}`;else if(e==="info"||e==="success")s=`${n} ${r} ${f}`;else s=`${n} ${r} ${d.cyan(f)}`;if(!c)return s.trim();let $=l(s).trim().length,w=l(i).length,u=Math.max(1,h-2-$-w);return`${s.trim()}${" ".repeat(u)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=d.underline(d.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",s="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>d.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>d.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>d.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>d.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>d.strikethrough(r)),i}supportsHyperlinks(){if(g())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=_.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(T$(i)||i.startsWith("./")||i.startsWith("../"))i=S$(i);else return null;return dn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:s}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":Bh[t],u=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:d.gray(h),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:d.green(h),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.error(y),l){let E=l.split(`
|
|
10
|
-
`);for(let A of
|
|
11
|
-
`;if(
|
|
12
|
-
`;if(
|
|
13
|
-
`);if(this[
|
|
14
|
-
|
|
15
|
-
`),
|
|
16
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(g())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
18
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||g()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(g()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
1
|
+
import{a as G,b as Un,c as Fn,d as a,e as LS,f as ci,g as kS,h as X$,i as Ac,j as ya,k as wf,l as P$,m as VS,n as tw,o as v$}from"./chunk-jpf41gb9.js";import{execSync as za}from"node:child_process";import*as Bi from"node:http";import*as yw from"node:http2";import*as aw from"node:net";import*as D from"node:process";var S={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};var Mn=(t,i)=>(n)=>`\x1B[${t}m${n}\x1B[${i}m`,dt={bold:Mn(1,22),dim:Mn(2,22),green:Mn(32,39),cyan:Mn(36,39)};import{homedir as se}from"node:os";import{join as ye,resolve as Zm}from"node:path";import{existsSync as Hc,statSync as Mc}from"fs";import{existsSync as Ew,mkdirSync as ga,readdirSync as ba,readFileSync as Tw,writeFileSync as Xa}from"fs";import{homedir as Ci}from"os";import{dirname as pa,resolve as Bt}from"path";import Ar from"process";import{existsSync as zc,statSync as Gc}from"fs";import{existsSync as kf,mkdirSync as Sw,readdirSync as Rw,writeFileSync as Bw}from"fs";import{homedir as Fi}from"os";import{dirname as Kc,resolve as ut}from"path";import Ai from"process";import{join as Cw,relative as Fw,resolve as qc}from"path";import nr from"process";import{existsSync as Cl,mkdirSync as hA,readdirSync as $A,writeFileSync as wA}from"fs";import{homedir as Jf}from"os";import{dirname as yA,resolve as wt}from"path";import wn from"process";import{join as Nw,relative as Jw,resolve as xc}from"path";import rr from"process";import{existsSync as Fl,mkdirSync as TA,readdirSync as SA,writeFileSync as RA}from"fs";import{dirname as CA,resolve as fr}from"path";import Vf from"process";import{Buffer as li}from"buffer";import{createCipheriv as _w,createDecipheriv as Uw,randomBytes as _f}from"crypto";import{closeSync as Uf,createReadStream as Oc,createWriteStream as dw,existsSync as df,fsyncSync as Dc,openSync as Lc,writeFileSync as jw}from"fs";import{access as Ww,constants as kc,mkdir as Yw,readdir as zn,rename as Vc,stat as Ni,unlink as Gn,writeFile as jf}from"fs/promises";import{join as Ji}from"path";import rt from"process";import{pipeline as Iw}from"stream/promises";import{createGzip as oc}from"zlib";import _i from"process";import Lt from"process";import{Buffer as xt}from"buffer";import{createCipheriv as Zw,createDecipheriv as Hw,randomBytes as Wf}from"crypto";import{closeSync as Yf,createReadStream as gc,createWriteStream as Mw,existsSync as Kn,fsyncSync as bc,openSync as Xc,writeFileSync as zw}from"fs";import{access as Gw,constants as Pc,mkdir as Kw,readdir as qn,rename as vc,stat as Ui,unlink as xn,writeFile as If}from"fs/promises";import{isAbsolute as qw,join as di,resolve as xw}from"path";import _ from"process";import{pipeline as Ow}from"stream/promises";import{createGzip as pc}from"zlib";import ji from"process";import kt from"process";import On from"process";import{existsSync as Dn}from"fs";import{resolve as Zf}from"path";import{existsSync as Dw}from"fs";import{existsSync as Lw,readdirSync as kw}from"fs";import{extname as Hf,resolve as Qc}from"path";import Vw from"process";import{join as ow,relative as gw,resolve as tl}from"path";import er from"process";import{Buffer as Ot}from"buffer";import{createCipheriv as bw,createDecipheriv as Xw,randomBytes as Mf}from"crypto";import{closeSync as zf,createReadStream as il,createWriteStream as Pw,existsSync as Ln,fsyncSync as nl,openSync as rl,writeFileSync as vw}from"fs";import{access as pw,constants as fl,mkdir as Qw,readdir as kn,rename as el,stat as Wi,unlink as Vn,writeFile as Gf}from"fs/promises";import{isAbsolute as tu,join as Yi,resolve as iu}from"path";import U from"process";import{pipeline as nu}from"stream/promises";import{createGzip as cl}from"zlib";import Ii from"process";import Vt from"process";import gn from"process";import{existsSync as bn}from"fs";import{resolve as Lf}from"path";import{existsSync as Cs}from"fs";class Rl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Hc(t))return!0;return Mc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Hc(n)?Mc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Bl{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var ir=new Rl,ne=new Bl;var ru=Object.defineProperty,fu=(t)=>t;function eu(t,i){this[t]=fu.bind(null,i)}var cu=(t,i)=>{for(var n in i)ru(t,n,{get:i[n],enumerable:!0,configurable:!0,set:eu.bind(i,n)})},lu=(t,i)=>()=>(t&&(i=t(t=0)),i),Nl={};cu(Nl,{withErrorRecovery:()=>Ul,tryLoadConfig:()=>Wu,loadConfigWithResult:()=>du,loadConfig:()=>Il,isRetryableError:()=>Cu,isConfigNotFoundError:()=>Bu,isBunfigError:()=>dl,globalPerformanceMonitor:()=>yn,globalCache:()=>Zi,getEnvOrDefault:()=>Fu,generateConfigTypes:()=>Yu,defaultGeneratedDir:()=>xl,defaultConfigDir:()=>ql,deepMergeWithArrayStrategy:()=>le,deepMerge:()=>jl,createLibraryConfig:()=>Iu,config:()=>ju,bunfigPlugin:()=>Zu,applyEnvVarsToConfig:()=>$n,TypeGenerationError:()=>pf,SchemaValidationError:()=>sn,PluginError:()=>te,PerformanceMonitor:()=>fe,FileSystemError:()=>vf,ErrorFactory:()=>hi,EnvVarError:()=>ur,EnvProcessor:()=>mr,ConfigValidator:()=>he,ConfigValidationError:()=>Xf,ConfigNotFoundError:()=>wr,ConfigMergeError:()=>Pf,ConfigLoader:()=>$e,ConfigLoadError:()=>un,ConfigFileLoader:()=>Er,ConfigCache:()=>re,CacheUtils:()=>Hl,BunfigError:()=>Et,BrowserConfigError:()=>Qf,ArrayMergeStrategies:()=>Gl});class re{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!zc(t))return!0;return Gc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=zc(n)?Gc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class fe{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function hu(t,i={}){let r=Object.keys(i).sort().map((f)=>`${f}:${i[f]}`).join("|");return r?`${t}:${r}`:t}function $u(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function wu(t){return t.getStats().size*2}function ee(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let r=[...i];for(let f of t)if(x(f)&&"name"in f){if(!r.find((c)=>x(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find((c)=>x(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>cr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!x(i)||!x(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=ee(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let e=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!e.find((l)=>x(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(x(c)&&"path"in c){if(!e.find((l)=>x(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((h)=>cr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function cr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!cr(t[n],i[n]))return!1;return!0}if(x(t)&&x(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!cr(t[f],i[f]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function uu(t,i){if(!Fl(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ee(i,r)}catch{return null}}catch{return null}}async function su({name:t="",cwd:i,defaultConfig:n}){let r=i||Vf.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let h of f){let l=fr(r,`${c}${h}`),$=await uu(l,n);if($!==null)return $}try{let c=fr(r,"package.json");if(Fl(c)){let l=(await import(c))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return ee(n,l)}catch{}}}catch{}return n}function yu(t,i={}){let n=rr.cwd();while(n.includes("storage"))n=xc(n,"..");let r=xc(n,t||"");if(i?.relative)return Jw(rr.cwd(),r);return r}async function au(){try{let t=await su({name:"clarity",defaultConfig:vn,cwd:rr.cwd(),endpoint:"",headers:{}});return{...vn,...t}}catch{return vn}}function L(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Au(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Lt<"u"){let t=Lt.type;if(t==="renderer"||t==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class Jl{async format(t){let i=await Au(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:_i.pid,hostname:i(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...gf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Jl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??rt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...pn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...pn};return{...pn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:gf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,h=1000;while(e<c)try{try{try{await Ww(this.config.logDirectory,kc.F_OK|kc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Yw(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:li.from(t);try{if(!df(this.currentLogFile))await jf(this.currentLogFile,"",{mode:420});if(f=Lc(this.currentLogFile,"a",420),jw(f,l,{flag:"a"}),Dc(f),f!==void 0)Uf(f),f=void 0;if((await Ni(this.currentLogFile)).size===0){if(await jf(this.currentLogFile,l,{flag:"w",mode:420}),(await Ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{Uf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ji(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 Ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(L())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return _f(16).toString("hex")}generateKey(){return _f(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=_f(16),r=_w("aes-256-gcm",i,n),f=li.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:li.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=oc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(li.from(li.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(L())return;let t=await Ni(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await zn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ni(n).catch(()=>null))try{if(await Vc(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Gn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await jf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ni(n).catch(()=>null))await Vc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await zn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await Gn(Ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Oc(t),r=dw(i),f=oc();await Iw(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),df(this.currentLogFile))try{let t=Lc(this.currentLogFile,"r+");Dc(t),Uf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!L()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await zn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Gn(Ji(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?K.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=rt.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${K.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!L()){let $=Ml[t],w=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",s;switch(t){case"debug":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:K.gray(c),level:t}),console.error(s);break;case"info":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s);break;case"success":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:K.green(c),level:t}),console.error(s);break;case"warning":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.warn(s);break;case"error":if(s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s),h){let y=h.split(`
|
|
2
|
+
`);for(let u of y)if(u.trim()&&!u.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!L()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let l=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
|
|
3
|
+
`;if(h)l+=`${h}
|
|
4
|
+
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!L()){let n=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:K.blue("◐"),tag:n,message:`${K.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
5
|
+
`,$=$.replace(this.ANSI_PATTERN,""),this.fancy&&!L()){let w=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:K.green("✓"),tag:w,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!L())console.error($.trim());await this.writeToFile($)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new lr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(L())throw Error("createReadStream is not supported in browser environments");if(!df(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=li.isBuffer(t)?t:li.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),h=Uw("aes-256-gcm",n,f);return h.setAuthTag(e),li.concat([h.update(c),h.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return L()}isServerMode(){return!L()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i);if(this.fancy&&!L()){let e=t.split(`
|
|
6
|
+
`),c=Math.max(...e.map((w)=>w.length))+2,h=`┌${"─".repeat(c)}┐`,l=`└${"─".repeat(c)}┘`,$=e.map((w)=>{let s=" ".repeat(c-w.length-2);return`│ ${w}${s} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:K.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(h)})),$.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(l),showTimestamp:!1}))}else if(!L())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let f=`${r} ${this.environment}.INFO: [BOX] ${t}
|
|
7
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(L())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${K.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();rt.stdin.removeListener("data",n);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!L()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",h=K.blue("◐");console.error(`${h} ${c} ${K.cyan(n)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}progress(t,i=""){if(!this.enabled||!this.fancy||L()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,c)),h!==void 0)this.activeProgressBar.message=h;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,h="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(h,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||L()||!rt.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=K.green("━".repeat(r)),c=K.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=i||n===100?K.green("✓"):K.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=rt.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,rt.stdout.write(t.lastRenderedLine),i)rt.stdout.write(`
|
|
9
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||L()||!rt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(L()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await zn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Ji(this.config.logDirectory,r);if(t.before)try{if((await Ni(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Gn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Pn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&Z(i[0])&&"id"in i[0]&&i[0].id===3&&Z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(Z(i)&&Z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(Z(t)&&"arr"in t&&Array.isArray(t.arr)&&Z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&Z(i[0])&&Z(t[0])){let r=[...i];for(let f of t)if(Z(f)&&"name"in f){if(!r.find((c)=>Z(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(Z(f)&&"path"in f){if(!r.find((c)=>Z(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>hr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!Z(i)||!Z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(Z(f)&&Z(n[r]))n[r]=Pn(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&Z(f[0])&&Z(n[r][0])){let e=[...f];for(let c of n[r])if(Z(c)&&"name"in c){if(!e.find((l)=>Z(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(Z(c)&&"path"in c){if(!e.find((l)=>Z(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((h)=>hr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function ce(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Pn(t,i);if(Array.isArray(t))return n==="replace"?i:Pn(t,i);if(!Z(i)||!Z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Pn(c,e);else if(Z(e)&&Z(c))r[f]=ce(c,e,n);else r[f]=e}return r}function hr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!hr(t[n],i[n]))return!1;return!0}if(Z(t)&&Z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!hr(t[f],i[f]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function on(t,i,n="replace"){if(!Cl(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return ce(i,f,n)}catch{return null}}catch{return null}}function mu(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${r}_${s.map(y).join("_")}`,m=`${r}_${s.map((A)=>A.toUpperCase()).join("_")}`;if(n)et.info(`Checking environment variable ${u} for config ${t}.${s.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))l[$]=e(w,s);else{let A=wn.env[u]||wn.env[m];if(A!==void 0){if(n)et.info(`Using environment variable ${A?u:m} for config ${t}.${s.join(".")}`);if(typeof w==="number")l[$]=Number(A);else if(typeof w==="boolean")l[$]=A.toLowerCase()==="true";else if(Array.isArray(w))try{let T=JSON.parse(A);if(Array.isArray(T))l[$]=T;else l[$]=A.split(",").map((E)=>E.trim())}catch{l[$]=A.split(",").map((T)=>T.trim())}else l[$]=A}}}return l}return e(f)}async function Eu({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:h="replace"}){let l=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?mu(t,f,e):f,$=n||wn.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(e)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let s=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,wt($,"config"),wt($,".config"),r?wt($,r):void 0].filter(Boolean)));for(let T of A){if(e)et.info(`Searching for configuration in: ${T}`);let R=[wt($,"config"),wt($,".config")].concat(r?[wt($,r)]:[]).includes(T)?[...s,...y,...u,...m]:[...y,...s,...m,...u];for(let N of R)for(let J of w){let d=wt(T,`${N}${J}`),B=await on(d,l,h);if(B!==null){if(e)et.success(`Configuration loaded from: ${d}`);return B}}}if(t){let T=wt(Jf(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)et.info(`Checking user config directory: ${T}`);for(let R of E)for(let N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user config directory: ${J}`);return d}}}if(t){let T=wt(Jf(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)et.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user config directory dotfile: ${J}`);return d}}}if(t){let T=Jf(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)et.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user home directory: ${J}`);return d}}}try{let T=wt($,"package.json");if(Cl(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)et.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)et.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return ce(l,R,h)}catch(N){if(e)et.warn("Failed to merge package.json config:",N)}}}catch(T){if(e)et.warn("Failed to load package.json:",T)}if(e)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function Tu(t,i={}){let n=nr.cwd();while(n.includes("storage"))n=qc(n,"..");let r=qc(n,t||"");if(i?.relative)return Fw(nr.cwd(),r);return r}async function Su(){try{let t=await Eu({name:"clarity",alias:"logging",defaultConfig:Qn,cwd:nr.cwd()});return{...Qn,...t||{}}}catch{return Qn}}function g(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ru(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let t=kt.type;if(t==="renderer"||t==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class _l{async format(t){let i=await Ru(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $r{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...bf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new _l,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...tr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...tr};return{...tr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:bf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!g()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,h=1000;while(e<c)try{try{try{await Gw(this.config.logDirectory,Pc.F_OK|Pc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Kw(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:xt.from(t);try{if(!Kn(this.currentLogFile))await If(this.currentLogFile,"",{mode:420});if(f=Xc(this.currentLogFile,"a",420),zw(f,l,{flag:"a"}),bc(f),f!==void 0)Yf(f),f=void 0;if((await Ui(this.currentLogFile)).size===0){if(await If(this.currentLogFile,l,{flag:"w",mode:420}),(await Ui(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{Yf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return di(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 di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(g())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Wf(16).toString("hex")}generateKey(){return Wf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Wf(16),r=Zw("aes-256-gcm",i,n),f=xt.isBuffer(t)?t:xt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=xt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=pc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(xt.from(xt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(g())return;if(!this.shouldWriteToFile())return;let t=await Ui(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await qn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ui(n).catch(()=>null))try{if(await vc(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await xn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await If(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ui(n).catch(()=>null))await vc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await qn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await xn(di(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=gc(t),r=Mw(i),f=pc();await Ow(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Kn(this.currentLogFile))try{let t=Xc(this.currentLogFile,"r+");bc(t),Yf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await qn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await xn(di(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?j.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||g())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=_.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${j.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=j.underline(j.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>j.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>j.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>j.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>j.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>j.strikethrough(r)),i}supportsHyperlinks(){if(g())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=_.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(qw(i)||i.startsWith("./")||i.startsWith("../"))i=xw(i);else return null;return Kn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":zl[t],y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:j.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:j.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
10
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:j.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!g()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
11
|
+
`;if(h)w+=`${h}
|
|
12
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(h,l)=>{},finish:(h)=>{},interrupt:(h,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,l="info")=>{if(!g()&&_.stdout.isTTY)_.stdout.write(`
|
|
13
|
+
`);if(this[l==="warning"?"warn":l](h),this.activeProgressBar&&this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:n,message:`${j.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
14
|
+
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":j.green("✓"),tag:w,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!g())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new $r(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(g())throw Error("createReadStream is not supported in browser environments");if(!Kn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return gc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=xt.isBuffer(t)?t:xt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=Hw("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=xt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return g()}isServerMode(){return!g()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
15
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:j.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan(w),showTimestamp:!1}))}else if(!g())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
16
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(g())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${j.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();_.stdin.removeListener("data",n);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,$=0;if(n=t.replace(l,(w,s)=>{if(s==="%")return"%";if($>=i.length)return w;let y=i[$++];switch(s){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<i.length)n+=` ${i.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${$}${l} ${j.cyan(r)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=j.green("━".repeat(r)),c=j.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?j.green("✓"):j.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=_.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
|
|
18
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||g()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(g()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await qn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=di(this.config.logDirectory,r);if(t.before)try{if((await Ui(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await xn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Ul(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function dl(t){return t instanceof Et}function Bu(t){return t instanceof wr}function Cu(t){if(dl(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class mr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return yn.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=On.env[l]||($?On.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=On.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof ur)throw s;throw hi.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw hi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(On.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
19
19
|
|
|
20
20
|
`;for(let r of t)n+=`${r.key}
|
|
21
21
|
`,n+=` Type: ${r.type}
|
|
@@ -27,25 +27,25 @@ import{a as G,b as Tn,c as Qe,d as a,e as hS,f as fi,g as lS,h as Ws,i as tc,j a
|
|
|
27
27
|
`;n+=`| Variable | Type | Description | Example |
|
|
28
28
|
`,n+=`|----------|------|-------------|----------|
|
|
29
29
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
30
|
-
`;return n}}function nw(t,i){let n=Th("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function ah(t,i,n={}){return Ah(t,i,n,new WeakMap)}function Ah(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return mh(t,i,f,r);if(!Nt(i)||!Nt(t))return i;return cw(t,i,n,r)}function mh(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return rw(t,i);case"smart":return fw(t,i,r);default:return i}return i}function rw(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>If(f,r)))n.push(r);return n}function fw(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Nt(i[0])&&Nt(t[0]))return ew(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function ew(t,i,n){let r=[...i];for(let f of t){if(!Nt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((s)=>Nt(s)&&(l in s)&&s[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function cw(t,i,n,r){let f=i;if(Nt(f)&&r.has(f))return r.get(f);let e={...t};if(Nt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Nt(l)&&Nt(h))e[c]=Ah(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=mh(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function gf(t,i,n="replace"){return ah(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function If(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!If(t[n],i[n]))return!1;return!0}if(Nt(t)&&Nt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!If(t[f],i[f]))return!1}return!0}return!1}function Nt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class lr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let s=Wi.getWithFileCheck("file",t);if(s){if(l)console.log(`Configuration loaded from cache: ${t}`);return s}}let h=async()=>{if(!Zn(t))return null;try{let s=`?t=${Date.now()}`,$=await import(t+s),w=$.default||$,u="default"in $,y=Object.keys($).length>0;if(!u&&!y)throw new cn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new cn(t,Error("Configuration must export a valid object"),"unknown");let T={config:gf(i,w,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Wi.setWithFileCheck("file",T,t,e);return T}catch(s){throw s instanceof Error?ci.configLoad(t,s):ci.configLoad(t,Error(String(s)))}};if(c)return ln.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Sf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return yh(async()=>{return Zn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Zn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=Sf(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=Sf(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Zn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class bf{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,s=async()=>{let $=[],w=[],u={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,u);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],u);else return this.validateWithJSONSchema(t,i,u)}catch(y){return $.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:$,warnings:w}}};if(l)return await ln.track("validateConfiguration",s);return s()}async validateWithSchemaFile(t,i,n){try{if(!B$(i))throw new hn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new hn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let s=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,s,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Fh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xf{fileLoader=new lr;envProcessor=new hr;validator=new bf;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let s=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if(s)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let $=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),w=!$&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),u=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if(s&&(u||$))throw h;if(w&&(!s||!u))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!s)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)dt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){let h=Date.now()-i;throw dt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:s="replace",verbose:$=!1}=t,w=e||wi.cwd(),u=[],y=await this.loadLocalConfiguration(r,f,w,c,l,s,$,h,n);if(y)return u.push(...this.getLocalSearchPaths(r,f,w,c)),this.finalizeResult(y,u,h,r,$);let E=await this.loadHomeConfiguration(r,f,l,s,$,h);if(E)return u.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(E,u,h,r,$);let A=await this.loadPackageJsonConfiguration(r,f,w,l,s,$,h);if(A)return u.push($t(w,"package.json")),this.finalizeResult(A,u,h,r,$);if(u.push(...this.getAllSearchPaths(r,f,w,c)),i)throw ci.configNotFound(r,u,f);return{...await this.applyEnvironmentVariables(r,l,h,$),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let s=l?fn(t,f,c):f,$=this.getLocalDirectories(n,r);for(let w of $){if(c)dt.info(`Searching for configuration in: ${w}`);let u=this.fileLoader.generateConfigPaths(t,w,i),y=await this.fileLoader.tryLoadFromPaths(u,s,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(y){if(c)dt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?fn(t,n,f):n,l=[$t(Ri(),".config",t),$t(Ri(),".config"),Ri()];for(let h of l){if(f)dt.info(`Checking home directory: ${h}`);let s=this.fileLoader.generateConfigPaths(t,h,i),$=await this.fileLoader.tryLoadFromPaths(s,c,{arrayStrategy:r,verbose:f});if($){if(f)dt.success(`Configuration loaded from home directory: ${$.source.path}`);return $}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?fn(t,r,e):r;try{let h=$t(n,"package.json");if(!Wf(h))return null;let s=await import(h),$=s[t],w=t;if(!$&&i)$=s[i],w=i;if($&&typeof $==="object"&&!Array.isArray($)){if(e)dt.success(`Configuration loaded from package.json: ${w}`);return{config:gf(l,$,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)dt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:fn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw ci.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Wi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Wi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,$t(t,"config"),$t(t,".config"),i?$t(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push($t(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[$t(Ri(),".config",t),$t(Ri(),".config"),Ri()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function Vc(t){let n=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return n||r}async function hw(t){return ot.loadConfig({...t,__strictErrorHandling:!0})}async function Eh(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ot.loadConfig(t);else r=await ot.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)dt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ot.applyEnvironmentVariables(l.name||"",i,!0,l.verbose||!1))?.config??i;return i}}async function lw(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ot.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Vc(n)))return(await ot.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ot.loadConfig({...t,cwd:t.cwd||wi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Vc(i)))return(await ot.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function sw(t,i,n="replace"){let r=new lr;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function fn(t,i,n=!1){let r=new hr,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[s,$]of Object.entries(c)){let w=[...l,s],u=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((A)=>A.toUpperCase()).join("")}`,`${f}_${w.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,E;for(let A of u)if(y=wi.env[A],y!==void 0){E=A;break}if(y!==void 0&&E)if(typeof $==="boolean")h[s]=["true","1","yes"].includes(y.toLowerCase());else if(typeof $==="number"){let A=Number(y);if(!Number.isNaN(A))h[s]=A}else if(Array.isArray($))try{h[s]=JSON.parse(y)}catch{h[s]=y.split(",").map((A)=>A.trim())}else h[s]=y;else if($&&typeof $==="object"&&!Array.isArray($))h[s]=e($,w)}return h}return e(i)}function $w(t){let i=$t(wi.cwd(),t.configDir),n=$t(wi.cwd(),t.generatedDir),r=$t(n,"config-types.ts");if(!Wf(Fc(r)))ps(Fc(r),{recursive:!0,mode:511});let f=Wf(i)?Qs(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${qw}
|
|
30
|
+
`;return n}}function Fu(t,i){let n=Zl("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function jl(t,i,n={}){return Wl(t,i,n,new WeakMap)}function Wl(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return Yl(t,i,f,r);if(!Ct(i)||!Ct(t))return i;return Uu(t,i,n,r)}function Yl(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return Nu(t,i);case"smart":return Ju(t,i,r);default:return i}return i}function Nu(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>of(f,r)))n.push(r);return n}function Ju(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ct(i[0])&&Ct(t[0]))return _u(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function _u(t,i,n){let r=[...i];for(let f of t){if(!Ct(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find(($)=>Ct($)&&(h in $)&&$[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Uu(t,i,n,r){let f=i;if(Ct(f)&&r.has(f))return r.get(f);let e={...t};if(Ct(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Ct(h)&&Ct(l))e[c]=Wl(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=Yl(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function le(t,i,n="replace"){return jl(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function of(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!of(t[n],i[n]))return!1;return!0}if(Ct(t)&&Ct(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!of(t[f],i[f]))return!1}return!0}return!1}function Ct(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Er{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=Zi.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Dn(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new un(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new un(t,Error("Configuration must export a valid object"),"unknown");let T={config:le(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Zi.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?hi.configLoad(t,$):hi.configLoad(t,Error(String($)))}};if(c)return yn.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Zf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return Ul(async()=>{return Dn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Dn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Zf(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Zf(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Dn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class he{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await yn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Dw(i))throw new sn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new sn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Kl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class $e{fileLoader=new Er;envProcessor=new mr;validator=new he;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)jt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){let l=Date.now()-i;throw jt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||Ai.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(ut(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?$n(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)jt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)jt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?$n(t,n,f):n,h=[ut(Fi(),".config",t),ut(Fi(),".config"),Fi()];for(let l of h){if(f)jt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)jt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?$n(t,r,e):r;try{let l=ut(n,"package.json");if(!kf(l))return null;let $=await import(l),w=$[t],s=t;if(!w&&i)w=$[i],s=i;if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)jt.success(`Configuration loaded from package.json: ${s}`);return{config:le(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)jt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$n(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw hi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Zi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Zi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,ut(t,"config"),ut(t,".config"),i?ut(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(ut(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[ut(Fi(),".config",t),ut(Fi(),".config"),Fi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function ll(t){let n=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return n||r}async function du(t){return ot.loadConfig({...t,__strictErrorHandling:!0})}async function Il(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ot.loadConfig(t);else r=await ot.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)jt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let h=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ot.applyEnvironmentVariables(h.name||"",i,!0,h.verbose||!1))?.config??i;return i}}async function ju(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ot.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&ll(n)))return(await ot.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ot.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&ll(i)))return(await ot.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Wu(t,i,n="replace"){let r=new Er;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function $n(t,i,n=!1){let r=new mr,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=Ai.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}function Yu(t){let i=ut(Ai.cwd(),t.configDir),n=ut(Ai.cwd(),t.generatedDir),r=ut(n,"config-types.ts");if(!kf(Kc(r)))Sw(Kc(r),{recursive:!0,mode:511});let f=kf(i)?Rw(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${cs}
|
|
31
31
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
32
|
-
`;
|
|
33
|
-
${f.map((
|
|
32
|
+
`;Bw(r,e,{mode:438})}function Iu(t){let i=null,n=null,r=()=>{if(!n)n=Il(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)jt.warn("Config loading failed, using defaults:",[e instanceof Error?e:Error(String(e))]);return c});return n},f="defaultConfig"in t?t.defaultConfig:{};return i=f,r(),new Proxy({},{get(e,c){if(i)return i[c];let h=f[c];return r(),h},has(e,c){return c in(i||f)},ownKeys(){return Object.keys(i||f)},getOwnPropertyDescriptor(e,c){return Object.getOwnPropertyDescriptor(i||f,c)},set(e,c,h){if(!i)i={...f};return i[c]=h,!0}})}function Zu(t){let i=Qc(Vw.cwd(),t?.configDir||"./config");function n(){if(!Lw(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=kw(i).filter((l)=>f.has(Hf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),h=new Map;for(let{base:l,file:$}of c){let w=Hf($).toLowerCase(),s=h.get(l);if(!s){h.set(l,$);continue}let y=Hf(s).toLowerCase();if(e.indexOf(w)<e.indexOf(y))h.set(l,$)}return Array.from(h.entries()).map(([l,$])=>({base:l,file:$})).sort((l,$)=>l.base.localeCompare($.base))}function r(){let f=n(),e=f.map(($)=>$.base),c=e.length?e.map(($)=>`'${$}'`).join(" | "):"string",h=f.length?`{
|
|
33
|
+
${f.map(($)=>{let w=Qc(i,$.file).replace(/\\/g,"/");return` '${$.base}': typeof import('${w}').default`}).join(`,
|
|
34
34
|
`)}
|
|
35
35
|
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
36
|
-
export type ConfigByName = ${
|
|
36
|
+
export type ConfigByName = ${h}
|
|
37
37
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
38
38
|
export type ConfigOf = Config
|
|
39
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Th,Wi,ln,Sh,uw,aw,gc,On,Zf,rt,K,Aw,bc,mw,Xc,Ew,Tw,Cf,Sw,Pc,vc,Jf,Rw,Bw,Nw,Fw,Ln,Rh,Cw,ft,Jw,_w,pc,kn,Hf,b,d,Uw,Qc,jw,th,dw,Ww,_f,Yw,ih,nh,Iw,Uf,Zw,Hw,Mw,zw,Gw,on,Bh,Kw,qw="0.15.6",Et,ir,cn,Mf,zf,nr,Gf,Kf,hn,qf,Df,ci,Nh,Fh,dt,ot,Ch,Jh,Dw=D$(async()=>{Th=import.meta.require,Wi=new Lf,ln=new kf,Sh={createKey:x$,isEquivalent:O$,estimateMemoryUsage:L$},uw=Xn(Yf.cwd(),"config"),aw=Xn(Yf.cwd(),"src/generated"),gc=bn.env.CLARITY_LOG_DIR||r$(V$(),"logs"),On={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Zf=await g$(),rt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},K=rt,Aw=rt.red,bc=rt.green,mw=rt.yellow,Xc=rt.blue,Ew=rt.magenta,Tw=rt.cyan,Cf=rt.white,Sw=rt.gray,Pc=rt.bgRed,vc=rt.bgYellow,Jf=rt.bold,Rw=rt.dim,Bw=rt.italic,Nw=rt.underline,Fw=rt.reset,Ln={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Rh={debug:"\uD83D\uDD0D",info:Xc("ℹ"),success:bc("✓"),warning:vc(Cf(Jf(" WARN "))),error:Pc(Cf(Jf(" ERROR ")))},Cw=new pn("stacks"),ft=new pn("bunfig",{showTags:!0}),Jw=st(en.cwd(),"config"),_w=st(en.cwd(),"src/generated"),pc=gn.env.CLARITY_LOG_DIR||i$(v$(),"logs"),kn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Hf=await p$(),b={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},d=b,Uw=b.red,Qc=b.green,jw=b.yellow,th=b.blue,dw=b.magenta,Ww=b.cyan,_f=b.white,Yw=b.gray,ih=b.bgRed,nh=b.bgYellow,Iw=b.bgGray,Uf=b.bold,Zw=b.dim,Hw=b.italic,Mw=b.underline,zw=b.strikethrough,Gw=b.reset,on={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bh={debug:"\uD83D\uDD0D",info:th("ℹ"),success:Qc("✓"),warning:nh(_f(Uf(" WARN "))),error:ih(_f(Uf(" ERROR ")))},Kw=new tr("stacks"),Et=class extends Error{timestamp;context;constructor(i,n={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},ir=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:n,searchPathCount:n.length})}},cn=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,n,r){super(`Failed to load configuration from "${i}": ${n.message}`,{configPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Mf=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,n,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:n,errorCount:n.length})}},zf=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,n,r,f){super(`Failed to merge configuration from "${i}" with "${n}": ${r.message}`,{sourcePath:i,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},nr=class extends Et{code="ENV_VAR_ERROR";constructor(i,n,r,f){super(`Failed to parse environment variable "${i}" with value "${n}" as ${r}`,{envKey:i,envValue:n,expectedType:r,configName:f})}},Gf=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,n,r){super(`File system ${i} failed for "${n}": ${r.message}`,{operation:i,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Kf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,n,r){super(`Failed to generate types from "${i}" to "${n}": ${r.message}`,{configDir:i,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},hn=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:n,errorCount:n.length})}},qf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,n,r,f){super(`Failed to fetch configuration from "${i}": ${n} ${r}`,{endpoint:i,status:n,statusText:r,configName:f})}},Df=class extends Et{code="PLUGIN_ERROR";constructor(i,n,r){super(`Plugin "${i}" failed during ${n}: ${r.message}`,{pluginName:i,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},ci={configNotFound(t,i,n){return new ir(t,i,n)},configLoad(t,i,n){return new cn(t,i,n)},configValidation(t,i,n){return new Mf(t,i,n)},configMerge(t,i,n,r){return new zf(t,i,n,r)},envVar(t,i,n,r){return new nr(t,i,n,r)},fileSystem(t,i,n){return new Gf(t,i,n)},typeGeneration(t,i,n){return new Kf(t,i,n)},schemaValidation(t,i,n){return new hn(t,i,n)},browserConfig(t,i,n,r){return new qf(t,i,n,r)},plugin(t,i,n){return new Df(t,i,n)}},Nh={replace:"replace",concat:"concat",smart:"smart"},Fh=/^https?:\/\//,dt=new tr("bunfig",{showTags:!0}),ot=new Xf,Ch=$t(wi.cwd(),"config"),Jh=$t(wi.cwd(),"src/generated")});function xw(t,i={}){let n=Pn.cwd();while(n.includes("storage"))n=qc(n,"..");let r=qc(n,t||"");if(i?.relative)return _$(Pn.cwd(),r);return r}var Ow=Pn.env.CLARITY_LOG_DIR||J$(xw(),"logs"),_h={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ow,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rr={..._h},DA=(async()=>{try{let{loadConfig:t}=await Dw().then(()=>sh),i=await t({name:"clarity",alias:"logging",defaultConfig:_h,cwd:Pn.cwd()});if(i)Object.assign(rr,i)}catch{}return rr})();function X(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lw(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let t=kt.type;if(t==="renderer"||t==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class Uh{async format(t){let i=await Lw(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:di.pid,hostname:i(),environment:di.env.NODE_ENV||"development",platform:di.platform,version:di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:di.env.NODE_ENV||di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Q={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},Y=Q,xA=Q.red,kw=Q.green,OA=Q.yellow,ow=Q.blue,LA=Q.magenta,kA=Q.cyan,rh=Q.white,oA=Q.gray,Vw=Q.bgRed,gw=Q.bgYellow,VA=Q.bgGray,fh=Q.bold,gA=Q.dim,bA=Q.italic,XA=Q.underline,PA=Q.strikethrough,vA=Q.reset,jf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bw={debug:"\uD83D\uDD0D",info:ow("ℹ"),success:kw("✓"),warning:gw(rh(fh(" WARN "))),error:Vw(rh(fh(" ERROR ")))};class sr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...rr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Uh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??U.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...jf,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...jf};return{...jf,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:rr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await Y$(this.config.logDirectory,Lc.F_OK|Lc.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await I$(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Dt.from(t);try{if(!Hn(this.currentLogFile))await Ff(this.currentLogFile,"",{mode:420});if(f=Oc(this.currentLogFile,"a",420),W$(f,h,{flag:"a"}),xc(f),f!==void 0)Nf(f),f=void 0;if((await Ui(this.currentLogFile)).size===0){if(await Ff(this.currentLogFile,h,{flag:"w",mode:420}),(await Ui(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let $=s;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(e<c-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,w);let u=l*2**e;await new Promise((y)=>setTimeout(y,u)),e++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(f!==void 0)try{Nf(f)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(h){if(e===c-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}e++;let s=l*2**(e-1);await new Promise(($)=>setTimeout($,s))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ji(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 ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Bf(16).toString("hex")}generateKey(){return Bf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Bf(16),r=U$("aes-256-gcm",i,n),f=Dt.isBuffer(t)?t:Dt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),s=Dt.allocUnsafe(16+l+16);return n.copy(s,0),e.copy(s,16),c.copy(s,16+e.length),h.copy(s,16+l),{encrypted:s,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=oc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Dt.from(Dt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Ui(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Mn(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,s)=>{let $=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0")-$}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Ui(n).catch(()=>null))try{if(await kc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await zn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Ff(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ui(n).catch(()=>null))await kc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Mn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await zn(ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Dc(t),r=d$(i),f=oc();await M$(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Hn(this.currentLogFile))try{let t=Oc(this.currentLogFile,"r+");xc(t),Nf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Mn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await zn(ji(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?Y.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof U.env.NO_COLOR<"u",i=U.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof U.stderr<"u"&&U.stderr.isTTY||typeof U.stdout<"u"&&U.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(c)y.push(i);if(e==="warning")y.push("WARN");else if(e==="error")y.push("ERROR");else if(n)y.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)y.push(r.replace(/[[\]]/g,""));return y.push(f),y.join(" ")}let h=U.stdout.columns||120,s="";if(e==="warning"||e==="error")s=`${n} ${f}`;else if(e==="info"||e==="success")s=`${n} ${r} ${f}`;else s=`${n} ${r} ${Y.cyan(f)}`;if(!c)return s.trim();let $=l(s).trim().length,w=l(i).length,u=Math.max(1,h-2-$-w);return`${s.trim()}${" ".repeat(u)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=Y.underline(Y.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",s="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>Y.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Y.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Y.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Y.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>Y.strikethrough(r)),i}supportsHyperlinks(){if(X())return!1;let t=U.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=U.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(Z$(i)||i.startsWith("./")||i.startsWith("../"))i=H$(i);else return null;return Hn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:s}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":bw[t],u=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:Y.gray(h),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:Y.green(h),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.error(y),l){let E=l.split(`
|
|
40
|
-
`);for(let A of
|
|
41
|
-
`;if(
|
|
42
|
-
`;if(
|
|
43
|
-
`);if(this[
|
|
44
|
-
|
|
45
|
-
`),
|
|
46
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${Y.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();U.stdin.removeListener("data",n);try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!1)}catch{}U.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!0)}catch{}U.stdin.resume(),U.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
48
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!U.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(X()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
39
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Zl,Zi,yn,Hl,Hu,Mu,hl,vn,gf,ft,K,zu,$l,Gu,wl,Ku,qu,Kf,xu,ul,sl,qf,Ou,Du,Lu,ku,pn,Ml,Vu,et,ou,gu,yl,Qn,bf,b,j,bu,al,Xu,Al,Pu,vu,xf,pu,ml,El,Qu,Of,ts,is,ns,rs,fs,tr,zl,es,cs="0.15.6",Et,wr,un,Xf,Pf,ur,vf,pf,sn,Qf,te,hi,Gl,Kl,jt,ot,ql,xl,ls=lu(async()=>{Zl=import.meta.require,Zi=new re,yn=new fe,Hl={createKey:hu,isEquivalent:$u,estimateMemoryUsage:wu},Hu=fr(Vf.cwd(),"config"),Mu=fr(Vf.cwd(),"src/generated"),hl=rr.env.CLARITY_LOG_DIR||Nw(yu(),"logs"),vn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},gf=await au(),ft={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},K=ft,zu=ft.red,$l=ft.green,Gu=ft.yellow,wl=ft.blue,Ku=ft.magenta,qu=ft.cyan,Kf=ft.white,xu=ft.gray,ul=ft.bgRed,sl=ft.bgYellow,qf=ft.bold,Ou=ft.dim,Du=ft.italic,Lu=ft.underline,ku=ft.reset,pn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ml={debug:"\uD83D\uDD0D",info:wl("ℹ"),success:$l("✓"),warning:sl(Kf(qf(" WARN "))),error:ul(Kf(qf(" ERROR ")))},Vu=new lr("stacks"),et=new lr("bunfig",{showTags:!0}),ou=wt(wn.cwd(),"config"),gu=wt(wn.cwd(),"src/generated"),yl=nr.env.CLARITY_LOG_DIR||Cw(Tu(),"logs"),Qn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bf=await Su(),b={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},j=b,bu=b.red,al=b.green,Xu=b.yellow,Al=b.blue,Pu=b.magenta,vu=b.cyan,xf=b.white,pu=b.gray,ml=b.bgRed,El=b.bgYellow,Qu=b.bgGray,Of=b.bold,ts=b.dim,is=b.italic,ns=b.underline,rs=b.strikethrough,fs=b.reset,tr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},zl={debug:"\uD83D\uDD0D",info:Al("ℹ"),success:al("✓"),warning:El(xf(Of(" WARN "))),error:ml(xf(Of(" ERROR ")))},es=new $r("stacks"),Et=class extends Error{timestamp;context;constructor(i,n={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},wr=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:n,searchPathCount:n.length})}},un=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,n,r){super(`Failed to load configuration from "${i}": ${n.message}`,{configPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Xf=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,n,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:n,errorCount:n.length})}},Pf=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,n,r,f){super(`Failed to merge configuration from "${i}" with "${n}": ${r.message}`,{sourcePath:i,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},ur=class extends Et{code="ENV_VAR_ERROR";constructor(i,n,r,f){super(`Failed to parse environment variable "${i}" with value "${n}" as ${r}`,{envKey:i,envValue:n,expectedType:r,configName:f})}},vf=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,n,r){super(`File system ${i} failed for "${n}": ${r.message}`,{operation:i,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},pf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,n,r){super(`Failed to generate types from "${i}" to "${n}": ${r.message}`,{configDir:i,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},sn=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:n,errorCount:n.length})}},Qf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,n,r,f){super(`Failed to fetch configuration from "${i}": ${n} ${r}`,{endpoint:i,status:n,statusText:r,configName:f})}},te=class extends Et{code="PLUGIN_ERROR";constructor(i,n,r){super(`Plugin "${i}" failed during ${n}: ${r.message}`,{pluginName:i,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},hi={configNotFound(t,i,n){return new wr(t,i,n)},configLoad(t,i,n){return new un(t,i,n)},configValidation(t,i,n){return new Xf(t,i,n)},configMerge(t,i,n,r){return new Pf(t,i,n,r)},envVar(t,i,n,r){return new ur(t,i,n,r)},fileSystem(t,i,n){return new vf(t,i,n)},typeGeneration(t,i,n){return new pf(t,i,n)},schemaValidation(t,i,n){return new sn(t,i,n)},browserConfig(t,i,n,r){return new Qf(t,i,n,r)},plugin(t,i,n){return new te(t,i,n)}},Gl={replace:"replace",concat:"concat",smart:"smart"},Kl=/^https?:\/\//,jt=new $r("bunfig",{showTags:!0}),ot=new $e,ql=ut(Ai.cwd(),"config"),xl=ut(Ai.cwd(),"src/generated")});function hs(t,i={}){let n=er.cwd();while(n.includes("storage"))n=tl(n,"..");let r=tl(n,t||"");if(i?.relative)return gw(er.cwd(),r);return r}var $s=er.env.CLARITY_LOG_DIR||ow(hs(),"logs"),Ol={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$s,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sr={...Ol},$m=(async()=>{try{let{loadConfig:t}=await ls().then(()=>Nl),i=await t({name:"clarity",alias:"logging",defaultConfig:Ol,cwd:er.cwd()});if(i)Object.assign(sr,i)}catch{}return sr})();function X(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ws(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let t=Vt.type;if(t==="renderer"||t==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class Dl{async format(t){let i=await ws(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ii.pid,hostname:i(),environment:Ii.env.NODE_ENV||"development",platform:Ii.platform,version:Ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ii.env.NODE_ENV||Ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var tt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},Y=tt,wm=tt.red,us=tt.green,um=tt.yellow,ss=tt.blue,sm=tt.magenta,ym=tt.cyan,Tl=tt.white,am=tt.gray,ys=tt.bgRed,as=tt.bgYellow,Am=tt.bgGray,Sl=tt.bold,mm=tt.dim,Em=tt.italic,Tm=tt.underline,Sm=tt.strikethrough,Rm=tt.reset,Df={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},As={debug:"\uD83D\uDD0D",info:ss("ℹ"),success:us("✓"),warning:as(Tl(Sl(" WARN "))),error:ys(Tl(Sl(" ERROR ")))};class Tr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...sr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Dl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??U.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Df,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Df};return{...Df,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:sr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,h=1000;while(e<c)try{try{try{await pw(this.config.logDirectory,fl.F_OK|fl.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Qw(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Ot.from(t);try{if(!Ln(this.currentLogFile))await Gf(this.currentLogFile,"",{mode:420});if(f=rl(this.currentLogFile,"a",420),vw(f,l,{flag:"a"}),nl(f),f!==void 0)zf(f),f=void 0;if((await Wi(this.currentLogFile)).size===0){if(await Gf(this.currentLogFile,l,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{zf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Mf(16).toString("hex")}generateKey(){return Mf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Mf(16),r=bw("aes-256-gcm",i,n),f=Ot.isBuffer(t)?t:Ot.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=Ot.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=cl(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Ot.from(Ot.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Wi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await kn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Wi(n).catch(()=>null))try{if(await el(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Vn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Gf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Wi(n).catch(()=>null))await el(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await kn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await Vn(Yi(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=il(t),r=Pw(i),f=cl();await nu(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ln(this.currentLogFile))try{let t=rl(this.currentLogFile,"r+");nl(t),zf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await kn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Vn(Yi(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?Y.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof U.env.NO_COLOR<"u",i=U.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof U.stderr<"u"&&U.stderr.isTTY||typeof U.stdout<"u"&&U.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=U.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${Y.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=Y.underline(Y.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>Y.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Y.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Y.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Y.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>Y.strikethrough(r)),i}supportsHyperlinks(){if(X())return!1;let t=U.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=U.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(tu(i)||i.startsWith("./")||i.startsWith("../"))i=iu(i);else return null;return Ln(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":As[t],y=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:Y.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:Y.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
40
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:Y.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
41
|
+
`;if(h)w+=`${h}
|
|
42
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(h,l)=>{},finish:(h)=>{},interrupt:(h,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,l="info")=>{if(!X()&&U.stdout.isTTY)U.stdout.write(`
|
|
43
|
+
`);if(this[l==="warning"?"warn":l](h),this.activeProgressBar&&this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Y.blue("◐"),tag:n,message:`${Y.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
44
|
+
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":Y.green("✓"),tag:w,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!X())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new Tr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(X())throw Error("createReadStream is not supported in browser environments");if(!Ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return il(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Ot.isBuffer(t)?t:Ot.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=Xw("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=Ot.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X()}isServerMode(){return!X()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
45
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:Y.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan(w),showTimestamp:!1}))}else if(!X())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
46
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${Y.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();U.stdin.removeListener("data",n);try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!1)}catch{}U.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!0)}catch{}U.stdin.resume(),U.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,$=0;if(n=t.replace(l,(w,s)=>{if(s==="%")return"%";if($>=i.length)return w;let y=i[$++];switch(s){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<i.length)n+=` ${i.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${Y.blue("◐")} `;console.error(`${$}${l} ${Y.cyan(r)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!U.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=Y.green("━".repeat(r)),c=Y.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?Y.green("✓"):Y.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=U.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,U.stdout.write(t.lastRenderedLine),i)U.stdout.write(`
|
|
48
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!U.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(X()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await kn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Yi(this.config.logDirectory,r);if(t.before)try{if((await Wi(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Vn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Bm=new Tr("stacks");class Wt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class Ll extends Wt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((e)=>`"${e}"`).join(", ")}`;super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class yr extends Wt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}}class kl extends Wt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class Vl extends Wt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class we extends Wt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}}class ol extends Wt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class gl extends Wt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class ar extends Wt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class bl extends Wt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}}class Xl extends Wt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}}var Hi={configNotFound(t,i,n){return new Ll(t,i,n)},configLoad(t,i,n){return new yr(t,i,n)},configValidation(t,i,n){return new kl(t,i,n)},configMerge(t,i,n,r){return new Vl(t,i,n,r)},envVar(t,i,n,r){return new we(t,i,n,r)},fileSystem(t,i,n){return new ol(t,i,n)},typeGeneration(t,i,n){return new gl(t,i,n)},schemaValidation(t,i,n){return new ar(t,i,n)},browserConfig(t,i,n,r){return new bl(t,i,n,r)},plugin(t,i,n){return new Xl(t,i,n)}};async function ms(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class ue{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ne.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=gn.env[l]||($?gn.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=gn.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof we)throw s;throw Hi.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw Hi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(gn.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
49
49
|
|
|
50
50
|
`;for(let r of t)n+=`${r.key}
|
|
51
51
|
`,n+=` Type: ${r.type}
|
|
@@ -57,24 +57,24 @@ export type ConfigOf = Config
|
|
|
57
57
|
`;n+=`| Variable | Type | Description | Example |
|
|
58
58
|
`,n+=`|----------|------|-------------|----------|
|
|
59
59
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
60
|
-
`;return n}}function Pw(t,i,n={}){return Mh(t,i,n,new WeakMap)}function Mh(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return zh(t,i,f,r);if(!Ft(i)||!Ft(t))return i;return ty(t,i,n,r)}function zh(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return vw(t,i);case"smart":return pw(t,i,r);default:return i}return i}function vw(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>xf(f,r)))n.push(r);return n}function pw(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return Qw(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Qw(t,i,n){let r=[...i];for(let f of t){if(!Ft(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((s)=>Ft(s)&&(l in s)&&s[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function ty(t,i,n,r){let f=i;if(Ft(f)&&r.has(f))return r.get(f);let e={...t};if(Ft(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Ft(l)&&Ft(h))e[c]=Mh(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=zh(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function Gh(t,i,n="replace"){return Pw(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function xf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!xf(t[n],i[n]))return!1;return!0}if(Ft(t)&&Ft(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!xf(t[f],i[f]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Kh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let s=Vn.getWithFileCheck("file",t);if(s){if(l)console.log(`Configuration loaded from cache: ${t}`);return s}}let h=async()=>{if(!qn(t))return null;try{let s=`?t=${Date.now()}`,$=await import(t+s),w=$.default||$,u="default"in $,y=Object.keys($).length>0;if(!u&&!y)throw new fr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new fr(t,Error("Configuration must export a valid object"),"unknown");let T={config:Gh(i,w,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Vn.setWithFileCheck("file",T,t,e);return T}catch(s){throw s instanceof Error?Yi.configLoad(t,s):Yi.configLoad(t,Error(String(s)))}};if(c)return Of.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(df(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return Xw(async()=>{return qn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!qn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=df(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=df(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!qn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var ny=/^https?:\/\//;class qh{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,s=async()=>{let $=[],w=[],u={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,u);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],u);else return this.validateWithJSONSchema(t,i,u)}catch(y){return $.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:$,warnings:w}}};if(l)return await Of.track("validateConfiguration",s);return s()}async validateWithSchemaFile(t,i,n){try{if(!iy(i))throw new er(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new er(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let s=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,s,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ny},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var xt=new sr("bunfig",{showTags:!0});function ry(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class Dh{fileLoader=new Kh;envProcessor=new vf;validator=new qh;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let s=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if(s)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let $=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),w=!$&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),u=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if(s&&(u||$))throw h;if(w&&(!s||!u))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!s)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)xt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let h=Date.now()-i;throw xt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:s="replace",verbose:$=!1}=t,w=e||cr.cwd(),u=[],y=await this.loadLocalConfiguration(r,f,w,c,l,s,$,h,n);if(y)return u.push(...this.getLocalSearchPaths(r,f,w,c)),this.finalizeResult(y,u,h,r,$);let E=await this.loadHomeConfiguration(r,f,l,s,$,h);if(E)return u.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(E,u,h,r,$);let A=await this.loadPackageJsonConfiguration(r,f,w,l,s,$,h);if(A)return u.push(Bt(w,"package.json")),this.finalizeResult(A,u,h,r,$);if(u.push(...this.getAllSearchPaths(r,f,w,c)),i)throw Yi.configNotFound(r,u,f);return{...await this.applyEnvironmentVariables(r,l,h,$),warnings:[`No configuration file found for "${r}"${ry(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let s=l?Dn(t,f,c):f,$=this.getLocalDirectories(n,r);for(let w of $){if(c)xt.info(`Searching for configuration in: ${w}`);let u=this.fileLoader.generateConfigPaths(t,w,i),y=await this.fileLoader.tryLoadFromPaths(u,s,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(y){if(c)xt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Dn(t,n,f):n,l=[Bt(Si(),".config",t),Bt(Si(),".config"),Si()];for(let h of l){if(f)xt.info(`Checking home directory: ${h}`);let s=this.fileLoader.generateConfigPaths(t,h,i),$=await this.fileLoader.tryLoadFromPaths(s,c,{arrayStrategy:r,verbose:f});if($){if(f)xt.success(`Configuration loaded from home directory: ${$.source.path}`);return $}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?Dn(t,r,e):r;try{let h=Bt(n,"package.json");if(!Ps(h))return null;let s={};try{s=JSON.parse(vs(h,"utf8"))}catch(u){if(e)xt.warn("Failed to parse package.json:",[u instanceof Error?u:Error(String(u))]);return null}let $=s[t],w=t;if(!$&&i){let u=Array.isArray(i)?i:[i];for(let y of u){if(!y)continue;if(s[y]){$=s[y],w=y;break}}}if($&&typeof $==="object"&&!Array.isArray($)){if(e)xt.success(`Configuration loaded from package.json: ${w}`);return{config:Gh(l,$,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)xt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Dn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Yi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Vn.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Vn.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Bt(t,"config"),Bt(t,".config"),i?Bt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Bt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Bt(Si(),".config",t),Bt(Si(),".config"),Si()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var rm=new Dh;function Dn(t,i,n=!1){let r=new vf,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[s,$]of Object.entries(c)){let w=[...l,s],u=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((A)=>A.toUpperCase()).join("")}`,`${f}_${w.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,E;for(let A of u)if(y=cr.env[A],y!==void 0){E=A;break}if(y!==void 0&&E)if(typeof $==="boolean")h[s]=["true","1","yes"].includes(y.toLowerCase());else if(typeof $==="number"){let A=Number(y);if(!Number.isNaN(A))h[s]=A}else if(Array.isArray($))try{h[s]=JSON.parse(y)}catch{h[s]=y.split(",").map((A)=>A.trim())}else h[s]=y;else if($&&typeof $==="object"&&!Array.isArray($))h[s]=e($,w)}return h}return e(i)}var fm=Bt(cr.cwd(),"config"),em=Bt(cr.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",fy={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Qf(pf(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Qf(pf(),".stacks","ssl","stacks.localhost.crt"),keyPath:Qf(pf(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Ii=fy;import*as qs from"node:fs";import*as Ds from"node:path";import*as Kt from"node:process";import{spawn as i0}from"node:child_process";import*as Gt from"node:fs/promises";import{homedir as n0}from"node:os";import*as Qi from"node:path";import*as it from"node:process";import{execSync as ui}from"node:child_process";import V from"node:fs/promises";import*as pe from"node:os";import{homedir as ic}from"node:os";import{join as at}from"node:path";import*as zt from"node:process";import{createRequire as ey}from"node:module";import te from"node:os";import ie from"node:path";import{existsSync as xh,statSync as Oh}from"fs";import{existsSync as cy,mkdirSync as Sm,readdirSync as Rm,readFileSync as hy,writeFileSync as Bm}from"fs";import{homedir as Zi}from"os";import{dirname as Cm,resolve as Ct}from"path";import or from"process";import{existsSync as Lh,statSync as kh}from"fs";import{existsSync as Be,mkdirSync as ly,readdirSync as sy,writeFileSync as $y}from"fs";import{homedir as Hi}from"os";import{dirname as oh,resolve as yt}from"path";import yi from"process";import{join as wy,relative as yy,resolve as Vh}from"path";import dr from"process";import{existsSync as Zl,mkdirSync as Hm,readdirSync as Mm,writeFileSync as zm}from"fs";import{homedir as ne}from"os";import{dirname as qm,resolve as wt}from"path";import yn from"process";import{join as uy,relative as ay,resolve as gh}from"path";import Wr from"process";import{existsSync as Hl,mkdirSync as km,readdirSync as om,writeFileSync as Vm}from"fs";import{dirname as bm,resolve as Yr}from"path";import Ne from"process";import{Buffer as hi}from"buffer";import{createCipheriv as Ay,createDecipheriv as my,randomBytes as re}from"crypto";import{closeSync as fe,createReadStream as bh,createWriteStream as Ey,existsSync as ee,fsyncSync as Xh,openSync as Ph,writeFileSync as Ty}from"fs";import{access as Sy,constants as vh,mkdir as Ry,readdir as $r,rename as ph,stat as Mi,unlink as wr,writeFile as ce}from"fs/promises";import{join as zi}from"path";import et from"process";import{pipeline as By}from"stream/promises";import{createGzip as Qh}from"zlib";import Gi from"process";import Xt from"process";import{Buffer as Vt}from"buffer";import{createCipheriv as Ny,createDecipheriv as Fy,randomBytes as he}from"crypto";import{closeSync as le,createReadStream as tl,createWriteStream as Cy,existsSync as yr,fsyncSync as il,openSync as nl,writeFileSync as Jy}from"fs";import{access as _y,constants as rl,mkdir as Uy,readdir as ur,rename as fl,stat as Ki,unlink as ar,writeFile as se}from"fs/promises";import{isAbsolute as jy,join as qi,resolve as dy}from"path";import H from"process";import{pipeline as Wy}from"stream/promises";import{createGzip as el}from"zlib";import Di from"process";import Pt from"process";import Ar from"process";import{existsSync as mr}from"fs";import{resolve as $e}from"path";import{existsSync as Yy}from"fs";import{existsSync as Iy,readdirSync as Zy}from"fs";import{extname as we,resolve as cl}from"path";import Hy from"process";import{join as My,relative as zy,resolve as hl}from"path";import Ir from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Gy,createDecipheriv as Ky,randomBytes as ye}from"crypto";import{closeSync as ue,createReadStream as ll,createWriteStream as qy,existsSync as Er,fsyncSync as sl,openSync as $l,writeFileSync as Dy}from"fs";import{access as xy,constants as wl,mkdir as Oy,readdir as Tr,rename as yl,stat as xi,unlink as Sr,writeFile as ae}from"fs/promises";import{isAbsolute as Ly,join as Oi,resolve as ky}from"path";import M from"process";import{pipeline as oy}from"stream/promises";import{createGzip as ul}from"zlib";import Li from"process";import vt from"process";import Rr from"process";import{existsSync as Br}from"fs";import{resolve as Ae}from"path";import{existsSync as Vy}from"fs";import{exec as aa}from"node:child_process";import Ul from"node:fs";import Aa from"node:os";import Yt from"node:path";import ms from"node:process";import{promisify as ma}from"node:util";import gi from"node:crypto";import pt from"node:fs";import Me from"node:path";import{execSync as Il}from"node:child_process";import kr from"node:os";var am=ey(import.meta.url);class Ml{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!xh(t))return!0;return Oh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=xh(n)?Oh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class zl{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Zr=new Ml,ze=new zl,gy=Object.defineProperty,by=(t)=>t;function Xy(t,i){this[t]=by.bind(null,i)}var Py=(t,i)=>{for(var n in i)gy(t,n,{get:i[n],enumerable:!0,configurable:!0,set:Xy.bind(i,n)})},vy=(t,i)=>()=>(t&&(i=t(t=0)),i),Gl={};Py(Gl,{withErrorRecovery:()=>Dl,tryLoadConfig:()=>Ru,loadConfigWithResult:()=>Tu,loadConfig:()=>ol,isRetryableError:()=>yu,isConfigNotFoundError:()=>wu,isBunfigError:()=>xl,globalPerformanceMonitor:()=>mn,globalCache:()=>oi,getEnvOrDefault:()=>uu,generateConfigTypes:()=>Bu,defaultGeneratedDir:()=>Ql,defaultConfigDir:()=>pl,deepMergeWithArrayStrategy:()=>xe,deepMerge:()=>Ol,createLibraryConfig:()=>Nu,config:()=>Su,bunfigPlugin:()=>Fu,applyEnvVarsToConfig:()=>$n,TypeGenerationError:()=>de,SchemaValidationError:()=>an,PluginError:()=>Ye,PerformanceMonitor:()=>Ke,FileSystemError:()=>je,ErrorFactory:()=>si,EnvVarError:()=>qr,EnvProcessor:()=>Vr,ConfigValidator:()=>Oe,ConfigValidationError:()=>_e,ConfigNotFoundError:()=>Kr,ConfigMergeError:()=>Ue,ConfigLoader:()=>Le,ConfigLoadError:()=>un,ConfigFileLoader:()=>gr,ConfigCache:()=>Ge,CacheUtils:()=>gl,BunfigError:()=>Tt,BrowserConfigError:()=>We,ArrayMergeStrategies:()=>Pl});class Ge{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Lh(t))return!0;return kh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Lh(n)?kh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Ke{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function py(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function Qy(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function tu(t){return t.getStats().size*2}function qe(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let r=[...i];for(let f of t)if(x(f)&&"name"in f){if(!r.find((e)=>x(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find((e)=>x(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Hr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!x(i)||!x(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=qe(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let e=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!e.find((l)=>x(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(x(c)&&"path"in c){if(!e.find((l)=>x(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((l)=>Hr(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function Hr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Hr(t[n],i[n]))return!1;return!0}if(x(t)&&x(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Hr(t[f],i[f]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function iu(t,i){if(!Hl(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return qe(i,r)}catch{return null}}catch{return null}}async function nu({name:t="",cwd:i,defaultConfig:n}){let r=i||Ne.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let l of f){let h=Yr(r,`${c}${l}`),s=await iu(h,n);if(s!==null)return s}try{let c=Yr(r,"package.json");if(Hl(c)){let l=(await import(c))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return qe(n,l)}catch{}}}catch{}return n}function ru(t,i={}){let n=Wr.cwd();while(n.includes("storage"))n=gh(n,"..");let r=gh(n,t||"");if(i?.relative)return ay(Wr.cwd(),r);return r}async function fu(){try{let t=await nu({name:"clarity",defaultConfig:Jr,cwd:Wr.cwd(),endpoint:"",headers:{}});return{...Jr,...t}}catch{return Jr}}function k(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eu(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Xt<"u"){let t=Xt.type;if(t==="renderer"||t==="worker")return!1;return!!(Xt.versions&&(Xt.versions.node||Xt.versions.bun))}return!1}class Kl{async format(t){let i=await eu(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Gi.pid,hostname:i(),environment:Gi.env.NODE_ENV||"development",platform:Gi.platform,version:Gi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gi.env.NODE_ENV||Gi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Ce},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Kl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??et.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{..._r,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{..._r};return{..._r,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ce.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await Sy(this.config.logDirectory,vh.F_OK|vh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Ry(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:hi.from(t);try{if(!ee(this.currentLogFile))await ce(this.currentLogFile,"",{mode:420});if(r=Ph(this.currentLogFile,"a",420),Ty(r,l,{flag:"a"}),Xh(r),r!==void 0)fe(r),r=void 0;if((await Mi(this.currentLogFile)).size===0){if(await ce(this.currentLogFile,l,{flag:"w",mode:420}),(await Mi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let s=h;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(f<e-1){let $=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,$);let w=c*2**f;await new Promise((u)=>setTimeout(u,w)),f++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(r!==void 0)try{fe(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let s=l,$=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),l}f++;let h=c*2**(f-1);await new Promise((s)=>setTimeout(s,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return zi(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 zi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return zi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return re(16).toString("hex")}generateKey(){return re(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=re(16),r=Ay("aes-256-gcm",i,n),f=hi.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:hi.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Qh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(hi.from(hi.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Mi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await $r(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,s)=>{let $=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0")-$}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Mi(n).catch(()=>null))try{if(await ph(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await wr(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await ce(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Mi(n).catch(()=>null))await ph(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await $r(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await wr(zi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=bh(t),r=Ey(i),f=Qh();await By(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ee(this.currentLogFile))try{let t=Ph(this.currentLogFile,"r+");Xh(t),fe(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await $r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await wr(zi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?q.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(c)y.push(i);if(e==="warning")y.push("WARN");else if(e==="error")y.push("ERROR");else if(n)y.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)y.push(r.replace(/[[\]]/g,""));return y.push(f),y.join(" ")}let h=et.stdout.columns||120,s="";if(e==="warning"||e==="error")s=`${n} ${f}`;else if(e==="info"||e==="success")s=`${n} ${r} ${f}`;else s=`${n} ${r} ${q.cyan(f)}`;if(!c)return s.trim();let $=l(s).trim().length,w=l(i).length,u=Math.max(1,h-2-$-w);return`${s.trim()}${" ".repeat(u)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!k()){let s=bl[t],$=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:q.gray(c),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:c,level:t}),console.error(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:q.green(c),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:c,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:s,tag:$,message:c,level:t}),console.error(w),l){let u=l.split(`
|
|
61
|
-
`);for(let
|
|
62
|
-
`;if(l
|
|
63
|
-
`;
|
|
64
|
-
`,
|
|
65
|
-
`),c=Math.max(...e.map((
|
|
66
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${q.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();
|
|
67
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,r)),f!==void 0)this.activeProgressBar.message=f;let e=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,e)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;
|
|
68
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!et.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await $r(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=zi(this.config.logDirectory,r);if(t.before)try{if((await Mi(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await wr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Cr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&z(i[0])&&"id"in i[0]&&i[0].id===3&&z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(z(i)&&z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(z(t)&&"arr"in t&&Array.isArray(t.arr)&&z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&z(i[0])&&z(t[0])){let r=[...i];for(let f of t)if(z(f)&&"name"in f){if(!r.find((e)=>z(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(z(f)&&"path"in f){if(!r.find((e)=>z(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>zr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!z(i)||!z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(z(f)&&z(n[r]))n[r]=Cr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&z(f[0])&&z(n[r][0])){let e=[...f];for(let c of n[r])if(z(c)&&"name"in c){if(!e.find((l)=>z(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(z(c)&&"path"in c){if(!e.find((l)=>z(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((l)=>zr(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function De(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Cr(t,i);if(Array.isArray(t))return n==="replace"?i:Cr(t,i);if(!z(i)||!z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Cr(c,e);else if(z(e)&&z(c))r[f]=De(c,e,n);else r[f]=e}return r}function zr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!zr(t[n],i[n]))return!1;return!0}if(z(t)&&z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!zr(t[f],i[f]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Nr(t,i,n="replace"){if(!Zl(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return De(i,f,n)}catch{return null}}catch{return null}}function cu(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,l=[]){let h={...c};for(let[s,$]of Object.entries(c)){let w=[...l,s],u=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${r}_${w.map(u).join("_")}`,E=`${r}_${w.map((A)=>A.toUpperCase()).join("_")}`;if(n)ht.info(`Checking environment variable ${y} for config ${t}.${w.join(".")}`);if(typeof $==="object"&&$!==null&&!Array.isArray($))h[s]=e($,w);else{let A=yn.env[y]||yn.env[E];if(A!==void 0){if(n)ht.info(`Using environment variable ${A?y:E} for config ${t}.${w.join(".")}`);if(typeof $==="number")h[s]=Number(A);else if(typeof $==="boolean")h[s]=A.toLowerCase()==="true";else if(Array.isArray($))try{let T=JSON.parse(A);if(Array.isArray(T))h[s]=T;else h[s]=A.split(",").map((m)=>m.trim())}catch{h[s]=A.split(",").map((T)=>T.trim())}else h[s]=A}}}return h}return e(f)}async function hu({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let h=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?cu(t,f,e):f,s=n||yn.cwd(),$=[".ts",".js",".mjs",".cjs",".json"];if(e)ht.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${s}`);let w=[t,`.${t}`].filter(Boolean),u=[`${t}.config`,`.${t}.config`].filter(Boolean),y=i?[i,`.${i}`]:[],E=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([s,wt(s,"config"),wt(s,".config"),r?wt(s,r):void 0].filter(Boolean)));for(let T of A){if(e)ht.info(`Searching for configuration in: ${T}`);let m=[wt(s,"config"),wt(s,".config")].concat(r?[wt(s,r)]:[]).includes(T)?[...w,...u,...y,...E]:[...u,...w,...E,...y];for(let R of m)for(let C of $){let J=wt(T,`${R}${C}`),j=await Nr(J,h,l);if(j!==null){if(e)ht.success(`Configuration loaded from: ${J}`);return j}}}if(t){let T=wt(ne(),".config",t),m=["config",`${t}.config`];if(i)m.push(`${i}.config`);if(e)ht.info(`Checking user config directory: ${T}`);for(let R of m)for(let C of $){let J=wt(T,`${R}${C}`),j=await Nr(J,h,l);if(j!==null){if(e)ht.success(`Configuration loaded from user config directory: ${J}`);return j}}}if(t){let T=wt(ne(),".config"),m=[`.${t}.config`];if(i)m.push(`.${i}.config`);if(e)ht.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of m)for(let C of $){let J=wt(T,`${R}${C}`),j=await Nr(J,h,l);if(j!==null){if(e)ht.success(`Configuration loaded from user config directory dotfile: ${J}`);return j}}}if(t){let T=ne(),m=[`.${t}.config`,`.${t}`];if(i)m.push(`.${i}.config`),m.push(`.${i}`);if(e)ht.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of m)for(let C of $){let J=wt(T,`${R}${C}`),j=await Nr(J,h,l);if(j!==null){if(e)ht.success(`Configuration loaded from user home directory: ${J}`);return j}}}try{let T=wt(s,"package.json");if(Zl(T)){let m=await import(T),R=m[t];if(!R&&i){if(R=m[i],R&&e)ht.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)ht.success(`Configuration loaded from package.json: ${R===m[t]?t:i}`);return De(h,R,l)}catch(C){if(e)ht.warn("Failed to merge package.json config:",C)}}}catch(T){if(e)ht.warn("Failed to load package.json:",T)}if(e)ht.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return h}function lu(t,i={}){let n=dr.cwd();while(n.includes("storage"))n=Vh(n,"..");let r=Vh(n,t||"");if(i?.relative)return yy(dr.cwd(),r);return r}async function su(){try{let t=await hu({name:"clarity",alias:"logging",defaultConfig:Ur,cwd:dr.cwd()});return{...Ur,...t||{}}}catch{return Ur}}function P(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $u(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pt<"u"){let t=Pt.type;if(t==="renderer"||t==="worker")return!1;return!!(Pt.versions&&(Pt.versions.node||Pt.versions.bun))}return!1}class ql{async format(t){let i=await $u(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Di.pid,hostname:i(),environment:Di.env.NODE_ENV||"development",platform:Di.platform,version:Di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Di.env.NODE_ENV||Di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Je},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ql,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...jr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...jr};return{...jr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Je.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await _y(this.config.logDirectory,rl.F_OK|rl.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Uy(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Vt.from(t);try{if(!yr(this.currentLogFile))await se(this.currentLogFile,"",{mode:420});if(r=nl(this.currentLogFile,"a",420),Jy(r,l,{flag:"a"}),il(r),r!==void 0)le(r),r=void 0;if((await Ki(this.currentLogFile)).size===0){if(await se(this.currentLogFile,l,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let s=h;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(f<e-1){let $=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,$);let w=c*2**f;await new Promise((u)=>setTimeout(u,w)),f++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(r!==void 0)try{le(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let s=l,$=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),l}f++;let h=c*2**(f-1);await new Promise((s)=>setTimeout(s,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return qi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return he(16).toString("hex")}generateKey(){return he(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=he(16),r=Ny("aes-256-gcm",i,n),f=Vt.isBuffer(t)?t:Vt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),s=Vt.allocUnsafe(16+l+16);return n.copy(s,0),e.copy(s,16),c.copy(s,16+e.length),h.copy(s,16+l),{encrypted:s,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=el(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Vt.from(Vt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ur(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,s)=>{let $=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0")-$}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Ki(n).catch(()=>null))try{if(await fl(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await ar(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await se(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ki(n).catch(()=>null))await fl(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await ur(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await ar(qi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=tl(t),r=Cy(i),f=el();await Wy(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),yr(this.currentLogFile))try{let t=nl(this.currentLogFile,"r+");il(t),le(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ur(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await ar(qi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof H.env.NO_COLOR<"u",i=H.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(c)y.push(i);if(e==="warning")y.push("WARN");else if(e==="error")y.push("ERROR");else if(n)y.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)y.push(r.replace(/[[\]]/g,""));return y.push(f),y.join(" ")}let h=H.stdout.columns||120,s="";if(e==="warning"||e==="error")s=`${n} ${f}`;else if(e==="info"||e==="success")s=`${n} ${r} ${f}`;else s=`${n} ${r} ${W.cyan(f)}`;if(!c)return s.trim();let $=l(s).trim().length,w=l(i).length,u=Math.max(1,h-2-$-w);return`${s.trim()}${" ".repeat(u)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=W.underline(W.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",s="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>W.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>W.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>W.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>W.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>W.strikethrough(r)),i}supportsHyperlinks(){if(P())return!1;let t=H.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=H.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(jy(i)||i.startsWith("./")||i.startsWith("../"))i=dy(i);else return null;return yr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:s}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":Xl[t],u=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:W.gray(h),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:W.green(h),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.error(y),l){let E=l.split(`
|
|
69
|
-
`);for(let A of
|
|
70
|
-
`;if(
|
|
71
|
-
`;if(
|
|
72
|
-
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:n,message:`${W.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,
|
|
73
|
-
`,
|
|
74
|
-
`),
|
|
75
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,
|
|
76
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=W.green("━".repeat(r)),c=W.gray("━".repeat(f)),
|
|
77
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
60
|
+
`;return n}}function Es(t,i,n={}){return Pl(t,i,n,new WeakMap)}function Pl(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return vl(t,i,f,r);if(!Ft(i)||!Ft(t))return i;return Bs(t,i,n,r)}function vl(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return Ts(t,i);case"smart":return Ss(t,i,r);default:return i}return i}function Ts(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>ie(f,r)))n.push(r);return n}function Ss(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return Rs(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Rs(t,i,n){let r=[...i];for(let f of t){if(!Ft(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find(($)=>Ft($)&&(h in $)&&$[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Bs(t,i,n,r){let f=i;if(Ft(f)&&r.has(f))return r.get(f);let e={...t};if(Ft(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Ft(h)&&Ft(l))e[c]=Pl(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=vl(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function pl(t,i,n="replace"){return Es(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function ie(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!ie(t[n],i[n]))return!1;return!0}if(Ft(t)&&Ft(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!ie(t[f],i[f]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Ql{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=ir.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!bn(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new yr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new yr(t,Error("Configuration must export a valid object"),"unknown");let T={config:pl(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)ir.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?Hi.configLoad(t,$):Hi.configLoad(t,Error(String($)))}};if(c)return ne.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Lf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return ms(async()=>{return bn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!bn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Lf(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Lf(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!bn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var Fs=/^https?:\/\//;class th{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await ne.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Cs(i))throw new ar(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new ar(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Fs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Dt=new Tr("bunfig",{showTags:!0});function Ns(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class ih{fileLoader=new Ql;envProcessor=new ue;validator=new th;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Dt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let l=Date.now()-i;throw Dt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||Ar.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(Bt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw Hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${Ns(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?Xn(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)Dt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)Dt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Xn(t,n,f):n,h=[Bt(Ci(),".config",t),Bt(Ci(),".config"),Ci()];for(let l of h){if(f)Dt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)Dt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?Xn(t,r,e):r;try{let l=Bt(n,"package.json");if(!Ew(l))return null;let $={};try{$=JSON.parse(Tw(l,"utf8"))}catch(y){if(e)Dt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let w=$[t],s=t;if(!w&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if($[u]){w=$[u],s=u;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)Dt.success(`Configuration loaded from package.json: ${s}`);return{config:pl(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)Dt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Hi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return ir.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);ir.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Bt(t,"config"),Bt(t,".config"),i?Bt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Bt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Bt(Ci(),".config",t),Bt(Ci(),".config"),Ci()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var _m=new ih;function Xn(t,i,n=!1){let r=new ue,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=Ar.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}var Um=Bt(Ar.cwd(),"config"),dm=Bt(Ar.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Js={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:ye(se(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:ye(se(),".stacks","ssl","stacks.localhost.crt"),keyPath:ye(se(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Mi=Js;import*as cw from"node:fs";import*as lw from"node:path";import*as qt from"node:process";import{spawn as Na}from"node:child_process";import*as Kt from"node:fs/promises";import{homedir as rw}from"node:os";import*as Gt from"node:path";import*as nt from"node:process";import{execSync as tn}from"node:child_process";import o from"node:fs/promises";import*as ac from"node:os";import{homedir as uf}from"node:os";import{join as Q}from"node:path";import*as zt from"node:process";import{createRequire as _s}from"node:module";import ae from"node:os";import Ae from"node:path";import{existsSync as nh,statSync as rh}from"fs";import{existsSync as Us,mkdirSync as Dm,readdirSync as Lm,readFileSync as ds,writeFileSync as km}from"fs";import{homedir as zi}from"os";import{dirname as gm,resolve as Nt}from"path";import tf from"process";import{existsSync as fh,statSync as eh}from"fs";import{existsSync as Me,mkdirSync as js,readdirSync as Ws,writeFileSync as Ys}from"fs";import{homedir as Gi}from"os";import{dirname as ch,resolve as yt}from"path";import mi from"process";import{join as Is,relative as Zs,resolve as lh}from"path";import Kr from"process";import{existsSync as bh,mkdirSync as r1,readdirSync as f1,writeFileSync as e1}from"fs";import{homedir as me}from"os";import{dirname as h1,resolve as st}from"path";import En from"process";import{join as Hs,relative as Ms,resolve as hh}from"path";import qr from"process";import{existsSync as Xh,mkdirSync as y1,readdirSync as a1,writeFileSync as A1}from"fs";import{dirname as E1,resolve as xr}from"path";import ze from"process";import{Buffer as $i}from"buffer";import{createCipheriv as zs,createDecipheriv as Gs,randomBytes as Ee}from"crypto";import{closeSync as Te,createReadStream as $h,createWriteStream as Ks,existsSync as Se,fsyncSync as wh,openSync as uh,writeFileSync as qs}from"fs";import{access as xs,constants as sh,mkdir as Os,readdir as Sr,rename as yh,stat as Ki,unlink as Rr,writeFile as Re}from"fs/promises";import{join as qi}from"path";import ct from"process";import{pipeline as Ds}from"stream/promises";import{createGzip as ah}from"zlib";import xi from"process";import Pt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Ls,createDecipheriv as ks,randomBytes as Be}from"crypto";import{closeSync as Ce,createReadStream as Ah,createWriteStream as Vs,existsSync as Br,fsyncSync as mh,openSync as Eh,writeFileSync as os}from"fs";import{access as gs,constants as Th,mkdir as bs,readdir as Cr,rename as Sh,stat as Oi,unlink as Fr,writeFile as Fe}from"fs/promises";import{isAbsolute as Xs,join as Di,resolve as Ps}from"path";import H from"process";import{pipeline as vs}from"stream/promises";import{createGzip as Rh}from"zlib";import Li from"process";import vt from"process";import Nr from"process";import{existsSync as Jr}from"fs";import{resolve as Ne}from"path";import{existsSync as ps}from"fs";import{existsSync as Qs,readdirSync as t0}from"fs";import{extname as Je,resolve as Bh}from"path";import i0 from"process";import{join as n0,relative as r0,resolve as Ch}from"path";import Or from"process";import{Buffer as bt}from"buffer";import{createCipheriv as f0,createDecipheriv as e0,randomBytes as _e}from"crypto";import{closeSync as Ue,createReadStream as Fh,createWriteStream as c0,existsSync as _r,fsyncSync as Nh,openSync as Jh,writeFileSync as l0}from"fs";import{access as h0,constants as _h,mkdir as $0,readdir as Ur,rename as Uh,stat as ki,unlink as dr,writeFile as de}from"fs/promises";import{isAbsolute as w0,join as Vi,resolve as u0}from"path";import M from"process";import{pipeline as s0}from"stream/promises";import{createGzip as dh}from"zlib";import oi from"process";import pt from"process";import jr from"process";import{existsSync as Wr}from"fs";import{resolve as je}from"path";import{existsSync as y0}from"fs";import{exec as My}from"node:child_process";import Dh from"node:fs";import zy from"node:os";import Yt from"node:path";import Y$ from"node:process";import{promisify as Gy}from"node:util";import Pi from"node:crypto";import Qt from"node:fs";import Xe from"node:path";import{execSync as gh}from"node:child_process";import Qr from"node:os";var Gm=_s(import.meta.url);class Ph{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!nh(t))return!0;return rh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=nh(n)?rh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class vh{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Dr=new Ph,Pe=new vh,a0=Object.defineProperty,A0=(t)=>t;function m0(t,i){this[t]=A0.bind(null,i)}var E0=(t,i)=>{for(var n in i)a0(t,n,{get:i[n],enumerable:!0,configurable:!0,set:m0.bind(i,n)})},T0=(t,i)=>()=>(t&&(i=t(t=0)),i),ph={};E0(ph,{withErrorRecovery:()=>i$,tryLoadConfig:()=>O0,loadConfigWithResult:()=>q0,loadConfig:()=>c$,isRetryableError:()=>Z0,isConfigNotFoundError:()=>I0,isBunfigError:()=>n$,globalPerformanceMonitor:()=>Bn,globalCache:()=>bi,getEnvOrDefault:()=>H0,generateConfigTypes:()=>D0,defaultGeneratedDir:()=>a$,defaultConfigDir:()=>y$,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>r$,createLibraryConfig:()=>L0,config:()=>x0,bunfigPlugin:()=>k0,applyEnvVarsToConfig:()=>An,TypeGenerationError:()=>Le,SchemaValidationError:()=>Sn,PluginError:()=>Ve,PerformanceMonitor:()=>pe,FileSystemError:()=>De,ErrorFactory:()=>ui,EnvVarError:()=>br,EnvProcessor:()=>nf,ConfigValidator:()=>nc,ConfigValidationError:()=>xe,ConfigNotFoundError:()=>gr,ConfigMergeError:()=>Oe,ConfigLoader:()=>rc,ConfigLoadError:()=>Tn,ConfigFileLoader:()=>rf,ConfigCache:()=>ve,CacheUtils:()=>h$,BunfigError:()=>Tt,BrowserConfigError:()=>ke,ArrayMergeStrategies:()=>u$});class ve{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!fh(t))return!0;return eh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=fh(n)?eh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class pe{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function S0(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function R0(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function B0(t){return t.getStats().size*2}function Qe(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&O(i[0])&&"id"in i[0]&&i[0].id===3&&O(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(O(i)&&O(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(O(t)&&"arr"in t&&Array.isArray(t.arr)&&O(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&O(i[0])&&O(t[0])){let r=[...i];for(let f of t)if(O(f)&&"name"in f){if(!r.find((e)=>O(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(O(f)&&"path"in f){if(!r.find((e)=>O(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Lr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!O(i)||!O(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(O(f)&&O(n[r]))n[r]=Qe(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&O(f[0])&&O(n[r][0])){let e=[...f];for(let c of n[r])if(O(c)&&"name"in c){if(!e.find((h)=>O(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(O(c)&&"path"in c){if(!e.find((h)=>O(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((h)=>Lr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function Lr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Lr(t[n],i[n]))return!1;return!0}if(O(t)&&O(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Lr(t[f],i[f]))return!1}return!0}return!1}function O(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function C0(t,i){if(!Xh(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return Qe(i,r)}catch{return null}}catch{return null}}async function F0({name:t="",cwd:i,defaultConfig:n}){let r=i||ze.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let h of f){let l=xr(r,`${c}${h}`),$=await C0(l,n);if($!==null)return $}try{let c=xr(r,"package.json");if(Xh(c)){let h=(await import(c))[t];if(h&&typeof h==="object"&&!Array.isArray(h))try{return Qe(n,h)}catch{}}}catch{}return n}function N0(t,i={}){let n=qr.cwd();while(n.includes("storage"))n=hh(n,"..");let r=hh(n,t||"");if(i?.relative)return Ms(qr.cwd(),r);return r}async function J0(){try{let t=await F0({name:"clarity",defaultConfig:Hr,cwd:qr.cwd(),endpoint:"",headers:{}});return{...Hr,...t}}catch{return Hr}}function k(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _0(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pt<"u"){let t=Pt.type;if(t==="renderer"||t==="worker")return!1;return!!(Pt.versions&&(Pt.versions.node||Pt.versions.bun))}return!1}class Qh{async format(t){let i=await _0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:xi.pid,hostname:i(),environment:xi.env.NODE_ENV||"development",platform:xi.platform,version:xi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xi.env.NODE_ENV||xi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Ke},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Qh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??ct.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Mr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Mr};return{...Mr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ke.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await xs(this.config.logDirectory,sh.F_OK|sh.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Os(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 h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:$i.from(t);try{if(!Se(this.currentLogFile))await Re(this.currentLogFile,"",{mode:420});if(r=uh(this.currentLogFile,"a",420),qs(r,h,{flag:"a"}),wh(r),r!==void 0)Te(r),r=void 0;if((await Ki(this.currentLogFile)).size===0){if(await Re(this.currentLogFile,h,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{Te(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return qi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,h])=>h.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ee(16).toString("hex")}generateKey(){return Ee(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Ee(16),r=zs("aes-256-gcm",i,n),f=$i.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:$i.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=ah(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i($i.from($i.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Sr(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ki(n).catch(()=>null))try{if(await yh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Rr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Re(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ki(n).catch(()=>null))await yh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Sr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Rr(qi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=$h(t),r=Ks(i),f=ah();await Ds(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Se(this.currentLogFile))try{let t=uh(this.currentLogFile,"r+");wh(t),Te(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Sr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Rr(qi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?q.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=ct.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${q.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!k()){let $=$$[t],w=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",s;switch(t){case"debug":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:q.gray(c),level:t}),console.error(s);break;case"info":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s);break;case"success":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:q.green(c),level:t}),console.error(s);break;case"warning":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.warn(s);break;case"error":if(s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s),h){let y=h.split(`
|
|
61
|
+
`);for(let u of y)if(u.trim()&&!u.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:q.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let l=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
|
|
62
|
+
`;if(h)l+=`${h}
|
|
63
|
+
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!k()){let n=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:q.blue("◐"),tag:n,message:`${q.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
64
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let $=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:q.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!k())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new kr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!Se(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $h(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=$i.isBuffer(t)?t:$i.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),h=Gs("aes-256-gcm",n,f);return h.setAuthTag(e),$i.concat([h.update(c),h.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i);if(this.fancy&&!k()){let e=t.split(`
|
|
65
|
+
`),c=Math.max(...e.map((w)=>w.length))+2,h=`┌${"─".repeat(c)}┐`,l=`└${"─".repeat(c)}┘`,$=e.map((w)=>{let s=" ".repeat(c-w.length-2);return`│ ${w}${s} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:q.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(h)})),$.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(l),showTimestamp:!1}))}else if(!k())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let f=`${r} ${this.environment}.INFO: [BOX] ${t}
|
|
66
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${q.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();ct.stdin.removeListener("data",n);try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!1)}catch{}ct.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!0)}catch{}ct.stdin.resume(),ct.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let f=/%([sdijfo%])/g,e=0;if(n=t.replace(f,(c,h)=>{if(h==="%")return"%";if(e>=i.length)return c;let l=i[e++];switch(h){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return c}}),e<i.length)n+=` ${i.slice(e).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!k()){let f=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",e=q.blue("◐");console.error(`${e} ${f} ${q.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
67
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,r)),f!==void 0)this.activeProgressBar.message=f;let e=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,e)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;ct.stdout.write(`${"\r".padEnd(ct.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=q.green("━".repeat(r)),c=q.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=i||n===100?q.green("✓"):q.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=ct.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,ct.stdout.write(t.lastRenderedLine),i)ct.stdout.write(`
|
|
68
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Sr(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=qi(this.config.logDirectory,r);if(t.before)try{if((await Ki(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Rr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Zr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&z(i[0])&&"id"in i[0]&&i[0].id===3&&z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(z(i)&&z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(z(t)&&"arr"in t&&Array.isArray(t.arr)&&z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&z(i[0])&&z(t[0])){let r=[...i];for(let f of t)if(z(f)&&"name"in f){if(!r.find((e)=>z(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(z(f)&&"path"in f){if(!r.find((e)=>z(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Vr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!z(i)||!z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(z(f)&&z(n[r]))n[r]=Zr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&z(f[0])&&z(n[r][0])){let e=[...f];for(let c of n[r])if(z(c)&&"name"in c){if(!e.find((h)=>z(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(z(c)&&"path"in c){if(!e.find((h)=>z(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((h)=>Vr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function tc(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Zr(t,i);if(Array.isArray(t))return n==="replace"?i:Zr(t,i);if(!z(i)||!z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Zr(c,e);else if(z(e)&&z(c))r[f]=tc(c,e,n);else r[f]=e}return r}function Vr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Vr(t[n],i[n]))return!1;return!0}if(z(t)&&z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Vr(t[f],i[f]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Yr(t,i,n="replace"){if(!bh(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return tc(i,f,n)}catch{return null}}catch{return null}}function U0(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${r}_${s.map(y).join("_")}`,m=`${r}_${s.map((A)=>A.toUpperCase()).join("_")}`;if(n)ht.info(`Checking environment variable ${u} for config ${t}.${s.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))l[$]=e(w,s);else{let A=En.env[u]||En.env[m];if(A!==void 0){if(n)ht.info(`Using environment variable ${A?u:m} for config ${t}.${s.join(".")}`);if(typeof w==="number")l[$]=Number(A);else if(typeof w==="boolean")l[$]=A.toLowerCase()==="true";else if(Array.isArray(w))try{let T=JSON.parse(A);if(Array.isArray(T))l[$]=T;else l[$]=A.split(",").map((E)=>E.trim())}catch{l[$]=A.split(",").map((T)=>T.trim())}else l[$]=A}}}return l}return e(f)}async function d0({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:h="replace"}){let l=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?U0(t,f,e):f,$=n||En.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(e)ht.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let s=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,st($,"config"),st($,".config"),r?st($,r):void 0].filter(Boolean)));for(let T of A){if(e)ht.info(`Searching for configuration in: ${T}`);let E=[st($,"config"),st($,".config")].concat(r?[st($,r)]:[]).includes(T)?[...s,...y,...u,...m]:[...y,...s,...m,...u];for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from: ${J}`);return d}}}if(t){let T=st(me(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)ht.info(`Checking user config directory: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user config directory: ${J}`);return d}}}if(t){let T=st(me(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)ht.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user config directory dotfile: ${J}`);return d}}}if(t){let T=me(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)ht.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user home directory: ${J}`);return d}}}try{let T=st($,"package.json");if(bh(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)ht.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)ht.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return tc(l,R,h)}catch(N){if(e)ht.warn("Failed to merge package.json config:",N)}}}catch(T){if(e)ht.warn("Failed to load package.json:",T)}if(e)ht.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function j0(t,i={}){let n=Kr.cwd();while(n.includes("storage"))n=lh(n,"..");let r=lh(n,t||"");if(i?.relative)return Zs(Kr.cwd(),r);return r}async function W0(){try{let t=await d0({name:"clarity",alias:"logging",defaultConfig:zr,cwd:Kr.cwd()});return{...zr,...t||{}}}catch{return zr}}function P(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Y0(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class t${async format(t){let i=await Y0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Li.pid,hostname:i(),environment:Li.env.NODE_ENV||"development",platform:Li.platform,version:Li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Li.env.NODE_ENV||Li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class or{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...qe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new t$,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Gr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Gr};return{...Gr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:qe.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await gs(this.config.logDirectory,Th.F_OK|Th.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await bs(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 h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:gt.from(t);try{if(!Br(this.currentLogFile))await Fe(this.currentLogFile,"",{mode:420});if(r=Eh(this.currentLogFile,"a",420),os(r,h,{flag:"a"}),mh(r),r!==void 0)Ce(r),r=void 0;if((await Oi(this.currentLogFile)).size===0){if(await Fe(this.currentLogFile,h,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{Ce(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Di(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 Di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,h])=>h.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Be(16).toString("hex")}generateKey(){return Be(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Be(16),r=Ls("aes-256-gcm",i,n),f=gt.isBuffer(t)?t:gt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=gt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Rh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(gt.from(gt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Oi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Cr(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Oi(n).catch(()=>null))try{if(await Sh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Fr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Fe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Oi(n).catch(()=>null))await Sh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Cr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Fr(Di(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=Ah(t),r=Vs(i),f=Rh();await vs(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Br(this.currentLogFile))try{let t=Eh(this.currentLogFile,"r+");mh(t),Ce(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Cr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Fr(Di(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof H.env.NO_COLOR<"u",i=H.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=H.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${W.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=W.underline(W.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>W.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>W.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>W.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>W.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>W.strikethrough(r)),i}supportsHyperlinks(){if(P())return!1;let t=H.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=H.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(Xs(i)||i.startsWith("./")||i.startsWith("../"))i=Ps(i);else return null;return Br(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":w$[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:W.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:W.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
69
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:W.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
70
|
+
`;if(h)w+=`${h}
|
|
71
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(f,e)=>{},finish:(f)=>{},interrupt:(f,e)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,e)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),e!==void 0)this.activeProgressBar.message=e;if(this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,e="info")=>{if(!P()&&H.stdout.isTTY)H.stdout.write(`
|
|
72
|
+
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:n,message:`${W.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
73
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":W.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new or(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Br(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ah(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=gt.isBuffer(t)?t:gt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=ks("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=gt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
74
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:W.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
75
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${h}${c} ${W.cyan(r)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
76
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=W.green("━".repeat(r)),c=W.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?W.green("✓"):W.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=H.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,H.stdout.write(t.lastRenderedLine),i)H.stdout.write(`
|
|
77
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Cr(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Di(this.config.logDirectory,r);if(t.before)try{if((await Oi(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Fr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function i$(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function n$(t){return t instanceof Tt}function I0(t){return t instanceof gr}function Z0(t){if(n$(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class nf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Bn.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=Nr.env[l]||($?Nr.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=Nr.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof br)throw s;throw ui.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw ui.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(Nr.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
78
78
|
|
|
79
79
|
`;for(let r of t)n+=`${r.key}
|
|
80
80
|
`,n+=` Type: ${r.type}
|
|
@@ -86,25 +86,25 @@ export type ConfigOf = Config
|
|
|
86
86
|
`;n+=`| Variable | Type | Description | Example |
|
|
87
87
|
`,n+=`|----------|------|-------------|----------|
|
|
88
88
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
89
|
-
`;return n}}function uu(t,i){let n=Vl("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function Ol(t,i,n={}){return Ll(t,i,n,new WeakMap)}function Ll(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return kl(t,i,f,r);if(!Jt(i)||!Jt(t))return i;return Eu(t,i,n,r)}function kl(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return au(t,i);case"smart":return Au(t,i,r);default:return i}return i}function au(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Fe(f,r)))n.push(r);return n}function Au(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Jt(i[0])&&Jt(t[0]))return mu(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function mu(t,i,n){let r=[...i];for(let f of t){if(!Jt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((h)=>Jt(h)&&(l in h)&&h[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function Eu(t,i,n,r){let f=i;if(Jt(f)&&r.has(f))return r.get(f);let e={...t};if(Jt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Jt(l)&&Jt(h))e[c]=Ll(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=kl(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function xe(t,i,n="replace"){return Ol(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Fe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Fe(t[n],i[n]))return!1;return!0}if(Jt(t)&&Jt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Fe(t[f],i[f]))return!1}return!0}return!1}function Jt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class gr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let s=oi.getWithFileCheck("file",t);if(s){if(l)console.log(`Configuration loaded from cache: ${t}`);return s}}let h=async()=>{if(!mr(t))return null;try{let s=`?t=${Date.now()}`,$=await import(t+s),w=$.default||$,u="default"in $,y=Object.keys($).length>0;if(!u&&!y)throw new un(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new un(t,Error("Configuration must export a valid object"),"unknown");let E={config:xe(i,w,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)oi.setWithFileCheck("file",E,t,e);return E}catch(s){throw s instanceof Error?si.configLoad(t,s):si.configLoad(t,Error(String(s)))}};if(c)return mn.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push($e(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return Dl(async()=>{return mr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!mr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=$e(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=$e(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!mr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Oe{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,s=async()=>{let $=[],w=[],u={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,u);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],u);else return this.validateWithJSONSchema(t,i,u)}catch(y){return $.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:$,warnings:w}}};if(l)return await mn.track("validateConfiguration",s);return s()}async validateWithSchemaFile(t,i,n){try{if(!Yy(i))throw new an(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new an(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let s=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,s,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:vl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Le{fileLoader=new gr;envProcessor=new Vr;validator=new Oe;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let s=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if(s)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let $=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),w=!$&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),u=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if(s&&(u||$))throw h;if(w&&(!s||!u))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!s)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){let h=Date.now()-i;throw It.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:s="replace",verbose:$=!1}=t,w=e||yi.cwd(),u=[],y=await this.loadLocalConfiguration(r,f,w,c,l,s,$,h,n);if(y)return u.push(...this.getLocalSearchPaths(r,f,w,c)),this.finalizeResult(y,u,h,r,$);let E=await this.loadHomeConfiguration(r,f,l,s,$,h);if(E)return u.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(E,u,h,r,$);let A=await this.loadPackageJsonConfiguration(r,f,w,l,s,$,h);if(A)return u.push(yt(w,"package.json")),this.finalizeResult(A,u,h,r,$);if(u.push(...this.getAllSearchPaths(r,f,w,c)),i)throw si.configNotFound(r,u,f);return{...await this.applyEnvironmentVariables(r,l,h,$),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let s=l?$n(t,f,c):f,$=this.getLocalDirectories(n,r);for(let w of $){if(c)It.info(`Searching for configuration in: ${w}`);let u=this.fileLoader.generateConfigPaths(t,w,i),y=await this.fileLoader.tryLoadFromPaths(u,s,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(y){if(c)It.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?$n(t,n,f):n,l=[yt(Hi(),".config",t),yt(Hi(),".config"),Hi()];for(let h of l){if(f)It.info(`Checking home directory: ${h}`);let s=this.fileLoader.generateConfigPaths(t,h,i),$=await this.fileLoader.tryLoadFromPaths(s,c,{arrayStrategy:r,verbose:f});if($){if(f)It.success(`Configuration loaded from home directory: ${$.source.path}`);return $}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?$n(t,r,e):r;try{let h=yt(n,"package.json");if(!Be(h))return null;let s=await import(h),$=s[t],w=t;if(!$&&i)$=s[i],w=i;if($&&typeof $==="object"&&!Array.isArray($)){if(e)It.success(`Configuration loaded from package.json: ${w}`);return{config:xe(l,$,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)It.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$n(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw si.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return oi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);oi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(yt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[yt(Hi(),".config",t),yt(Hi(),".config"),Hi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function al(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||n}async function Tu(t){return Qt.loadConfig({...t,__strictErrorHandling:!0})}async function ol(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await Qt.loadConfig(t);else r=await Qt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)It.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Qt.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function Su(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await Qt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&al(n)))return(await Qt.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await Qt.loadConfig({...t,cwd:t.cwd||yi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&al(i)))return(await Qt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Ru(t,i,n="replace"){let r=new gr;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function $n(t,i,n=!1){let r=new Vr,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[s,$]of Object.entries(c)){let w=[...l,s],u=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((A)=>A.toUpperCase()).join("")}`,`${f}_${w.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,E;for(let A of u)if(y=yi.env[A],y!==void 0){E=A;break}if(y!==void 0&&E)if(typeof $==="boolean")h[s]=["true","1","yes"].includes(y.toLowerCase());else if(typeof $==="number"){let A=Number(y);if(!Number.isNaN(A))h[s]=A}else if(Array.isArray($))try{h[s]=JSON.parse(y)}catch{h[s]=y.split(",").map((A)=>A.trim())}else h[s]=y;else if($&&typeof $==="object"&&!Array.isArray($))h[s]=e($,w)}return h}return e(i)}function Bu(t){let i=yt(yi.cwd(),t.configDir),n=yt(yi.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!Be(oh(r)))ly(oh(r),{recursive:!0,mode:511});let f=Be(i)?sy(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Pu}
|
|
89
|
+
`;return n}}function H0(t,i){let n=l$("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function r$(t,i,n={}){return f$(t,i,n,new WeakMap)}function f$(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return e$(t,i,f,r);if(!Jt(i)||!Jt(t))return i;return K0(t,i,n,r)}function e$(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return M0(t,i);case"smart":return z0(t,i,r);default:return i}return i}function M0(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Ge(f,r)))n.push(r);return n}function z0(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Jt(i[0])&&Jt(t[0]))return G0(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function G0(t,i,n){let r=[...i];for(let f of t){if(!Jt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find((l)=>Jt(l)&&(h in l)&&l[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function K0(t,i,n,r){let f=i;if(Jt(f)&&r.has(f))return r.get(f);let e={...t};if(Jt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Jt(h)&&Jt(l))e[c]=f$(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=e$(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function ic(t,i,n="replace"){return r$(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ge(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Ge(t[n],i[n]))return!1;return!0}if(Jt(t)&&Jt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Ge(t[f],i[f]))return!1}return!0}return!1}function Jt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class rf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=bi.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Jr(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new Tn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new Tn(t,Error("Configuration must export a valid object"),"unknown");let m={config:ic(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)bi.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?ui.configLoad(t,$):ui.configLoad(t,Error(String($)))}};if(c)return Bn.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Ne(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return i$(async()=>{return Jr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Jr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Ne(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Ne(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Jr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class nc{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await Bn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!ps(i))throw new Sn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new Sn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:s$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class rc{fileLoader=new rf;envProcessor=new nf;validator=new nc;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){let l=Date.now()-i;throw It.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||mi.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(yt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw ui.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?An(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)It.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)It.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?An(t,n,f):n,h=[yt(Gi(),".config",t),yt(Gi(),".config"),Gi()];for(let l of h){if(f)It.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)It.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?An(t,r,e):r;try{let l=yt(n,"package.json");if(!Me(l))return null;let $=await import(l),w=$[t],s=t;if(!w&&i)w=$[i],s=i;if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)It.success(`Configuration loaded from package.json: ${s}`);return{config:ic(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)It.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:An(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw ui.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return bi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);bi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(yt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[yt(Gi(),".config",t),yt(Gi(),".config"),Gi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function jh(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||n}async function q0(t){return ti.loadConfig({...t,__strictErrorHandling:!0})}async function c$(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ti.loadConfig(t);else r=await ti.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)It.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ti.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function x0(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ti.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&jh(n)))return(await ti.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ti.loadConfig({...t,cwd:t.cwd||mi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&jh(i)))return(await ti.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function O0(t,i,n="replace"){let r=new rf;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function An(t,i,n=!1){let r=new nf,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=mi.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}function D0(t){let i=yt(mi.cwd(),t.configDir),n=yt(mi.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!Me(ch(r)))js(ch(r),{recursive:!0,mode:511});let f=Me(i)?Ws(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Ey}
|
|
90
90
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
91
|
-
|
|
92
|
-
${f.map((
|
|
91
|
+
`;Ys(r,e,{mode:438})}function L0(t){let i=null,n=null,r=()=>{if(!n)n=c$(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)It.warn("Config loading failed, using defaults:",[e instanceof Error?e:Error(String(e))]);return c});return n},f="defaultConfig"in t?t.defaultConfig:{};return i=f,r(),new Proxy({},{get(e,c){if(i)return i[c];let h=f[c];return r(),h},has(e,c){return c in(i||f)},ownKeys(){return Object.keys(i||f)},getOwnPropertyDescriptor(e,c){return Object.getOwnPropertyDescriptor(i||f,c)},set(e,c,h){if(!i)i={...f};return i[c]=h,!0}})}function k0(t){let i=Bh(i0.cwd(),t?.configDir||"./config");function n(){if(!Qs(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=t0(i).filter((l)=>f.has(Je(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),h=new Map;for(let{base:l,file:$}of c){let w=Je($).toLowerCase(),s=h.get(l);if(!s){h.set(l,$);continue}let y=Je(s).toLowerCase();if(e.indexOf(w)<e.indexOf(y))h.set(l,$)}return Array.from(h.entries()).map(([l,$])=>({base:l,file:$})).sort((l,$)=>l.base.localeCompare($.base))}function r(){let f=n(),e=f.map((l)=>l.base),c=e.length?e.map((l)=>`'${l}'`).join(" | "):"string",h=f.length?`{
|
|
92
|
+
${f.map((l)=>{let $=Bh(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${$}').default`}).join(`,
|
|
93
93
|
`)}
|
|
94
94
|
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
95
|
-
export type ConfigByName = ${
|
|
95
|
+
export type ConfigByName = ${h}
|
|
96
96
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
97
97
|
export type ConfigOf = Config
|
|
98
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Vl,oi,mn,gl,Cu,Ju,Al,Jr,Ce,ct,q,_u,ml,Uu,El,ju,du,me,Wu,Tl,Sl,Ee,Yu,Iu,Zu,Hu,_r,bl,Mu,ht,zu,Gu,Rl,Ur,Je,v,W,Ku,Bl,qu,Nl,Du,xu,Te,Ou,Fl,Cl,Lu,Se,ku,ou,Vu,gu,bu,jr,Xl,Xu,Pu="0.15.6",Tt,Kr,un,_e,Ue,qr,je,de,an,We,Ye,si,Pl,vl,It,Qt,pl,Ql,vu=vy(async()=>{Vl=import.meta.require,oi=new Ge,mn=new Ke,gl={createKey:py,isEquivalent:Qy,estimateMemoryUsage:tu},Cu=Yr(Ne.cwd(),"config"),Ju=Yr(Ne.cwd(),"src/generated"),Al=Wr.env.CLARITY_LOG_DIR||uy(ru(),"logs"),Jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Al,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ce=await fu(),ct={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},q=ct,_u=ct.red,ml=ct.green,Uu=ct.yellow,El=ct.blue,ju=ct.magenta,du=ct.cyan,me=ct.white,Wu=ct.gray,Tl=ct.bgRed,Sl=ct.bgYellow,Ee=ct.bold,Yu=ct.dim,Iu=ct.italic,Zu=ct.underline,Hu=ct.reset,_r={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bl={debug:"\uD83D\uDD0D",info:El("ℹ"),success:ml("✓"),warning:Sl(me(Ee(" WARN "))),error:Tl(me(Ee(" ERROR ")))},Mu=new Mr("stacks"),ht=new Mr("bunfig",{showTags:!0}),zu=wt(yn.cwd(),"config"),Gu=wt(yn.cwd(),"src/generated"),Rl=dr.env.CLARITY_LOG_DIR||wy(lu(),"logs"),Ur={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Je=await su(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=v,Ku=v.red,Bl=v.green,qu=v.yellow,Nl=v.blue,Du=v.magenta,xu=v.cyan,Te=v.white,Ou=v.gray,Fl=v.bgRed,Cl=v.bgYellow,Lu=v.bgGray,Se=v.bold,ku=v.dim,ou=v.italic,Vu=v.underline,gu=v.strikethrough,bu=v.reset,jr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Xl={debug:"\uD83D\uDD0D",info:Nl("ℹ"),success:Bl("✓"),warning:Cl(Te(Se(" WARN "))),error:Fl(Te(Se(" ERROR ")))},Xu=new Gr("stacks"),Tt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Kr=class extends Tt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${t}"${r} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}},un=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},_e=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}},Ue=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},qr=class extends Tt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}},je=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}},de=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}},an=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}},We=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}},Ye=class extends Tt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}},si={configNotFound(t,i,n){return new Kr(t,i,n)},configLoad(t,i,n){return new un(t,i,n)},configValidation(t,i,n){return new _e(t,i,n)},configMerge(t,i,n,r){return new Ue(t,i,n,r)},envVar(t,i,n,r){return new qr(t,i,n,r)},fileSystem(t,i,n){return new je(t,i,n)},typeGeneration(t,i,n){return new de(t,i,n)},schemaValidation(t,i,n){return new an(t,i,n)},browserConfig(t,i,n,r){return new We(t,i,n,r)},plugin(t,i,n){return new Ye(t,i,n)}},Pl={replace:"replace",concat:"concat",smart:"smart"},vl=/^https?:\/\//,It=new Gr("bunfig",{showTags:!0}),Qt=new Le,pl=yt(yi.cwd(),"config"),Ql=yt(yi.cwd(),"src/generated")});function pu(t,i={}){let n=Ir.cwd();while(n.includes("storage"))n=hl(n,"..");let r=hl(n,t||"");if(i?.relative)return zy(Ir.cwd(),r);return r}var Qu=Ir.env.CLARITY_LOG_DIR||My(pu(),"logs"),ts={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Qu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dr={...ts},q1=(async()=>{try{let{loadConfig:t}=await vu().then(()=>Gl),i=await t({name:"clarity",alias:"logging",defaultConfig:ts,cwd:Ir.cwd()});if(i)Object.assign(Dr,i)}catch{}return Dr})();function p(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ta(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class is{async format(t){let i=await ta(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Li.pid,hostname:i(),environment:Li.env.NODE_ENV||"development",platform:Li.platform,version:Li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Li.env.NODE_ENV||Li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var tt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},I=tt,D1=tt.red,ia=tt.green,x1=tt.yellow,na=tt.blue,O1=tt.magenta,L1=tt.cyan,Jl=tt.white,k1=tt.gray,ra=tt.bgRed,fa=tt.bgYellow,o1=tt.bgGray,_l=tt.bold,V1=tt.dim,g1=tt.italic,b1=tt.underline,X1=tt.strikethrough,P1=tt.reset,Re={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ea={debug:"\uD83D\uDD0D",info:na("ℹ"),success:ia("✓"),warning:fa(Jl(_l(" WARN "))),error:ra(Jl(_l(" ERROR ")))};class br{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Dr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new is,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Re,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Re};return{...Re,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Dr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await xy(this.config.logDirectory,wl.F_OK|wl.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Oy(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:gt.from(t);try{if(!Er(this.currentLogFile))await ae(this.currentLogFile,"",{mode:420});if(r=$l(this.currentLogFile,"a",420),Dy(r,l,{flag:"a"}),sl(r),r!==void 0)ue(r),r=void 0;if((await xi(this.currentLogFile)).size===0){if(await ae(this.currentLogFile,l,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let s=h;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(f<e-1){let $=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,$);let w=c*2**f;await new Promise((u)=>setTimeout(u,w)),f++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(r!==void 0)try{ue(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let s=l,$=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),l}f++;let h=c*2**(f-1);await new Promise((s)=>setTimeout(s,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Oi(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 Oi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Oi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ye(16).toString("hex")}generateKey(){return ye(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=ye(16),r=Gy("aes-256-gcm",i,n),f=gt.isBuffer(t)?t:gt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),s=gt.allocUnsafe(16+l+16);return n.copy(s,0),e.copy(s,16),c.copy(s,16+e.length),h.copy(s,16+l),{encrypted:s,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=ul(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(gt.from(gt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await xi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Tr(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,s)=>{let $=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0")-$}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await xi(n).catch(()=>null))try{if(await yl(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Sr(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await ae(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await xi(n).catch(()=>null))await yl(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Tr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Sr(Oi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=ll(t),r=qy(i),f=ul();await oy(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Er(this.currentLogFile))try{let t=$l(this.currentLogFile,"r+");sl(t),ue(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Tr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Sr(Oi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?I.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof M.env.NO_COLOR<"u",i=M.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(c)y.push(i);if(e==="warning")y.push("WARN");else if(e==="error")y.push("ERROR");else if(n)y.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)y.push(r.replace(/[[\]]/g,""));return y.push(f),y.join(" ")}let h=M.stdout.columns||120,s="";if(e==="warning"||e==="error")s=`${n} ${f}`;else if(e==="info"||e==="success")s=`${n} ${r} ${f}`;else s=`${n} ${r} ${I.cyan(f)}`;if(!c)return s.trim();let $=l(s).trim().length,w=l(i).length,u=Math.max(1,h-2-$-w);return`${s.trim()}${" ".repeat(u)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=I.underline(I.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",s="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>I.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>I.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>I.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>I.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>I.strikethrough(r)),i}supportsHyperlinks(){if(p())return!1;let t=M.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=M.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(Ly(i)||i.startsWith("./")||i.startsWith("../"))i=ky(i);else return null;return Er(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:s}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":ea[t],u=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:I.gray(h),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:I.green(h),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:f,icon:w,tag:u,message:h,level:t}),console.error(y),l){let E=l.split(`
|
|
99
|
-
`);for(let A of
|
|
100
|
-
`;if(
|
|
101
|
-
`;if(
|
|
102
|
-
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:n,message:`${I.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,
|
|
103
|
-
`,
|
|
104
|
-
`),
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${I.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();M.stdin.removeListener("data",n);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,
|
|
106
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=I.green("━".repeat(r)),c=I.gray("━".repeat(f)),
|
|
107
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
98
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var l$,bi,Bn,h$,V0,o0,Wh,Hr,Ke,lt,q,g0,Yh,b0,Ih,X0,P0,We,v0,Zh,Hh,Ye,p0,Q0,ty,iy,Mr,$$,ny,ht,ry,fy,Mh,zr,qe,v,W,ey,zh,cy,Gh,ly,hy,Ie,$y,Kh,qh,wy,Ze,uy,sy,yy,ay,Ay,Gr,w$,my,Ey="0.15.6",Tt,gr,Tn,xe,Oe,br,De,Le,Sn,ke,Ve,ui,u$,s$,It,ti,y$,a$,Ty=T0(async()=>{l$=import.meta.require,bi=new ve,Bn=new pe,h$={createKey:S0,isEquivalent:R0,estimateMemoryUsage:B0},V0=xr(ze.cwd(),"config"),o0=xr(ze.cwd(),"src/generated"),Wh=qr.env.CLARITY_LOG_DIR||Hs(N0(),"logs"),Hr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ke=await J0(),lt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},q=lt,g0=lt.red,Yh=lt.green,b0=lt.yellow,Ih=lt.blue,X0=lt.magenta,P0=lt.cyan,We=lt.white,v0=lt.gray,Zh=lt.bgRed,Hh=lt.bgYellow,Ye=lt.bold,p0=lt.dim,Q0=lt.italic,ty=lt.underline,iy=lt.reset,Mr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$$={debug:"\uD83D\uDD0D",info:Ih("ℹ"),success:Yh("✓"),warning:Hh(We(Ye(" WARN "))),error:Zh(We(Ye(" ERROR ")))},ny=new kr("stacks"),ht=new kr("bunfig",{showTags:!0}),ry=st(En.cwd(),"config"),fy=st(En.cwd(),"src/generated"),Mh=Kr.env.CLARITY_LOG_DIR||Is(j0(),"logs"),zr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qe=await W0(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=v,ey=v.red,zh=v.green,cy=v.yellow,Gh=v.blue,ly=v.magenta,hy=v.cyan,Ie=v.white,$y=v.gray,Kh=v.bgRed,qh=v.bgYellow,wy=v.bgGray,Ze=v.bold,uy=v.dim,sy=v.italic,yy=v.underline,ay=v.strikethrough,Ay=v.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w$={debug:"\uD83D\uDD0D",info:Gh("ℹ"),success:zh("✓"),warning:qh(Ie(Ze(" WARN "))),error:Kh(Ie(Ze(" ERROR ")))},my=new or("stacks"),Tt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},gr=class extends Tt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${t}"${r} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}},Tn=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},xe=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}},Oe=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},br=class extends Tt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}},De=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Le=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Sn=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}},ke=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}},Ve=class extends Tt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}},ui={configNotFound(t,i,n){return new gr(t,i,n)},configLoad(t,i,n){return new Tn(t,i,n)},configValidation(t,i,n){return new xe(t,i,n)},configMerge(t,i,n,r){return new Oe(t,i,n,r)},envVar(t,i,n,r){return new br(t,i,n,r)},fileSystem(t,i,n){return new De(t,i,n)},typeGeneration(t,i,n){return new Le(t,i,n)},schemaValidation(t,i,n){return new Sn(t,i,n)},browserConfig(t,i,n,r){return new ke(t,i,n,r)},plugin(t,i,n){return new Ve(t,i,n)}},u$={replace:"replace",concat:"concat",smart:"smart"},s$=/^https?:\/\//,It=new or("bunfig",{showTags:!0}),ti=new rc,y$=yt(mi.cwd(),"config"),a$=yt(mi.cwd(),"src/generated")});function Sy(t,i={}){let n=Or.cwd();while(n.includes("storage"))n=Ch(n,"..");let r=Ch(n,t||"");if(i?.relative)return r0(Or.cwd(),r);return r}var Ry=Or.env.CLARITY_LOG_DIR||n0(Sy(),"logs"),A$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ry,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xr={...A$},hE=(async()=>{try{let{loadConfig:t}=await Ty().then(()=>ph),i=await t({name:"clarity",alias:"logging",defaultConfig:A$,cwd:Or.cwd()});if(i)Object.assign(Xr,i)}catch{}return Xr})();function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function By(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class m${async format(t){let i=await By(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:oi.pid,hostname:i(),environment:oi.env.NODE_ENV||"development",platform:oi.platform,version:oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:oi.env.NODE_ENV||oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},I=it,$E=it.red,Cy=it.green,wE=it.yellow,Fy=it.blue,uE=it.magenta,sE=it.cyan,xh=it.white,yE=it.gray,Ny=it.bgRed,Jy=it.bgYellow,aE=it.bgGray,Oh=it.bold,AE=it.dim,mE=it.italic,EE=it.underline,TE=it.strikethrough,SE=it.reset,He={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_y={debug:"\uD83D\uDD0D",info:Fy("ℹ"),success:Cy("✓"),warning:Jy(xh(Oh(" WARN "))),error:Ny(xh(Oh(" ERROR ")))};class ff{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Xr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new m$,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...He,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...He};return{...He,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Xr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await h0(this.config.logDirectory,_h.F_OK|_h.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await $0(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 h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!_r(this.currentLogFile))await de(this.currentLogFile,"",{mode:420});if(r=Jh(this.currentLogFile,"a",420),l0(r,h,{flag:"a"}),Nh(r),r!==void 0)Ue(r),r=void 0;if((await ki(this.currentLogFile)).size===0){if(await de(this.currentLogFile,h,{flag:"w",mode:420}),(await ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{Ue(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vi(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 Vi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Vi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,h])=>h.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return _e(16).toString("hex")}generateKey(){return _e(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=_e(16),r=f0("aes-256-gcm",i,n),f=bt.isBuffer(t)?t:bt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=bt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=dh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(bt.from(bt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ur(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await ki(n).catch(()=>null))try{if(await Uh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await dr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await de(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await ki(n).catch(()=>null))await Uh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Ur(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await dr(Vi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=Fh(t),r=c0(i),f=dh();await s0(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),_r(this.currentLogFile))try{let t=Jh(this.currentLogFile,"r+");Nh(t),Ue(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ur(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await dr(Vi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?I.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof M.env.NO_COLOR<"u",i=M.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=M.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${I.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=I.underline(I.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>I.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>I.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>I.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>I.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>I.strikethrough(r)),i}supportsHyperlinks(){if(p())return!1;let t=M.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=M.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(w0(i)||i.startsWith("./")||i.startsWith("../"))i=u0(i);else return null;return _r(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":_y[t],y=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:I.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:I.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
99
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:I.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
100
|
+
`;if(h)w+=`${h}
|
|
101
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(f,e)=>{},finish:(f)=>{},interrupt:(f,e)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,e)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),e!==void 0)this.activeProgressBar.message=e;if(this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,e="info")=>{if(!p()&&M.stdout.isTTY)M.stdout.write(`
|
|
102
|
+
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:n,message:`${I.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
103
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":I.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new ff(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!_r(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=bt.isBuffer(t)?t:bt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=e0("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=bt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
104
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:I.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan(w),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
105
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${I.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();M.stdin.removeListener("data",n);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${h}${c} ${I.cyan(r)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
106
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=I.green("━".repeat(r)),c=I.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?I.green("✓"):I.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=M.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,M.stdout.write(t.lastRenderedLine),i)M.stdout.write(`
|
|
107
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Ur(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Vi(this.config.logDirectory,r);if(t.before)try{if((await ki(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await dr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var RE=new ff("stacks");class Mt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class E$ extends Mt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((e)=>`"${e}"`).join(", ")}`;super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class Pr extends Mt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}}class T$ extends Mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class S$ extends Mt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class fc extends Mt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}}class R$ extends Mt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class B$ extends Mt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class vr extends Mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class C$ extends Mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}}class F$ extends Mt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}}var Xi={configNotFound(t,i,n){return new E$(t,i,n)},configLoad(t,i,n){return new Pr(t,i,n)},configValidation(t,i,n){return new T$(t,i,n)},configMerge(t,i,n,r){return new S$(t,i,n,r)},envVar(t,i,n,r){return new fc(t,i,n,r)},fileSystem(t,i,n){return new R$(t,i,n)},typeGeneration(t,i,n){return new B$(t,i,n)},schemaValidation(t,i,n){return new vr(t,i,n)},browserConfig(t,i,n,r){return new C$(t,i,n,r)},plugin(t,i,n){return new F$(t,i,n)}};async function Uy(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class ec{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Pe.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=jr.env[l]||($?jr.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=jr.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof fc)throw s;throw Xi.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw Xi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(jr.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
108
108
|
|
|
109
109
|
`;for(let r of t)n+=`${r.key}
|
|
110
110
|
`,n+=` Type: ${r.type}
|
|
@@ -116,40 +116,43 @@ export type ConfigOf = Config
|
|
|
116
116
|
`;n+=`| Variable | Type | Description | Example |
|
|
117
117
|
`,n+=`|----------|------|-------------|----------|
|
|
118
118
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
119
|
-
`;return n}}function ha(t,i,n={}){return ss(t,i,n,new WeakMap)}function ss(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return $s(t,i,f,r);if(!_t(i)||!_t(t))return i;return wa(t,i,n,r)}function $s(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return la(t,i);case"smart":return sa(t,i,r);default:return i}return i}function la(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Ie(f,r)))n.push(r);return n}function sa(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(_t(i[0])&&_t(t[0]))return $a(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function $a(t,i,n){let r=[...i];for(let f of t){if(!_t(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((h)=>_t(h)&&(l in h)&&h[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function wa(t,i,n,r){let f=i;if(_t(f)&&r.has(f))return r.get(f);let e={...t};if(_t(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(_t(l)&&_t(h))e[c]=ss(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=$s(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function ws(t,i,n="replace"){return ha(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ie(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Ie(t[n],i[n]))return!1;return!0}if(_t(t)&&_t(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Ie(t[f],i[f]))return!1}return!0}return!1}function _t(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class ys{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let s=Zr.getWithFileCheck("file",t);if(s){if(l)console.log(`Configuration loaded from cache: ${t}`);return s}}let h=async()=>{if(!Br(t))return null;try{let s=`?t=${Date.now()}`,$=await import(t+s),w=$.default||$,u="default"in $,y=Object.keys($).length>0;if(!u&&!y)throw new xr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new xr(t,Error("Configuration must export a valid object"),"unknown");let E={config:ws(i,w,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Zr.setWithFileCheck("file",E,t,e);return E}catch(s){throw s instanceof Error?Vi.configLoad(t,s):Vi.configLoad(t,Error(String(s)))}};if(c)return ze.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Ae(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return ca(async()=>{return Br(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Br(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=Ae(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=Ae(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Br(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var ya=/^https?:\/\//;class us{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,s=async()=>{let $=[],w=[],u={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,u);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],u);else return this.validateWithJSONSchema(t,i,u)}catch(y){return $.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:$,warnings:w}}};if(l)return await ze.track("validateConfiguration",s);return s()}async validateWithSchemaFile(t,i,n){try{if(!Vy(i))throw new Or(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new Or(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let s=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,s,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ya},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var bt=new br("bunfig",{showTags:!0});function ua(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class as{fileLoader=new ys;envProcessor=new oe;validator=new us;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let s=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if(s)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let $=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),w=!$&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),u=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if(s&&(u||$))throw h;if(w&&(!s||!u))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!s)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)bt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let h=Date.now()-i;throw bt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:s="replace",verbose:$=!1}=t,w=e||or.cwd(),u=[],y=await this.loadLocalConfiguration(r,f,w,c,l,s,$,h,n);if(y)return u.push(...this.getLocalSearchPaths(r,f,w,c)),this.finalizeResult(y,u,h,r,$);let E=await this.loadHomeConfiguration(r,f,l,s,$,h);if(E)return u.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(E,u,h,r,$);let A=await this.loadPackageJsonConfiguration(r,f,w,l,s,$,h);if(A)return u.push(Ct(w,"package.json")),this.finalizeResult(A,u,h,r,$);if(u.push(...this.getAllSearchPaths(r,f,w,c)),i)throw Vi.configNotFound(r,u,f);return{...await this.applyEnvironmentVariables(r,l,h,$),warnings:[`No configuration file found for "${r}"${ua(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let s=l?Fr(t,f,c):f,$=this.getLocalDirectories(n,r);for(let w of $){if(c)bt.info(`Searching for configuration in: ${w}`);let u=this.fileLoader.generateConfigPaths(t,w,i),y=await this.fileLoader.tryLoadFromPaths(u,s,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(y){if(c)bt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Fr(t,n,f):n,l=[Ct(Zi(),".config",t),Ct(Zi(),".config"),Zi()];for(let h of l){if(f)bt.info(`Checking home directory: ${h}`);let s=this.fileLoader.generateConfigPaths(t,h,i),$=await this.fileLoader.tryLoadFromPaths(s,c,{arrayStrategy:r,verbose:f});if($){if(f)bt.success(`Configuration loaded from home directory: ${$.source.path}`);return $}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?Fr(t,r,e):r;try{let h=Ct(n,"package.json");if(!cy(h))return null;let s={};try{s=JSON.parse(hy(h,"utf8"))}catch(u){if(e)bt.warn("Failed to parse package.json:",[u instanceof Error?u:Error(String(u))]);return null}let $=s[t],w=t;if(!$&&i){let u=Array.isArray(i)?i:[i];for(let y of u){if(!y)continue;if(s[y]){$=s[y],w=y;break}}}if($&&typeof $==="object"&&!Array.isArray($)){if(e)bt.success(`Configuration loaded from package.json: ${w}`);return{config:ws(l,$,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)bt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Fr(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Vi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Zr.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Zr.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Ct(t,"config"),Ct(t,".config"),i?Ct(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Ct(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Ct(Zi(),".config",t),Ct(Zi(),".config"),Zi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var p1=new as;function Fr(t,i,n=!1){let r=new oe,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[s,$]of Object.entries(c)){let w=[...l,s],u=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((A)=>A.toUpperCase()).join("")}`,`${f}_${w.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,E;for(let A of u)if(y=or.env[A],y!==void 0){E=A;break}if(y!==void 0&&E)if(typeof $==="boolean")h[s]=["true","1","yes"].includes(y.toLowerCase());else if(typeof $==="number"){let A=Number(y);if(!Number.isNaN(A))h[s]=A}else if(Array.isArray($))try{h[s]=JSON.parse(y)}catch{h[s]=y.split(",").map((A)=>A.trim())}else h[s]=y;else if($&&typeof $==="object"&&!Array.isArray($))h[s]=e($,w)}return h}return e(i)}var Q1=Ct(or.cwd(),"config"),tE=Ct(or.cwd(),"src/generated"),As={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:ie.join(te.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ie.join(te.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ie.join(te.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},o=As,Zt={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 F={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},ki={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function Ze(t,i){let n=[];function r(f){let e;try{e=Ul.readdirSync(f)}catch{return}for(let c of e){let l=Yt.join(f,c);try{if(Ul.statSync(l).isDirectory())r(l);else if(c===i)n.push(f)}catch{continue}}}return r(t),n}function N(t,i,n){if(n||o.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Ea=ma(aa);function Es(){return ms.env.SUDO_PASSWORD}var jl="[redacted]",Ta=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Sa=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Ra(t){let i=t.toLowerCase();return Ta.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Lr(t){if(Array.isArray(t))return t.map((n)=>Lr(n));if(typeof t==="string")return Sa.test(t)?jl:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(Ra(n)){i[n]=jl;continue}i[n]=Lr(r)}return i}function Xr(t){return JSON.stringify(Lr(t))}function Ba(t){let i=Es();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let n=i.replace(/'/g,"'\\''"),r=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function li(t,i={}){let n=Ba(t);try{let{stdout:r,stderr:f}=await Ea(n,{cwd:i.cwd||ms.cwd(),timeout:i.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${t}
|
|
120
|
-
Error: ${r.message}`);throw f.stack=r.stack,f}}function
|
|
119
|
+
`;return n}}function dy(t,i,n={}){return N$(t,i,n,new WeakMap)}function N$(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return J$(t,i,f,r);if(!_t(i)||!_t(t))return i;return Iy(t,i,n,r)}function J$(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return jy(t,i);case"smart":return Wy(t,i,r);default:return i}return i}function jy(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>oe(f,r)))n.push(r);return n}function Wy(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(_t(i[0])&&_t(t[0]))return Yy(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Yy(t,i,n){let r=[...i];for(let f of t){if(!_t(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find((l)=>_t(l)&&(h in l)&&l[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Iy(t,i,n,r){let f=i;if(_t(f)&&r.has(f))return r.get(f);let e={...t};if(_t(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(_t(h)&&_t(l))e[c]=N$(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=J$(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function _$(t,i,n="replace"){return dy(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function oe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!oe(t[n],i[n]))return!1;return!0}if(_t(t)&&_t(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!oe(t[f],i[f]))return!1}return!0}return!1}function _t(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class U${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=Dr.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Wr(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new Pr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new Pr(t,Error("Configuration must export a valid object"),"unknown");let m={config:_$(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Dr.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?Xi.configLoad(t,$):Xi.configLoad(t,Error(String($)))}};if(c)return Pe.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(je(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return Uy(async()=>{return Wr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Wr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=je(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=je(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Wr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var Zy=/^https?:\/\//;class d${async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await Pe.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!y0(i))throw new vr(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new vr(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Zy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Xt=new ff("bunfig",{showTags:!0});function Hy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class j${fileLoader=new U$;envProcessor=new ec;validator=new d$;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Xt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let l=Date.now()-i;throw Xt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||tf.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(Nt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw Xi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${Hy(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?Ir(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)Xt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)Xt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Ir(t,n,f):n,h=[Nt(zi(),".config",t),Nt(zi(),".config"),zi()];for(let l of h){if(f)Xt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)Xt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?Ir(t,r,e):r;try{let l=Nt(n,"package.json");if(!Us(l))return null;let $={};try{$=JSON.parse(ds(l,"utf8"))}catch(y){if(e)Xt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let w=$[t],s=t;if(!w&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if($[u]){w=$[u],s=u;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)Xt.success(`Configuration loaded from package.json: ${s}`);return{config:_$(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)Xt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ir(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Xi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Dr.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Dr.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Nt(t,"config"),Nt(t,".config"),i?Nt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Nt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Nt(zi(),".config",t),Nt(zi(),".config"),zi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var BE=new j$;function Ir(t,i,n=!1){let r=new ec,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=tf.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}var CE=Nt(tf.cwd(),"config"),FE=Nt(tf.cwd(),"src/generated"),W$={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:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},V=W$,Zt={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 F={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},gi={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function ge(t,i){let n=[];function r(f){let e;try{e=Dh.readdirSync(f)}catch{return}for(let c of e){let h=Yt.join(f,c);try{if(Dh.statSync(h).isDirectory())r(h);else if(c===i)n.push(f)}catch{continue}}}return r(t),n}function C(t,i,n){if(n||V.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Ky=Gy(My);function I$(){return Y$.env.SUDO_PASSWORD}var Lh="[redacted]",qy=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),xy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Oy(t){let i=t.toLowerCase();return qy.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function pr(t){if(Array.isArray(t))return t.map((n)=>pr(n));if(typeof t==="string")return xy.test(t)?Lh:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(Oy(n)){i[n]=Lh;continue}i[n]=pr(r)}return i}function ef(t){return JSON.stringify(pr(t))}function Dy(t){let i=I$();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let n=i.replace(/'/g,"'\\''"),r=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function wi(t,i={}){let n=Dy(t);try{let{stdout:r,stderr:f}=await Ky(n,{cwd:i.cwd||Y$.cwd(),timeout:i.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${t}
|
|
120
|
+
Error: ${r.message}`);throw f.stack=r.stack,f}}function Z$(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function cc(t){let i=Yt.join(zy.homedir(),".stacks","ssl"),n=t.basePath&&t.basePath.trim()!==""?t.basePath:V.basePath&&V.basePath.trim()!==""?V.basePath:i,r=t.certPath?Yt.isAbsolute(t.certPath)?t.certPath:Yt.join(n,t.certPath):Yt.join(n,V.certPath),f=t.keyPath?Yt.isAbsolute(t.keyPath)?t.keyPath:Yt.join(n,t.keyPath):Yt.join(n,V.keyPath),e=t.caCertPath?Yt.isAbsolute(t.caCertPath)?t.caCertPath:Yt.join(n,t.caCertPath):Yt.join(n,V.caCertPath);return{certPath:r,keyPath:f,caCertPath:e,basePath:n}}function H$(t){let i=[],n=new Set;if(t.domain)n.add(t.domain);if(t.domains?.length)t.domains.forEach((r)=>n.add(r));for(let r of n)i.push({type:2,value:r});if(t.altNameIPs?.length)for(let r of t.altNameIPs)i.push({type:7,ip:r});if(t.altNameURIs?.length)for(let r of t.altNameURIs)i.push({type:6,value:r});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return C(F.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function lc(t){let i=t.notBeforeDays??Zt.DEFAULT_NOT_BEFORE_DAYS,n=t.validityDays??(t.validityYears?t.validityYears*365:Zt.DEFAULT_VALIDITY_DAYS);C(F.CERT,"Calculating certificate validity dates",t.verbose);let r=new Date(Date.now()-86400*i*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),C(F.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,t.verbose),{notBefore:r,notAfter:f}}var Ht={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},at={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 mn(t){if(t<128)return Buffer.from([t]);let i=[],n=t;while(n>0)i.unshift(n&255),n>>=8;return Buffer.from([128|i.length,...i])}function Rt(t,i){let n=mn(i.length);return Buffer.concat([Buffer.from([t]),n,i])}function Rn(t){let i=t.split(".").map(Number),n=[];n.push(40*i[0]+i[1]);for(let r=2;r<i.length;r++){let f=i[r],e=[];e.unshift(f&127),f>>=7;while(f>0)e.unshift(f&127|128),f>>=7;n.push(...e)}return Rt(Ht.OID,Buffer.from(n))}function be(t){let i;if(typeof t==="bigint"){let n=t.toString(16).padStart(2,"0");i=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let n=t.toString(16).padStart(2,"0");i=Buffer.from(n.length%2?`0${n}`:n,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return Rt(Ht.INTEGER,i)}function M$(t,i=0){return Rt(Ht.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function z$(t){return Rt(Ht.OCTET_STRING,t)}function St(...t){return Rt(Ht.SEQUENCE,Buffer.concat(t))}function Ly(...t){return Rt(Ht.SET,Buffer.concat(t))}function ky(t){return Rt(Ht.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function Vy(t){return Rt(Ht.UTF8_STRING,Buffer.from(t,"utf8"))}function oy(){return Buffer.from([Ht.NULL,0])}function kh(t,i,n=!0){let r=160|t|(n?0:0),f=mn(i.length);return Buffer.concat([Buffer.from([r]),f,i])}function Vh(t){let i=t.getUTCFullYear();if(i>=2050){let n=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Rt(Ht.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(i%100).toString().padStart(2,"0"),r=(t.getUTCMonth()+1).toString().padStart(2,"0"),f=t.getUTCDate().toString().padStart(2,"0"),e=t.getUTCHours().toString().padStart(2,"0"),c=t.getUTCMinutes().toString().padStart(2,"0"),h=t.getUTCSeconds().toString().padStart(2,"0"),l=`${n}${r}${f}${e}${c}${h}Z`;return Rt(Ht.UTC_TIME,Buffer.from(l,"ascii"))}}function gy(t,i){return St(Vh(t),Vh(i))}function oh(t){let i=[];for(let n of t){let r;switch(n.shortName){case"CN":r=at.COMMON_NAME;break;case"C":r=at.COUNTRY;break;case"L":r=at.LOCALITY;break;case"ST":r=at.STATE;break;case"O":r=at.ORGANIZATION;break;case"OU":r=at.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?ky(n.value):Vy(n.value),e=St(Rn(r),f);i.push(Ly(e))}return St(...i)}function G$(t){return St(Rn(t),oy())}function by(t){return t.export({type:"spki",format:"der"})}function Xy(t){if(t.includes(":")){let i=t;if(t.includes("::")){let f=t.split("::"),e=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],h=8-e.length-c.length,l=Array.from({length:h},()=>"0");i=[...e,...l,...c].join(":")}let n=i.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let e=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(e,f*2)}return r}else{let i=t.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(i)}}function Py(t){let i=[];for(let n of t)if(n.type===2&&n.value){let r=mn(n.value.length);i.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=Xy(n.ip),f=mn(r.length);i.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=mn(n.value.length);i.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return St(...i)}function vy(t,i){if(t){if(i!==void 0)return St(Rt(1,Buffer.from([255])),be(i));return St(Rt(1,Buffer.from([255])))}return St()}function py(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let n=0,r=i;while(r>0&&(r&1)===0)n++,r>>=1;if(i===0)n=7;return M$(Buffer.from([i]),n)}function Qy(t){let i=[];if(t.serverAuth)i.push(Rn(at.SERVER_AUTH));if(t.clientAuth)i.push(Rn(at.CLIENT_AUTH));return St(...i)}function an(t,i,n){let r=[Rn(t)];if(i)r.push(Rt(1,Buffer.from([255])));return r.push(z$(n)),St(...r)}function ta(t){let i=[];if(i.push(kh(0,be(2))),i.push(be(t.serialNumber)),i.push(G$(at.SHA256_WITH_RSA)),i.push(oh(t.issuer)),i.push(gy(t.notBefore,t.notAfter)),i.push(oh(t.subject)),i.push(by(t.publicKey)),t.extensions){let n=[];if(t.extensions.basicConstraints)n.push(an(at.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,vy(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)n.push(an(at.KEY_USAGE,t.extensions.keyUsage.critical??!0,py(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)n.push(an(at.EXTENDED_KEY_USAGE,!1,Qy(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)n.push(an(at.SUBJECT_ALT_NAME,!1,Py(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)n.push(an(at.SUBJECT_KEY_IDENTIFIER,!1,z$(t.extensions.subjectKeyIdentifier)));if(n.length>0)i.push(kh(3,St(...n)))}return St(...i)}function ia(t,i){let n=Pi.createSign("SHA256");n.update(t);let r=n.sign(i);return St(t,G$(at.SHA256_WITH_RSA),M$(r))}function na(t,i){let n=t.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${i}-----
|
|
121
121
|
${r.join(`
|
|
122
122
|
`)}
|
|
123
123
|
-----END ${i}-----
|
|
124
|
-
`}function
|
|
125
|
-
`);for(let e of f){let[c,...l]=e.split("="),h=l.join("=");if(c&&h)r.push({shortName:c.trim(),value:h.trim()})}return{publicKey:n,subject:r}}async function Xe(t={}){N("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Zt.DEFAULT_KEY_SIZE;N("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=Fs(i),f=[{shortName:"C",value:t.countryName||o.countryName},{shortName:"ST",value:t.stateName||o.stateName},{shortName:"L",value:t.localityName||o.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:e,notAfter:c}=ge({validityYears:t.validityYears||Zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:l}=Cs({serialNumber:be(),notBefore:e,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:l,privateKey:Js(n),notBefore:e,notAfter:c}}async function Pe(t){if(N("ca","Generating new certificate",t.verbose),N("ca",`Options: ${Xr(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Ka(t.rootCA.certificate),n=Ga(t.rootCA.privateKey);N("ca",`Generating ${Zt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let r=Zt.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:e}=Fs(r),c=t.commonName||Ts(t),l=t.certificateAttributes||[{shortName:"C",value:t.countryName||o.countryName},{shortName:"ST",value:t.stateName||o.stateName},{shortName:"L",value:t.localityName||o.localityName},{shortName:"O",value:t.organizationName||o.organizationName},{shortName:"CN",value:c}],{notBefore:h,notAfter:s}=ge({validityDays:t.validityDays||Zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),$=Ss(t),w=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},u=t.extKeyUsage||{serverAuth:!0},{certificate:y}=Cs({serialNumber:be(),notBefore:h,notAfter:s,subject:l,issuer:i,publicKey:e,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:w,extendedKeyUsage:u,subjectAltName:$});return{certificate:y,privateKey:Js(f),notBefore:h,notAfter:s}}function _s(t,i){N(F.STORAGE,`Storing certificate and private key with options: ${Xr(i)}`,i?.verbose);let{certPath:n,keyPath:r}=Ve({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});N(F.STORAGE,`Certificate path: ${n}`,i?.verbose),N(F.STORAGE,`Private key path: ${r}`,i?.verbose);let f=Me.dirname(n);if(!pt.existsSync(f))N(F.STORAGE,`Creating certificate directory: ${f}`,i?.verbose),pt.mkdirSync(f,{recursive:!0});N(F.STORAGE,"Writing certificate file",i?.verbose),pt.writeFileSync(n,t.certificate);let e=Me.dirname(r);if(!pt.existsSync(e))N(F.STORAGE,`Creating private key directory: ${e}`,i?.verbose),pt.mkdirSync(e,{recursive:!0});return N(F.STORAGE,"Writing private key file",i?.verbose),pt.writeFileSync(r,t.privateKey),N(F.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function Us(t,i){N(F.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=Ve({basePath:i?.basePath,caCertPath:i?.caCertPath});N(F.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=Me.dirname(n);if(!pt.existsSync(r))N(F.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),pt.mkdirSync(r,{recursive:!0});return N(F.STORAGE,"Writing CA certificate file",i?.verbose),pt.writeFileSync(n,t),N(F.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function qa(t,i){if(kr.platform()!=="darwin")return!1;try{let n=Il(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return N(F.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Il("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return N(F.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return N(F.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return N(F.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var Da={platform:"darwin",async addCertificate(t,i){if(await qa(t,i?.verbose)){N(F.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),ki.success("Certificate is already trusted in system keychain");return}N(F.TRUST,"Adding certificate to macOS keychain",i?.verbose),await li(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||o.commonName;N(F.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await li(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(F.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(f){throw N(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},xa={platform:"win32",async addCertificate(t,i){N(F.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await li(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||o.commonName;N(F.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await li(`certutil -delstore -enterprise Root "${r}"`),N(F.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(f){throw N(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},Oa={platform:"linux",async addCertificate(t,i){N(F.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=kr.homedir(),r=Zt.LINUX_CERT_DB_FILENAME,f=Zt.LINUX_TRUST_ARGS;N(F.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let e=Ze(n,r);if(e.length===0){ki.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of e){N(F.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{N(F.TRUST,`Attempting to delete existing cert for ${o.commonName}`,i?.verbose),await li(`certutil -d sql:${c} -D -n ${o.commonName}`)}catch(l){N(F.TRUST,`Warning: Error deleting existing cert: ${l}`,i?.verbose),console.warn(`Error deleting existing cert: ${l}`)}N(F.TRUST,`Adding new certificate to ${c}`,i?.verbose),await li(`certutil -d sql:${c} -A -t ${f} -n ${o.commonName} -i ${t}`),ki.info(`Cert added to ${c}`)}},async removeCertificate(t,i,n){let r=n||o.commonName;N(F.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let f=kr.homedir(),e=Zt.LINUX_CERT_DB_FILENAME;N(F.TRUST,`Searching for certificate databases in ${f}`,i?.verbose);let c=Ze(f,e);if(c.length===0){ki.warn("No certificate databases found. Cannot remove certificate.");return}for(let l of c){N(F.TRUST,`Processing certificate database in ${l}`,i?.verbose);try{await li(`certutil -d sql:${l} -D -n "${r}"`),ki.info(`Cert removed from ${l}`)}catch(h){N(F.TRUST,`Error removing cert from ${l}: ${h}`,i?.verbose),console.warn(`Error removing cert from ${l}: ${h}`)}}}},La={darwin:Da,win32:xa,linux:Oa};async function ve(t,i,n){N(F.TRUST,`Adding certificate to system trust store with options: ${Xr(n)}`,n?.verbose),N(F.TRUST,"Storing certificate and private key",n?.verbose);let r=_s(t,n);N(F.TRUST,"Storing CA certificate",n?.verbose);let f=Us(i,n),e=kr.platform();N(F.TRUST,`Detected platform: ${e}`,n?.verbose);let c=La[e];if(!c){let l=`Unsupported platform: ${e}`;throw N(F.TRUST,`Error: ${l}`,n?.verbose),Error(l)}return await c.addCertificate(f,n),N(F.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}var ai=null,oa="rpx-root-ca.crt",Va="rpx-root-ca.key";function ga(t){return{caCertPath:at(t,oa),caKeyPath:at(t,Va)}}async function ba(t,i){try{let[n,r]=await Promise.all([V.readFile(t.caCertPath,"utf8"),V.readFile(t.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:n,privateKey:r}}catch(n){return a("ssl",`No existing Root CA at ${t.caCertPath} (${n.code||n}), will create one`,i),null}}function js(t){let i=new Set;i.add(t);let n=t.split(".");if(n.length>=2)i.add(`*.${n.slice(1).join(".")}`);return Array.from(i)}function Zs(t){let n=tc(t).replace(/\*/g,"wildcard"),r=at(ic(),".stacks","ssl"),f=r;if(typeof t?.https==="object")return f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:r,{caCertPath:t.https.caCertPath||at(f,`${n}.ca.crt`),certPath:t.https.certPath||at(f,`${n}.crt`),keyPath:t.https.keyPath||at(f,`${n}.key`)};return{caCertPath:at(f,`${n}.ca.crt`),certPath:at(f,`${n}.crt`),keyPath:at(f,`${n}.key`)}}function ds(t){let i=new Set;if(Pr(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";js(r).forEach((f)=>i.add(f))});else if(Ys(t)){let n=t.to||"rpx.localhost";js(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function Xa(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Ii,...t};if(t.https=Ai(i),!t.https?.keyPath&&!t.https?.certPath)return a("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let n=!t.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${n}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",t.verbose);let n=await V.readFile(t.https?.keyPath,"utf8"),r=await V.readFile(t.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",t.verbose),{key:n,cert:r}}catch(n){return a("ssl",`Failed to read certificates: ${n}`,t.verbose),null}}catch(n){throw a("ssl",`SSL configuration error: ${n}`,t.verbose),n}}async function Pa(t){if(zt.platform==="darwin")return va(t);if(zt.platform==="linux")try{let{exec:i}=await import("node:child_process");return await new Promise((n)=>{i(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(r)=>{if(!r)n(!0);else i(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function va(t){if(zt.platform!=="darwin")return!1;try{if(await vr(t,{verbose:!1,regenerateUntrustedCerts:!0}))return a("ssl","Certificate is already trusted, skipping trust operation",!1),!0;a("ssl","Trusting certificate via macOS security command",!1);try{return Qe(`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${t}"`),!0}catch{return!1}}catch{return!1}}async function bi(t){if(ai){a("ssl","Using cached SSL configuration",t.verbose);return}let i=Pr(t)?t.proxies.map(($)=>$.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=Ai(t,t.verbose),r=n.basePath||at(ic(),".stacks","ssl");await V.mkdir(r,{recursive:!0});let f=ga(r),e=await ba(f,t.verbose),c=!1;if(!e){if(t.verbose)S.info("Generating Root CA certificate (one-time)...");e=await Xe(n);try{await Promise.all([V.writeFile(f.caCertPath,e.certificate),V.writeFile(f.caKeyPath,e.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,t.verbose)}catch($){throw a("ssl",`Error saving Root CA files: ${$}`,t.verbose),Error(`Failed to save Root CA files: ${$}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,t.verbose);if(t.verbose)S.info(`Generating host certificate for: ${i.join(", ")}`);let l=await Pe({...n,rootCA:{certificate:e.certificate,privateKey:e.privateKey}});try{await Promise.all([V.writeFile(n.certPath,l.certificate),V.writeFile(n.keyPath,l.privateKey),V.writeFile(n.caCertPath,e.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch($){throw a("ssl",`Error saving certificate files: ${$}`,t.verbose),Error(`Failed to save certificate files: ${$}`)}if(c?!1:await vr(f.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)S.success("Root CA is already trusted in system trust store");if(ai={key:l.privateKey,cert:l.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)S.info("Adding certificate to system trust store (may require sudo permission)...");let s=!1;if(zt.platform==="darwin")try{if(Qe(`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${f.caCertPath}"`),t.verbose)S.success("Successfully added Root CA to system trust store");s=!0;let $=at(r,"trust-rpx-cert.sh"),w=`#!/bin/bash
|
|
124
|
+
`}function hc(){return Pi.randomBytes(20)}function K$(t=2048){let{privateKey:i,publicKey:n}=Pi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:n}}function ra(t){let i=t.export({type:"spki",format:"der"});return Pi.createHash("sha1").update(i).digest()}function q$(t){let i={serialNumber:t.serialNumber||hc(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:ra(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let n=ta(i),r=ia(n,t.signingKey);return{certificate:na(r,"CERTIFICATE"),certificateDer:r}}function x$(t){return t.export({type:"pkcs8",format:"pem"})}function fa(t){return Pi.createPrivateKey(t)}function ea(t){let i=new Pi.X509Certificate(t),n=i.publicKey,r=[],f=i.subject.split(`
|
|
125
|
+
`);for(let e of f){let[c,...h]=e.split("="),l=h.join("=");if(c&&l)r.push({shortName:c.trim(),value:l.trim()})}return{publicKey:n,subject:r}}async function $c(t={}){C("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Zt.DEFAULT_KEY_SIZE;C("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=K$(i),f=[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:e,notAfter:c}=lc({validityYears:t.validityYears||Zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:h}=q$({serialNumber:hc(),notBefore:e,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:h,privateKey:x$(n),notBefore:e,notAfter:c}}async function wc(t){if(C("ca","Generating new certificate",t.verbose),C("ca",`Options: ${ef(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=ea(t.rootCA.certificate),n=fa(t.rootCA.privateKey);C("ca",`Generating ${Zt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let r=Zt.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:e}=K$(r),c=t.commonName||Z$(t),h=t.certificateAttributes||[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organizationName||V.organizationName},{shortName:"CN",value:c}],{notBefore:l,notAfter:$}=lc({validityDays:t.validityDays||Zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),w=H$(t),s=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:u}=q$({serialNumber:hc(),notBefore:l,notAfter:$,subject:h,issuer:i,publicKey:e,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:s,extendedKeyUsage:y,subjectAltName:w});return{certificate:u,privateKey:x$(f),notBefore:l,notAfter:$}}function O$(t,i){C(F.STORAGE,`Storing certificate and private key with options: ${ef(i)}`,i?.verbose);let{certPath:n,keyPath:r}=cc({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});C(F.STORAGE,`Certificate path: ${n}`,i?.verbose),C(F.STORAGE,`Private key path: ${r}`,i?.verbose);let f=Xe.dirname(n);if(!Qt.existsSync(f))C(F.STORAGE,`Creating certificate directory: ${f}`,i?.verbose),Qt.mkdirSync(f,{recursive:!0});C(F.STORAGE,"Writing certificate file",i?.verbose),Qt.writeFileSync(n,t.certificate);let e=Xe.dirname(r);if(!Qt.existsSync(e))C(F.STORAGE,`Creating private key directory: ${e}`,i?.verbose),Qt.mkdirSync(e,{recursive:!0});return C(F.STORAGE,"Writing private key file",i?.verbose),Qt.writeFileSync(r,t.privateKey),C(F.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function D$(t,i){C(F.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=cc({basePath:i?.basePath,caCertPath:i?.caCertPath});C(F.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=Xe.dirname(n);if(!Qt.existsSync(r))C(F.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),Qt.mkdirSync(r,{recursive:!0});return C(F.STORAGE,"Writing CA certificate file",i?.verbose),Qt.writeFileSync(n,t),C(F.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function ca(t,i){if(Qr.platform()!=="darwin")return!1;try{let n=gh(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return C(F.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(gh("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return C(F.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return C(F.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return C(F.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var la={platform:"darwin",async addCertificate(t,i){if(await ca(t,i?.verbose)){C(F.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),gi.success("Certificate is already trusted in system keychain");return}C(F.TRUST,"Adding certificate to macOS keychain",i?.verbose),await wi(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await wi(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),C(F.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(f){throw C(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},ha={platform:"win32",async addCertificate(t,i){C(F.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await wi(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await wi(`certutil -delstore -enterprise Root "${r}"`),C(F.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(f){throw C(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},$a={platform:"linux",async addCertificate(t,i){C(F.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=Qr.homedir(),r=Zt.LINUX_CERT_DB_FILENAME,f=Zt.LINUX_TRUST_ARGS;C(F.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let e=ge(n,r);if(e.length===0){gi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of e){C(F.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{C(F.TRUST,`Attempting to delete existing cert for ${V.commonName}`,i?.verbose),await wi(`certutil -d sql:${c} -D -n ${V.commonName}`)}catch(h){C(F.TRUST,`Warning: Error deleting existing cert: ${h}`,i?.verbose),console.warn(`Error deleting existing cert: ${h}`)}C(F.TRUST,`Adding new certificate to ${c}`,i?.verbose),await wi(`certutil -d sql:${c} -A -t ${f} -n ${V.commonName} -i ${t}`),gi.info(`Cert added to ${c}`)}},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let f=Qr.homedir(),e=Zt.LINUX_CERT_DB_FILENAME;C(F.TRUST,`Searching for certificate databases in ${f}`,i?.verbose);let c=ge(f,e);if(c.length===0){gi.warn("No certificate databases found. Cannot remove certificate.");return}for(let h of c){C(F.TRUST,`Processing certificate database in ${h}`,i?.verbose);try{await wi(`certutil -d sql:${h} -D -n "${r}"`),gi.info(`Cert removed from ${h}`)}catch(l){C(F.TRUST,`Error removing cert from ${h}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${h}: ${l}`)}}}},wa={darwin:la,win32:ha,linux:$a};async function uc(t,i,n){C(F.TRUST,`Adding certificate to system trust store with options: ${ef(n)}`,n?.verbose),C(F.TRUST,"Storing certificate and private key",n?.verbose);let r=O$(t,n);C(F.TRUST,"Storing CA certificate",n?.verbose);let f=D$(i,n),e=Qr.platform();C(F.TRUST,`Detected platform: ${e}`,n?.verbose);let c=wa[e];if(!c){let h=`Unsupported platform: ${e}`;throw C(F.TRUST,`Error: ${h}`,n?.verbose),Error(h)}return await c.addCertificate(f,n),C(F.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{execSync as Nn}from"node:child_process";import{homedir as ua}from"node:os";import{join as sa}from"node:path";import{execSync as cf}from"node:child_process";function sc(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Cn(t){try{let i=cf(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return sc(i)}catch{return null}}function L$(t){try{return cf(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function k$(t,i){try{let n=cf(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((r)=>n.includes(`DNS:${r}`))}catch{return!1}}function V$(t,i,n=443){try{return cf(`echo | openssl s_client -connect ${t}:${n} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function o$(t){let i=[];for(let n of t.split(`
|
|
126
|
+
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)i.push(r[1].toUpperCase())}return i}var ii="-d -r trustRoot -p ssl -p basic",si="/Library/Keychains/System.keychain",lf="rpx.localhost";function vi(){return sa(ua(),"Library/Keychains/login.keychain-db")}function hf(){return[si,vi()]}function yc(t,i=lf){let n=Nn(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
127
|
+
`)){let e=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(e)r.push(e[1].toUpperCase())}return r}function Jn(t){if(process.platform!=="darwin")return;let i=Cn(t.caPath);if(!i)return;let n=t.commonName??lf,r=t.keychains??hf();for(let f of r)for(let e of yc(f,n)){if(e===i)continue;try{if(f.startsWith("/Library"))Fn(`security delete-certificate -Z ${e} "${f}"`);else Nn(`security delete-certificate -Z ${e} "${f}"`,{stdio:"ignore"});a("ssl",`Removed stale Root CA ${e} from ${f}`,t.verbose)}catch{}}}function pi(t,i,n){if(process.platform!=="darwin")return Qi(t,n);try{let f=Nn(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return a("ssl",`verify-cert ${i}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function Qi(t,i){let n=Cn(t);if(!n)return!1;for(let r of hf())try{let f=Nn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let e of f.split(`
|
|
128
|
+
`))if(e.toUpperCase().includes("SHA-256")){if(e.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return a("ssl",`Root CA fingerprint found in ${r}`,i?.verbose),!0}}catch{}return!1}function $f(t,i){if(process.platform!=="darwin")return!1;let n=i.serverName;Jn({caPath:t,commonName:i.commonName,verbose:i.verbose});let r=vi();try{Nn(`security add-trusted-cert ${ii} -k "${r}" "${t}"`,{stdio:"ignore"})}catch{}try{Fn(`security add-trusted-cert ${ii} -k ${si} "${t}"`)}catch{return!1}return pi(t,n,{verbose:i.verbose})||Qi(t,{verbose:i.verbose})}var yi=null,aa="rpx-root-ca.crt",Aa="rpx-root-ca.key";function sf(t){return{caCertPath:Q(t,aa),caKeyPath:Q(t,Aa)}}function ma(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:sf(t)}}async function Ea(t,i){try{let[n,r]=await Promise.all([o.readFile(t.caCertPath,"utf8"),o.readFile(t.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:n,privateKey:r}}catch(n){return a("ssl",`No existing Root CA at ${t.caCertPath} (${n.code||n}), will create one`,i),null}}function g$(t){let i=new Set;i.add(t);let n=t.split(".");if(n.length>=2)i.add(`*.${n.slice(1).join(".")}`);return Array.from(i)}function p$(t){let n=Ac(t).replace(/\*/g,"wildcard"),r=Q(uf(),".stacks","ssl"),f=r;if(typeof t?.https==="object")return f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:r,{caCertPath:t.https.caCertPath||Q(f,`${n}.ca.crt`),certPath:t.https.certPath||Q(f,`${n}.crt`),keyPath:t.https.keyPath||Q(f,`${n}.key`)};return{caCertPath:Q(f,`${n}.ca.crt`),certPath:Q(f,`${n}.crt`),keyPath:Q(f,`${n}.key`)}}function b$(t){let i=new Set;if(wf(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";g$(r).forEach((f)=>i.add(f))});else if(P$(t)){let n=t.to||"rpx.localhost";g$(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function Ta(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Mi,...t};if(t.https=Ei(i),!t.https?.keyPath&&!t.https?.certPath)return a("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let n=!t.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${n}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",t.verbose);let n=await o.readFile(t.https?.keyPath,"utf8"),r=await o.readFile(t.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",t.verbose),{key:n,cert:r}}catch(n){return a("ssl",`Failed to read certificates: ${n}`,t.verbose),null}}catch(n){throw a("ssl",`SSL configuration error: ${n}`,t.verbose),n}}async function Sa(t,i){if(zt.platform==="darwin")return Ra(t,i);if(zt.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(e)=>{r(!e)})})})}catch{return!1}return!1}async function Ra(t,i){if(zt.platform!=="darwin")return!1;let n=i?.serverName??"rpx.localhost",r=i?.verbose??!1;try{if(pi(t,n,{verbose:r}))return a("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return a("ssl","Trusting Root CA for browsers (login + system keychains)",r),$f(t,{serverName:n,verbose:r})}catch{return!1}}async function nn(t){if(yi&&!t.forceRegenerate){a("ssl","Using cached SSL configuration",t.verbose);return}Q$();let i=wf(t)?t.proxies.map((w)=>w.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=Ei(t,t.verbose),r=n.basePath||Q(uf(),".stacks","ssl");await o.mkdir(r,{recursive:!0});let f=sf(r),e=await Ea(f,t.verbose),c=!1;if(!e){if(t.verbose)S.info("Generating Root CA certificate (one-time)...");e=await $c(n);try{await Promise.all([o.writeFile(f.caCertPath,e.certificate),o.writeFile(f.caKeyPath,e.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,t.verbose)}catch(w){throw a("ssl",`Error saving Root CA files: ${w}`,t.verbose),Error(`Failed to save Root CA files: ${w}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,t.verbose);if(t.verbose)S.info(`Generating host certificate for: ${i.join(", ")}`);let h=await wc({...n,rootCA:{certificate:e.certificate,privateKey:e.privateKey}});try{await Promise.all([o.writeFile(n.certPath,h.certificate),o.writeFile(n.keyPath,h.privateKey),o.writeFile(n.caCertPath,e.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch(w){throw a("ssl",`Error saving certificate files: ${w}`,t.verbose),Error(`Failed to save certificate files: ${w}`)}if(c?!1:await Ec(f.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)S.success("Root CA is already trusted in system trust store");if(yi={key:h.privateKey,cert:h.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)S.info("Adding certificate to system trust store (may require sudo permission)...");let $=!1;if(zt.platform==="darwin")try{Jn({caPath:f.caCertPath,verbose:t.verbose});let w=vi();try{tn(`security add-trusted-cert ${ii} -k "${w}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Fn(`security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"`),t.verbose)S.success("Successfully added Root CA to system trust store");$=!0;let s=Q(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
126
129
|
echo "Trusting RPX Root CA"
|
|
127
|
-
sudo security add-trusted-cert
|
|
130
|
+
sudo security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"
|
|
128
131
|
echo "Root CA trusted! Please restart your browser."
|
|
129
132
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
130
|
-
`;await
|
|
133
|
+
`;await o.writeFile(s,y,{mode:493})}catch(w){if(t.verbose)S.warn(`Could not add Root CA to trust store automatically: ${w}`);let s=Q(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
131
134
|
echo "Trusting RPX Root CA"
|
|
132
|
-
sudo security add-trusted-cert
|
|
135
|
+
sudo security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"
|
|
133
136
|
echo "Root CA trusted! Please restart your browser."
|
|
134
137
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
135
|
-
`;if(await
|
|
138
|
+
`;if(await o.writeFile(s,y,{mode:493}),t.verbose)S.info(`Created a trust helper script at: ${s}`),S.info(`If you're still having certificate issues, run: sh ${s}`)}else if(zt.platform==="linux")try{let{exec:w}=await import("node:child_process"),s="/usr/local/share/ca-certificates/rpx",y=`
|
|
136
139
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
137
140
|
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
138
141
|
update-ca-certificates
|
|
139
142
|
echo "RPX Root CA installed. Please restart your browser."
|
|
140
|
-
`,
|
|
143
|
+
`,u=Q(ac.tmpdir(),`rpx-trust-${Date.now()}.sh`);await o.writeFile(u,y,{mode:493}),await new Promise((m)=>{w(`sudo bash "${u}"`,(A)=>{if(A){if(t.verbose)S.warn(`Could not trust certificates: ${A}`);m(!1)}else{if(t.verbose)S.success("Successfully added certificates to system trust store");m(!0)}})}),await o.unlink(u).catch(()=>{}),$=!0}catch(w){if(t.verbose)S.warn(`Failed to trust certificates: ${w}`)}else if(zt.platform==="win32")try{let w=`
|
|
141
144
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
142
145
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
143
146
|
$store.Open("ReadWrite")
|
|
144
147
|
$store.Add($cert)
|
|
145
148
|
$store.Close()
|
|
146
149
|
Write-Host "Root CA trusted successfully!"
|
|
147
|
-
`,w=at(pe.tmpdir(),"rpx-trust.ps1");if(await V.writeFile(w,$),ui(`powershell -ExecutionPolicy Bypass -File "${w}"`),t.verbose)S.success("Successfully added certificate to Windows trust store");s=!0}catch($){if(t.verbose)S.warn(`Could not trust certificate: ${$}`)}else try{await ve(l,e.certificate,n),s=!0}catch($){if(t.verbose)S.warn(`Could not add certificate to trust store: ${$}`)}if(ai={key:l.privateKey,cert:l.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!s&&t.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}async function ti(t){if(!t)return null;if(ai)return ai;let i=Ai(t);try{let[n,r,f]=await Promise.all([V.access(i.keyPath).then(()=>!0).catch(()=>!1),V.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?V.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return a("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let e="regenerateUntrustedCerts"in t,c=t.regenerateUntrustedCerts,l=e?c!==!1:!0;if(a("ssl",`Trust check: hasFlag=${e}, flagValue=${c}, shouldCheckTrust=${l}`,t.verbose),!(l?await vr(i.certPath,t):!0))return a("ssl","Certificate exists but is not trusted, will regenerate",t.verbose),null;let[s,$,w]=await Promise.all([V.readFile(i.keyPath,"utf8"),V.readFile(i.certPath,"utf8"),f&&i.caCertPath?V.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(w&&!w.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(Pr(t))try{let{X509Certificate:u}=await import("node:crypto"),E=new u($).subjectAltName||"",T=t.proxies.map((m)=>m.to).filter((m)=>!E.includes(`DNS:${m}`));if(T.length>0)return a("ssl",`Certificate missing SANs for: ${T.join(", ")}, will regenerate`,t.verbose),null}catch(u){a("ssl",`Could not verify cert SANs: ${u}`,t.verbose)}return a("ssl","Successfully loaded existing certificates",t.verbose),ai={key:s,cert:$,ca:w},ai}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function Ai(t,i){let n=tc(t);a("ssl",`Primary domain: ${n}`,i);let r=Zs(t),f=at(ic(),".stacks","ssl");if(typeof t.https==="object"){let e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:f,c={domain:n,hostCertCN:n,basePath:e,caCertPath:t.https.caCertPath||r.caCertPath,certPath:t.https.certPath||r.certPath,keyPath:t.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||n,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(ds(t)).map((l)=>({type:2,value:l}))};if(Ws(t.https.rootCA))c.rootCA=t.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(ds(t)).map((e)=>({type:2,value:e}))}}async function nc(t,i){let n=Zs({to:t,verbose:i}),r=[n.caCertPath,n.certPath,n.keyPath];a("certificates","Attempting to clean up relating certificates",i),await Promise.all(r.map((f)=>Is(f,i)))}async function vr(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),zt.platform==="darwin")try{let r=ui(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return a("ssl","Could not extract certificate fingerprint",i?.verbose),!1;if(ui("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256").toString().includes(r))return a("ssl","Certificate fingerprint found in system keychain",i?.verbose),!0;return a("ssl","Certificate fingerprint not found in system keychain",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust: ${n}`,i?.verbose),!1}else if(zt.platform==="win32")try{let r=ui(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!r)return a("ssl","Could not extract certificate subject",i?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(ui(f).toString().includes(r))return a("ssl","Certificate found in trusted root store",i?.verbose),!0;return a("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Windows: ${n}`,i?.verbose),!1}else if(zt.platform==="linux")try{let r=ui(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let e of f)try{if(ui(`find ${e} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${r}"`).toString().includes(r))return a("ssl",`Certificate fingerprint found in ${e}`,i?.verbose),!0}catch{}return a("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Linux: ${n}`,i?.verbose),!1}return a("ssl",`Platform ${zt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(n){return a("ssl",`Error checking if certificate is trusted: ${n}`,i?.verbose),!1}}function En(t,i){return async(n)=>{let r=new URL(n.url),e=(n.headers.get("host")||"").split(":")[0],c=t(e);if(!c)return a("request",`No route found for host: ${e}`,i),new Response(`No proxy configured for ${e}`,{status:404});let l=c.sourceHost,h=r.pathname,s=Hs(r.pathname,c.pathRewrites);if(s)l=s.targetHost,h=s.targetPath,a("request",`Path rewrite: ${r.pathname} → ${l}${h}`,i);let $=`http://${l}${h}${r.search}`;try{let w=new Headers(n.headers);if(w.set("host",l),c.changeOrigin)w.set("origin",`http://${c.sourceHost}`);w.set("x-forwarded-for","127.0.0.1"),w.set("x-forwarded-proto","https"),w.set("x-forwarded-host",e);let u=await fetch($,{method:n.method,headers:w,body:n.body,redirect:"manual"});if(c.cleanUrls&&r.pathname.endsWith(".html")){let E=r.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:E}})}let y=new Headers(u.headers);return new Response(u.body,{status:u.status,statusText:u.statusText,headers:y})}catch(w){return a("request",`Proxy error for ${e}: ${w}`,i),new Response(`Proxy Error: ${w}`,{status:502})}}}import*as pr from"node:fs";import*as At from"node:fs/promises";import{homedir as pa}from"node:os";import*as rc from"node:path";import*as Qr from"node:process";var Qa=/^[a-zA-Z0-9._-]+$/;function ii(){return rc.join(pa(),".stacks","rpx","registry.d")}function Pi(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Qa.test(t)}function fc(t,i){if(!Pi(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return rc.join(t,`${i}.json`)}function ni(t){if(!Number.isInteger(t)||t<=0)return!1;try{return Qr.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Ms(t){if(!t||typeof t!=="object")return!1;let i=t,n=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&Pi(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&n&&typeof i.createdAt==="string"}async function t0(t){await At.mkdir(t,{recursive:!0})}async function ec(t,i=ii(),n){if(!Ms(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await t0(i);let r=fc(i,t.id),f=`${r}.tmp.${Qr.pid}.${Date.now()}`,e=JSON.stringify(t,null,2);try{await At.writeFile(f,e,{encoding:"utf8",mode:420}),await At.rename(f,r),a("registry",`wrote entry ${t.id} → ${r}`,n)}catch(c){throw await At.unlink(f).catch(()=>{}),c}}async function tf(t,i=ii(),n){let r=fc(i,t);try{await At.unlink(r),a("registry",`removed entry ${t}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function zs(t,i=ii(),n){let r=fc(i,t);try{let f=await At.readFile(r,"utf8"),e=JSON.parse(f);if(!Ms(e))return a("registry",`entry ${t} failed validation, removing`,n),await At.unlink(r).catch(()=>{}),null;return e}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return a("registry",`entry ${t} has invalid JSON, removing`,n),await At.unlink(r).catch(()=>{}),null;throw f}}async function Xi(t=ii(),i){let n;try{n=await At.readdir(t)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let e=f.slice(0,-5);if(!Pi(e))continue;let c=await zs(e,t,i);if(c)r.push(c)}return r}async function nf(t=ii(),i){let n=await Xi(t,i),r=0;for(let f of n){if(f.pid===void 0)continue;if(!ni(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,i),await tf(f.id,t,i).catch(()=>{}),r++}return r}function cc(t,i={}){let n=i.dir??ii(),r=i.debounceMs??100,f=i.pollMs??Math.max(r*2,250),e=i.verbose;pr.mkdirSync(n,{recursive:!0});let c=null,l=!1,h=null,s=!1,$=(T)=>{return JSON.stringify(T.map((m)=>({id:m.id,from:m.from,to:m.to,pid:m.pid,pathRewrites:m.pathRewrites,cleanUrls:m.cleanUrls,changeOrigin:m.changeOrigin})).sort((m,R)=>m.id.localeCompare(R.id)))},w=()=>{if(c=null,l)return;Xi(n,e).then((T)=>{return h=$(T),t(T)}).catch((T)=>{a("registry",`watcher onChange failed: ${T}`,e)})},u=()=>{if(l)return;if(c)clearTimeout(c);c=setTimeout(w,r)},E=setInterval(()=>{if(l||s)return;s=!0,Xi(n,e).then((T)=>{if($(T)!==h)u()}).catch((T)=>{a("registry",`watcher poll failed: ${T}`,e)}).finally(()=>{s=!1})},f),A=pr.watch(n,{persistent:!0},(T,m)=>{if(m&&/\.tmp\.\d+\.\d+$/.test(m))return;u()});return A.on("error",(T)=>{a("registry",`watcher error: ${T}`,e)}),u(),{close:()=>{if(l=!0,c)clearTimeout(c);clearInterval(E),A.close()}}}var r0=5000;function ri(){return Qi.join(n0(),".stacks","rpx")}function rf(t=ri()){return Qi.join(t,"daemon.pid")}async function pi(t=ri()){try{let i=await Gt.readFile(rf(t),"utf8"),n=Number.parseInt(i.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function f0(t=ri()){let i=await pi(t);return i!==null&&ni(i)}async function Gs(t=ri()){await Gt.mkdir(t,{recursive:!0});let i=rf(t);while(!0){try{let r=await Gt.open(i,"wx");try{await r.write(`${it.pid}
|
|
148
|
-
`)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await
|
|
150
|
+
`,s=Q(ac.tmpdir(),"rpx-trust.ps1");if(await o.writeFile(s,w),tn(`powershell -ExecutionPolicy Bypass -File "${s}"`),t.verbose)S.success("Successfully added certificate to Windows trust store");$=!0}catch(w){if(t.verbose)S.warn(`Could not trust certificate: ${w}`)}else try{await uc(h,e.certificate,n),$=!0}catch(w){if(t.verbose)S.warn(`Could not add certificate to trust store: ${w}`)}if(yi={key:h.privateKey,cert:h.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!$&&t.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}function Q$(){yi=null}async function ni(t){if(!t)return null;if(yi)return yi;let i=Ei(t);try{let[n,r,f]=await Promise.all([o.access(i.keyPath).then(()=>!0).catch(()=>!1),o.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?o.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return a("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let e="regenerateUntrustedCerts"in t,c=t.regenerateUntrustedCerts,h=e?c!==!1:!0;a("ssl",`Trust check: hasFlag=${e}, flagValue=${c}, shouldCheckTrust=${h}`,t.verbose);let l=i.basePath||Q(uf(),".stacks","ssl"),$=sf(l);if(!(h?await Ec($.caCertPath,t):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[s,y,u]=await Promise.all([o.readFile(i.keyPath,"utf8"),o.readFile(i.certPath,"utf8"),f&&i.caCertPath?o.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(u&&!u.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(wf(t))try{let{X509Certificate:m}=await import("node:crypto"),T=new m(y).subjectAltName||"",R=t.proxies.map((N)=>N.to).filter((N)=>!T.includes(`DNS:${N}`));if(R.length>0)return a("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,t.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return a("ssl","Successfully loaded existing certificates",t.verbose),yi={key:s,cert:y,ca:u},yi}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function Ei(t,i){let n=Ac(t);a("ssl",`Primary domain: ${n}`,i);let r=p$(t),f=Q(uf(),".stacks","ssl");if(typeof t.https==="object"){let e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:f,c={domain:n,hostCertCN:n,basePath:e,caCertPath:t.https.caCertPath||r.caCertPath,certPath:t.https.certPath||r.certPath,keyPath:t.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||n,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(b$(t)).map((h)=>({type:2,value:h}))};if(X$(t.https.rootCA))c.rootCA=t.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(b$(t)).map((e)=>({type:2,value:e}))}}async function mc(t,i){let n=p$({to:t,verbose:i}),r=[n.caCertPath,n.certPath,n.keyPath];a("certificates","Attempting to clean up relating certificates",i),await Promise.all(r.map((f)=>v$(f,i)))}async function Ec(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),zt.platform==="darwin"){if(i?.serverName)return pi(t,i.serverName,{verbose:i.verbose});return Qi(t,{verbose:i.verbose})}else if(zt.platform==="win32")try{let r=tn(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!r)return a("ssl","Could not extract certificate subject",i?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(tn(f).toString().includes(r))return a("ssl","Certificate found in trusted root store",i?.verbose),!0;return a("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Windows: ${n}`,i?.verbose),!1}else if(zt.platform==="linux")try{let r=tn(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let e of f)try{if(tn(`find ${e} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${r}"`).toString().includes(r))return a("ssl",`Certificate fingerprint found in ${e}`,i?.verbose),!0}catch{}return a("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Linux: ${n}`,i?.verbose),!1}return a("ssl",`Platform ${zt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(n){return a("ssl",`Error checking if certificate is trusted: ${n}`,i?.verbose),!1}}function _n(t,i){return async(n)=>{let r=new URL(n.url),e=(n.headers.get("host")||"").split(":")[0],c=t(e);if(!c)return a("request",`No route found for host: ${e}`,i),new Response(`No proxy configured for ${e}`,{status:404});let h=c.sourceHost,l=r.pathname,$=tw(r.pathname,c.pathRewrites);if($)h=$.targetHost,l=$.targetPath,a("request",`Path rewrite: ${r.pathname} → ${h}${l}`,i);let w=`http://${h}${l}${r.search}`;try{let s=new Headers(n.headers);if(s.set("host",h),c.changeOrigin)s.set("origin",`http://${c.sourceHost}`);s.set("x-forwarded-for","127.0.0.1"),s.set("x-forwarded-proto","https"),s.set("x-forwarded-host",e);let y=await fetch(w,{method:n.method,headers:s,body:n.body,redirect:"manual"});if(c.cleanUrls&&r.pathname.endsWith(".html")){let m=r.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let u=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:u})}catch(s){return a("request",`Proxy error for ${e}: ${s}`,i),new Response(`Proxy Error: ${s}`,{status:502})}}}import*as yf from"node:fs";import*as At from"node:fs/promises";import{homedir as Ba}from"node:os";import*as Tc from"node:path";import*as af from"node:process";var Ca=/^[a-zA-Z0-9._-]+$/;function ri(){return Tc.join(Ba(),".stacks","rpx","registry.d")}function rn(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Ca.test(t)}function Sc(t,i){if(!rn(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return Tc.join(t,`${i}.json`)}function fi(t){if(!Number.isInteger(t)||t<=0)return!1;try{return af.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function iw(t){if(!t||typeof t!=="object")return!1;let i=t,n=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&rn(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&n&&typeof i.createdAt==="string"}async function Fa(t){await At.mkdir(t,{recursive:!0})}async function Rc(t,i=ri(),n){if(!iw(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await Fa(i);let r=Sc(i,t.id),f=`${r}.tmp.${af.pid}.${Date.now()}`,e=JSON.stringify(t,null,2);try{await At.writeFile(f,e,{encoding:"utf8",mode:420}),await At.rename(f,r),a("registry",`wrote entry ${t.id} → ${r}`,n)}catch(c){throw await At.unlink(f).catch(()=>{}),c}}async function Af(t,i=ri(),n){let r=Sc(i,t);try{await At.unlink(r),a("registry",`removed entry ${t}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function nw(t,i=ri(),n){let r=Sc(i,t);try{let f=await At.readFile(r,"utf8"),e=JSON.parse(f);if(!iw(e))return a("registry",`entry ${t} failed validation, removing`,n),await At.unlink(r).catch(()=>{}),null;return e}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return a("registry",`entry ${t} has invalid JSON, removing`,n),await At.unlink(r).catch(()=>{}),null;throw f}}async function Ti(t=ri(),i){let n;try{n=await At.readdir(t)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let e=f.slice(0,-5);if(!rn(e))continue;let c=await nw(e,t,i);if(c)r.push(c)}return r}async function mf(t=ri(),i){let n=await Ti(t,i),r=0;for(let f of n){if(f.pid===void 0)continue;if(!fi(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,i),await Af(f.id,t,i).catch(()=>{}),r++}return r}function Bc(t,i={}){let n=i.dir??ri(),r=i.debounceMs??100,f=i.pollMs??Math.max(r*2,250),e=i.verbose;yf.mkdirSync(n,{recursive:!0});let c=null,h=!1,l=null,$=!1,w=(T)=>{return JSON.stringify(T.map((E)=>({id:E.id,from:E.from,to:E.to,pid:E.pid,pathRewrites:E.pathRewrites,cleanUrls:E.cleanUrls,changeOrigin:E.changeOrigin})).sort((E,R)=>E.id.localeCompare(R.id)))},s=()=>{if(c=null,h)return;Ti(n,e).then((T)=>{return l=w(T),t(T)}).catch((T)=>{a("registry",`watcher onChange failed: ${T}`,e)})},y=()=>{if(h)return;if(c)clearTimeout(c);c=setTimeout(s,r)},m=setInterval(()=>{if(h||$)return;$=!0,Ti(n,e).then((T)=>{if(w(T)!==l)y()}).catch((T)=>{a("registry",`watcher poll failed: ${T}`,e)}).finally(()=>{$=!1})},f),A=yf.watch(n,{persistent:!0},(T,E)=>{if(E&&/\.tmp\.\d+\.\d+$/.test(E))return;y()});return A.on("error",(T)=>{a("registry",`watcher error: ${T}`,e)}),y(),{close:()=>{if(h=!0,c)clearTimeout(c);clearInterval(m),A.close()}}}var Ja=5000;function ei(){return Gt.join(rw(),".stacks","rpx")}function Ef(t=ei()){return Gt.join(t,"daemon.pid")}async function en(t=ei()){try{let i=await Kt.readFile(Ef(t),"utf8"),n=Number.parseInt(i.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _a(t=ei()){let i=await en(t);return i!==null&&fi(i)}async function fw(t=ei()){await Kt.mkdir(t,{recursive:!0});let i=Ef(t);while(!0){try{let r=await Kt.open(i,"wx");try{await r.write(`${nt.pid}
|
|
151
|
+
`)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await en(t);if(n!==null&&fi(n))throw Error(`rpx daemon already running (pid=${n})`);await Kt.unlink(i).catch(()=>{})}}async function fn(t=ei()){await Kt.unlink(Ef(t)).catch(()=>{})}function Ua(t){return{sourceHost:new URL(t.from.startsWith("http")?t.from:`http://${t.from}`).host,cleanUrls:t.cleanUrls??!1,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function da(t){return t.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??t[0]??"rpx.localhost"}async function ja(t,i){let n=await Ti(i,t.verbose),r=[...new Set(n.map((w)=>w.to))],f=da(r),e=[...new Set([f,...r,"rpx.localhost"])],c=Gt.join(rw(),".stacks","ssl"),h=Gt.join(c,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:h,keyPath:Gt.join(c,"rpx.localhost.key"),commonName:f}:{certPath:h,keyPath:Gt.join(c,"rpx.localhost.key"),caCertPath:Gt.join(c,"rpx.localhost.ca.crt"),commonName:f},verbose:t.verbose,regenerateUntrustedCerts:!0,...e.length>1?{proxies:e.map((w)=>({from:"localhost:1",to:w}))}:{to:f,from:"localhost:1"}},$=await ni(l);if(!$)a("daemon","no usable cert on disk, generating one",t.verbose),await nn(l),$=await ni(l);if(!$)throw Error("failed to bootstrap TLS for rpx daemon");return $}async function Wa(t={}){let i=t.verbose??!1,n=t.rpxDir??ei(),r=t.registryDir??Gt.join(n,"registry.d"),f=t.httpsPort??443,e=t.httpPort??80,c=t.hostname??"0.0.0.0",h=t.gcIntervalMs??Ja,l=await fw(n),$=new Map,w=(B)=>$.get(B);function s(B){let $t=new Map;for(let mt of B)$t.set(mt.to,Ua(mt));$=$t,a("daemon",`routing table now covers ${$t.size} host(s): ${Array.from($t.keys()).join(", ")||"<empty>"}`,i)}await mf(r,i).catch((B)=>{a("daemon",`initial gc failed: ${B}`,i)}),s(await Ti(r,i));let y=await ja(t,r),u=Bun.serve({port:f,hostname:c,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_n(w,i),error(B){return a("daemon",`https server error: ${B}`,i),new Response(`Server Error: ${B.message}`,{status:500})}}),m=null;if(e>0)m=Bun.serve({port:e,hostname:c,fetch(B){let $t=new URL(B.url),mt=(B.headers.get("host")??$t.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${mt}${$t.pathname}${$t.search}`}})}});if(i)S.success(`rpx daemon listening on https://${c}:${f}${m?` (http→https on :${e})`:""}`),S.info(`pid file: ${l}`),S.info(`registry: ${r}`);let A=Bc((B)=>{s(B)},{dir:r,verbose:i}),T=setInterval(()=>{mf(r,i).then((B)=>{if(B>0)a("daemon",`gc reaped ${B} stale entries`,i)}).catch((B)=>{a("daemon",`periodic gc failed: ${B}`,i)})},h);if(typeof T.unref==="function")T.unref();let E=!1,R,N=new Promise((B)=>{R=B});async function J(){if(E)return N;if(E=!0,clearInterval(T),A.close(),u.stop(!1),m?.stop(!1),await fn(n),i)S.info("rpx daemon stopped");return R(),N}let d=(B)=>{a("daemon",`received ${B}, shutting down`,i),J().catch(()=>{})};return nt.once("SIGINT",d),nt.once("SIGTERM",d),{stop:J,done:N,httpsPort:typeof u.port==="number"?u.port:f,httpPort:m&&typeof m.port==="number"?m.port:e,pidPath:l}}function ew(){let t=nt.execPath,i=Gt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&nt.argv[1])return[t,nt.argv[1],"daemon:start"];return[t,"daemon:start"]}async function Cc(t={}){let i=t.rpxDir??ei(),n=t.verbose??!1,r=await en(i);if(r!==null&&fi(r))return a("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)a("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await fn(i);await Kt.mkdir(i,{recursive:!0});let f=t.spawnCommand??ew();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,n);let e=Na(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??nt.cwd(),env:t.spawnEnv?{...nt.env,...t.spawnEnv}:nt.env});e.unref();let c=null;e.once("error",(w)=>{c=w});let h=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,$=Date.now()+h;while(Date.now()<$){if(c)throw c;let w=await en(i);if(w!==null&&fi(w))return a("daemon",`daemon registered with pid=${w}`,n),{pid:w,spawned:!0};await new Promise((s)=>setTimeout(s,l))}if(c)throw c;throw Error(`rpx daemon failed to start within ${h}ms (rpxDir=${i})`)}async function Ya(t={}){let i=t.rpxDir??ei(),n=t.verbose??!1,r=t.timeoutMs??5000,f=t.pollIntervalMs??50,e=t.forceAfterTimeout??!0,c=await en(i);if(c===null||!fi(c)){if(c!==null)await fn(i);return{stopped:!1,pid:c,forced:!1}}try{nt.kill(c,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await fn(i),{stopped:!1,pid:c,forced:!1};throw l}let h=Date.now()+r;while(Date.now()<h){if(!fi(c))return a("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((l)=>setTimeout(l,f))}if(!e)throw Error(`rpx daemon (pid=${c}) did not exit within ${r}ms`);a("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,n);try{nt.kill(c,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await fn(i),{stopped:!0,pid:c,forced:!0}}function hw(t){let i=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function Tf(t){if(t.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let i=t.verbose??!1,n=t.registryDir,r=new Set,f=t.proxies.map((y)=>{let u=y.id??hw(y.to);if(!rn(u))throw Error(`invalid registry id "${u}" derived from to="${y.to}"`);if(r.has(u))throw Error(`duplicate registry id "${u}" — set an explicit \`id\` on one of the proxies`);return r.add(u),{...y,id:u}}),e=new Date().toISOString();for(let y of f)await Rc({id:y.id,from:y.from,to:y.to,pid:t.persistent?void 0:qt.pid,cwd:qt.cwd(),createdAt:e,cleanUrls:y.cleanUrls,changeOrigin:y.changeOrigin,pathRewrites:y.pathRewrites},n,i);let c=await Cc({rpxDir:t.rpxDir,verbose:i,spawnCommand:t.spawnCommand,startupTimeoutMs:t.startupTimeoutMs,spawnEnv:t.spawnEnv});for(let y of f)S.success(`https://${y.to} → ${y.from}`);if(S.info(`(via rpx daemon pid=${c.pid}; \`rpx daemon:status\` to inspect)`),t.detached)return;let h=!1,l=n??ri(),$=f.map((y)=>y.id),w=async()=>{if(h)return;h=!0;for(let y of $)await Af(y,n,i).catch((u)=>{a("runner",`removeEntry(${y}) failed: ${u}`,i)})},s=(y)=>{a("runner",`received ${y}, unregistering ${$.length} entries`,i),w().finally(()=>qt.exit(0))};qt.once("SIGINT",s),qt.once("SIGTERM",s),qt.once("exit",()=>{if(h)return;for(let y of $)try{cw.unlinkSync(lw.join(l,`${y}.json`))}catch{}}),await new Promise(()=>{})}import{exec as Ia}from"node:child_process";import Si from"node:fs";import $w from"node:os";import Nc from"node:path";import*as dn from"node:process";import{promisify as Za}from"node:util";var Sf=Za(Ia),Ut=dn.platform==="win32"?Nc.join(dn.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Fc=!1;async function Rf(t){if(dn.platform==="win32")throw Error("Administrator privileges required on Windows");let i=Un(),n=t.replace(/'/g,"'\\''");try{if(i){let{stdout:f}=await Sf(`echo '${i}' | sudo -S sh -c '${n}' 2>/dev/null`);return Fc=!0,f}if(Fc)try{let{stdout:f}=await Sf(`sudo -n sh -c '${n}'`);return f}catch(f){a("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:r}=await Sf(`sudo sh -c '${n}'`);return Fc=!0,r}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}async function cn(t,i){a("hosts",`Adding hosts: ${t.join(", ")}`,i),a("hosts",`Using hosts file at: ${Ut}`,i);try{let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await Rf(`cat "${Ut}"`)}catch(c){throw console.log(" Could not read hosts file — skipping hosts setup"),a("hosts",`sudo read also failed: ${c}`,i),Error(`Cannot read hosts file: ${c}`)}}let r=t.filter((c)=>{let h=`127.0.0.1 ${c}`,l=`::1 ${c}`;return!n.includes(h)&&!n.includes(l)});if(r.length===0){a("hosts","All hosts already exist in hosts file",i);return}let f=r.map((c)=>`
|
|
149
152
|
# Added by rpx
|
|
150
153
|
127.0.0.1 ${c}
|
|
151
154
|
::1 ${c}`).join(`
|
|
152
|
-
`),e=
|
|
153
|
-
`),f=!1,e=r.filter((
|
|
155
|
+
`),e=Nc.join($w.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Si.promises.writeFile(e,n+f,"utf8"),await Rf(`cat "${e}" | tee "${Ut}" > /dev/null`),console.log(` Hosts updated: ${r.join(", ")}`)}catch(c){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),r.forEach((h)=>{console.log(` 127.0.0.1 ${h}`),console.log(` ::1 ${h}`)}),console.log(` Or run: sudo nano ${Ut}`)}finally{try{await Si.promises.unlink(e)}catch{}}}catch(n){a("hosts",`Failed to manage hosts file: ${n.message}`,i)}}async function Jc(t,i){a("hosts",`Removing hosts: ${t.join(", ")}`,i);try{let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await Rf(`cat "${Ut}"`)}catch(l){throw a("hosts",`sudo read also failed: ${l}`,i),Error(`Cannot read hosts file: ${l}`)}}let r=n.split(`
|
|
156
|
+
`),f=!1,e=r.filter((l)=>{if(t.some((w)=>l.includes(` ${w}`)&&(l.includes("127.0.0.1")||l.includes("::1"))))return f=!0,!1;if(l.trim()==="# Added by rpx")return f=!0,!1;return!0});if(!f){a("hosts","No matching hosts found to remove",i);return}while(e[e.length-1]?.trim()==="")e.pop();let c=`${e.join(`
|
|
154
157
|
`)}
|
|
155
|
-
`,l=sc.join(Os.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await mi.promises.writeFile(l,c,"utf8"),await cf(`cat "${l}" | tee "${Ut}" > /dev/null`),a("hosts","Hosts removed successfully",i)}catch(h){a("hosts","Could not clean up hosts file automatically",i)}finally{try{await mi.promises.unlink(l)}catch(h){a("hosts",`Failed to remove temporary file: ${h}`,i)}}}catch(n){a("hosts",`Failed to clean up hosts file: ${n.message}`,i)}}async function nn(t,i){a("hosts",`Checking hosts: ${t}`,i);let n;try{n=await mi.promises.readFile(Ut,"utf-8")}catch(r){a("hosts",`Error reading hosts file: ${r}`,i);try{let f=Tn(),e;if(f)e=`echo '${f}' | sudo -S cat "${Ut}" 2>/dev/null`;else e=`sudo -n cat "${Ut}" 2>/dev/null || cat "${Ut}" 2>/dev/null || echo ""`;let{stdout:c}=await ef(e);n=c}catch(f){return a("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,i),t.map(()=>!1)}}return t.map((r)=>{let f=`127.0.0.1 ${r}`,e=`::1 ${r}`;return n.includes(f)||n.includes(e)})}import*as hf from"node:net";function $i(t,i,n){return a("port",`Checking if port ${t} is in use on ${i}`,n),new Promise((r)=>{let f=hf.createServer(),e=setTimeout(()=>{a("port",`Checking port ${t} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout(e),c.code==="EADDRINUSE")a("port",`Port ${t} is in use`,n),r(!0);else a("port",`Error checking port ${t}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(e),a("port",`Port ${t} is available`,n),f.close(),r(!1)});try{f.listen(t,i)}catch(c){clearTimeout(e),a("port",`Exception checking port ${t}: ${c}`,n),r(!0)}})}async function ks(t,i,n,r=50){a("port",`Finding available port starting from ${t} (max attempts: ${r})`,n);let f=t,e=0;while(e<r){if(e++,!await $i(f,i,n))return a("port",`Found available port: ${f} after ${e} attempts`,n),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${e}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${t}`)}function Ls(t,i,n=5000,r){return a("port",`Testing connection to ${i}:${t}`,r),new Promise((f)=>{let e=hf.connect({host:i,port:t,timeout:n});e.once("connect",()=>{a("port",`Successfully connected to ${i}:${t}`,r),e.end(),f(!0)}),e.once("timeout",()=>{a("port",`Connection to ${i}:${t} timed out`,r),e.destroy(),f(!1)}),e.once("error",(c)=>{a("port",`Failed to connect to ${i}:${t}: ${c.message}`,r),e.destroy(),f(!1)})})}class Rn{usedPorts=new Set;hostname;verbose;maxRetries;constructor(t="0.0.0.0",i,n=50){this.hostname=t,this.verbose=i,this.maxRetries=n}async getNextAvailablePort(t,i=!1){if(this.usedPorts.has(t))return this.findNextAvailablePort(t+1,i);if(await $i(t,this.hostname,this.verbose))return this.findNextAvailablePort(t+1,i);if(i){if(!await Ls(t,this.hostname,3000,this.verbose))return a("port",`Port ${t} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(t+1,i)}return this.usedPorts.add(t),t}async findNextAvailablePort(t,i=!1){let n=await ks(t,this.hostname,this.verbose,this.maxRetries);if(i){if(!await Ls(n,this.hostname,3000,this.verbose))if(n<t+this.maxRetries)return this.findNextAvailablePort(n+1,i);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(t){a("port",`Releasing port ${t}`,this.verbose),this.usedPorts.delete(t)}}var w0=new Rn;import{spawn as y0}from"node:child_process";import*as Ei from"node:process";class lf{processes=new Map;isShuttingDown=!1;async startProcess(t,i,n){if(this.processes.has(t)){a("start",`Process ${t} is already running`,n);return}let[r,...f]=i.command.split(" "),e=i.cwd||Ei.cwd();a("start",`Starting process ${t}:`,n),a("start",` Command: ${r} ${f.join(" ")}`,n),a("start",` Working directory: ${e}`,n),a("start",` Environment variables: ${fi(i.env)}`,n);let c=y0(r,f,{cwd:e,env:{...Ei.env,...i.env},shell:!0,stdio:"inherit"});return this.processes.set(t,{command:i.command,cwd:e,process:c,env:i.env}),new Promise((l,h)=>{if(c.on("error",(s)=>{if(!this.isShuttingDown)a("start",`Process ${t} failed to start: ${s}`,n),this.processes.delete(t),h(s),Ei.emit("SIGINT")}),c.on("exit",(s)=>{if(!this.isShuttingDown&&s!==null&&s!==0)a("start",`Process ${t} exited with code ${s}`,n),this.processes.delete(t),h(Error(`Process ${t} exited with code ${s}`)),Ei.emit("SIGINT")}),n)c.stdout?.on("data",(s)=>{a("process",`[${t}] ${s.toString().trim()}`,!0)}),c.stderr?.on("data",(s)=>{a("process",`[${t}] ERR: ${s.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&c.killed)this.processes.delete(t),h(Error(`Process ${t} was killed during startup`));else a("start",`Process ${t} started successfully`,n),l()},1000)})}async stopProcess(t,i){let n=this.processes.get(t);if(!n?.process){a("start",`No process found for ${t}`,i);return}return a("start",`Stopping process ${t}`,i),new Promise((r)=>{if(!n.process){r();return}n.process.once("exit",()=>{this.processes.delete(t),a("start",`Process ${t} stopped`,i),r()});try{n.process.kill("SIGTERM"),setTimeout(()=>{if(n.process){a("start",`Force killing process ${t}`,i);try{n.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){a("start",`Error stopping process ${t}: ${f}`,i),this.processes.delete(t),r()}})}async stopAll(t){if(this.isShuttingDown){a("start","Already shutting down, skipping duplicate stopAll call",t);return}this.isShuttingDown=!0,a("start","Stopping all processes",t);let i=Array.from(this.processes.keys()).map((n)=>this.stopProcess(n,t).catch((r)=>{S.error(`Failed to stop process ${n}:`,r)}));await Promise.allSettled(i),this.processes.clear(),this.isShuttingDown=!1}isRunning(t){let i=this.processes.get(t);return!!i?.process&&!i.process.killed}}var jT=new lf;var $f=new lf,a0="0.12.0",A0=new Rn("0.0.0.0"),Bn=new Set,wc=!1,sf=null,yc=null;async function Fn(t){if(wc)return a("cleanup","Cleanup already in progress, skipping",t?.verbose),yc||Promise.resolve();wc=!0,a("cleanup","Starting cleanup process",t?.verbose),yc=new Promise((i)=>{sf=i});try{await $f.stopAll(t?.verbose),S.info("Shutting down proxy servers...");let i=[],n=Array.from(Bn).map((r)=>new Promise((f)=>{r.close(()=>{a("cleanup","Server closed successfully",t?.verbose),f()})}));if(i.push(...n),t?.hosts&&t.domains?.length){a("cleanup","Cleaning up hosts file entries",t?.verbose),a("cleanup",`Original domains for cleanup: ${JSON.stringify(t.domains)}`,t?.verbose);let r=t.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(a("cleanup",`Filtered domains for cleanup: ${JSON.stringify(r)}`,t?.verbose),r.length>0)S.info("Cleaning up hosts file entries..."),i.push($c(r,t?.verbose).then(()=>{a("cleanup",`Removed hosts entries for ${r.join(", ")}`,t?.verbose)}).catch((f)=>{a("cleanup",`Failed to remove hosts entries: ${f}`,t?.verbose),S.warn(`Failed to clean up hosts file entries for ${r.join(", ")}:`,f)}))}if(t?.certs&&t.domains?.length){a("cleanup","Cleaning up SSL certificates",t?.verbose),S.info("Cleaning up SSL certificates...");let r=t.domains.map(async(f)=>{try{await nc(f,t?.verbose),a("cleanup",`Removed certificates for ${f}`,t?.verbose)}catch(e){a("cleanup",`Failed to remove certificates for ${f}: ${e}`,t?.verbose),S.warn(`Failed to clean up certificates for ${f}:`,e)}});i.push(...r)}await Promise.allSettled(i),a("cleanup","All cleanup tasks completed successfully",t?.verbose),S.success("All cleanup tasks completed successfully")}catch(i){a("cleanup",`Error during cleanup: ${i}`,t?.verbose),S.error("Error during cleanup:",i)}finally{if(sf)sf();sf=null,wc=!1;let i=t&&"vitePluginUsage"in t&&t.vitePluginUsage===!0;if(O.env.NODE_ENV!=="test"&&O.env.BUN_ENV!=="test"&&!i)O.exit(0)}return yc}var uc=!1;function ac(t){if(uc){a("signal",`Received second ${t} signal, forcing exit`,!0),O.exit(1);return}uc=!0,a("signal",`Received ${t} signal, initiating cleanup`,!0),Fn().catch((i)=>{a("signal",`Cleanup failed after ${t}: ${i}`,!0),O.exit(1)}).finally(()=>{uc=!1})}O.once("SIGINT",()=>ac("SIGINT"));O.once("SIGTERM",()=>ac("SIGTERM"));O.on("uncaughtException",(t)=>{a("process",`Uncaught exception: ${t}`,!0),S.error("Uncaught exception:",t),ac("uncaughtException")});async function Nn(t,i,n,r=5){a("connection",`Testing connection to ${t}:${i} (retries left: ${r})`,n);let f=15000,e=Date.now();if(O.env.RPX_BYPASS_CONNECTION_TEST==="true"){a("connection",`Bypassing connection test for ${t}:${i} due to RPX_BYPASS_CONNECTION_TEST flag`,n);return}let c=()=>new Promise((l,h)=>{let s=gs.connect({host:t,port:i,timeout:3000});s.once("connect",()=>{a("connection",`Successfully connected to ${t}:${i}`,n),s.end(),l()}),s.once("timeout",()=>{a("connection",`Connection to ${t}:${i} timed out`,n),s.destroy(),h(Error("Connection timed out"))}),s.once("error",($)=>{a("connection",`Failed to connect to ${t}:${i}: ${$}`,n),s.destroy(),h($)})});try{await c()}catch(l){if(Date.now()-e>f){a("connection",`Connection test timed out after ${f}ms, but continuing anyway`,n),S.warn(`Connection test to ${t}:${i} timed out, but RPX will try to proceed anyway.`);return}if(l.code==="ECONNREFUSED"&&r>0)return a("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${r} retries left)`,n),await new Promise((s)=>setTimeout(s,2000)),Nn(t,i,n,r-1);if(r>0)try{a("connection",`Trying HTTP request to ${t}:${i}`,n),await new Promise((s,$)=>{let w=Ti.request({hostname:t,port:i,path:"/",method:"HEAD",timeout:5000},(u)=>{a("connection",`Received HTTP response with status: ${u.statusCode}`,n),s()});w.on("error",(u)=>$(u)),w.on("timeout",()=>{w.destroy(),$(Error("HTTP request timed out"))}),w.end()}),a("connection",`HTTP request to ${t}:${i} succeeded`,n);return}catch(s){return a("connection",`HTTP request to ${t}:${i} failed: ${s}`,n),a("connection",`Retrying socket connection in 2 seconds... (${r} retries left)`,n),await new Promise(($)=>setTimeout($,2000)),Nn(t,i,n,r-1)}let h=`Failed to connect to ${t}:${i} after ${5-r} attempts: ${l.message}`;a("connection",`${h}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,n),S.warn(h),S.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function Ac(t){a("server",`Starting server with options: ${fi(t)}`,t.verbose);let i=new URL((t.from?.startsWith("http")?t.from:`http://${t.from}`)||"localhost:5173"),n=new URL((t.to?.startsWith("http")?t.to:`http://${t.to}`)||"rpx.localhost"),r=Number.parseInt(i.port)||(i.protocol.includes("https:")?443:80),f=[n.hostname];if(!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){a("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,t?.verbose);try{if(!(await nn(f,t.verbose))[0]){S.info(`Adding ${n.hostname} to hosts file...`),S.info("This may require sudo/administrator privileges");try{await tn(f,t.verbose)}catch(l){if(S.error("Failed to add hosts entry:",l.message),S.warn("You can manually add this entry to your hosts file:"),S.warn(`127.0.0.1 ${n.hostname}`),S.warn(`::1 ${n.hostname}`),O.platform==="win32")S.warn("On Windows:"),S.warn("1. Run notepad as administrator"),S.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else S.warn("On Unix systems:"),S.warn("sudo nano /etc/hosts")}}else a("hosts",`Host entry already exists for ${n.hostname}`,t.verbose)}catch(c){S.error("Failed to check hosts file:",c.message)}}try{await Nn(i.hostname,r,t.verbose)}catch(c){a("server",`Connection test failed: ${c}`,t.verbose),S.error(c.message),S.warn("Continuing with proxy setup despite connection test failure..."),S.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let e=t._cachedSSLConfig||null;if(t.https)try{if(t.https===!0)t.https=Ai({...t,to:n.hostname});if(e=await ti({...t,to:n.hostname,https:t.https}),!e){if(a("ssl",`Generating new certificates for ${n.hostname}`,t.verbose),await bi({...t,from:i.toString(),to:n.hostname,https:t.https}),e=await ti({...t,to:n.hostname,https:t.https}),!e)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw a("server",`SSL setup failed: ${c}`,t.verbose),c}a("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,t.verbose),await E0({...t,from:t.from||"localhost:5173",to:n.hostname,fromPort:r,sourceUrl:{hostname:i.hostname,host:i.host},ssl:e})}async function m0(t,i,n,r,f,e,c,l,h,s,$){a("proxy",`Creating proxy server ${t} -> ${i} with cleanUrls: ${s}`,h);function w(A){let T={};for(let[m,R]of Object.entries(A))if(!m.startsWith(":"))T[m]=R;return T}let u=(A,T)=>{a("request",`Incoming request: ${A.method} ${A.url}`,h);let m=A.url||"/",R=A.method||"GET";if(A instanceof Vs.Http2ServerRequest){let B=A.headers;R=B[":method"]||R,m=B[":path"]||m}if(s){if(!m.match(/\.[a-z0-9]+$/i))if(m.endsWith("/"))m=`${m}index.html`;else m=`${m}.html`}let C=w(A.headers);if($)C.host=`${e.hostname}:${n}`,a("request",`Changed origin: setting host header to ${C.host}`,h);let J={hostname:e.hostname,port:n,path:m,method:R,headers:C};a("request",`Proxy request options: ${fi(J)}`,h);let j=Ti.request(J,(B)=>{if(a("response",`Proxy response received with status ${B.statusCode}`,h),s&&B.statusCode===404){let mt=[];if(m.endsWith(".html"))mt.push(m.slice(0,-5));else if(!m.match(/\.[a-z0-9]+$/i))mt.push(`${m}.html`);if(!m.endsWith("/"))mt.push(`${m}/index.html`);if(mt.length>0){a("cleanUrls",`Trying alternative paths: ${mt.join(", ")}`,h);let rn=(Cn)=>{if(Cn.length===0){T.writeHead(B.statusCode||404,B.headers),B.pipe(T);return}let Ec=Cn[0],Xs={...J,path:Ec},Tc=Ti.request(Xs,(Jn)=>{if(Jn.statusCode===200)a("cleanUrls",`Found matching path: ${Ec}`,h),T.writeHead(Jn.statusCode,Jn.headers),Jn.pipe(T);else rn(Cn.slice(1))});Tc.on("error",()=>rn(Cn.slice(1))),Tc.end()};rn(mt);return}}let lt={...B.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};T.writeHead(B.statusCode||500,lt),B.pipe(T)});j.on("error",(B)=>{a("request",`Proxy request failed: ${B}`,h),S.error("Proxy request failed:",B),T.writeHead(502),T.end(`Proxy Error: ${B.message}`)}),A.pipe(j)};if(a("server",`Creating server with SSL config: ${!!c}`,h),c)return new Promise((A,T)=>{try{let m=Bun.serve({port:r,hostname:f,tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let C=new URL(R.url);a("request",`Bun.serve received: ${R.method} ${C.pathname}`,h);let J=`http://${e.host}`,j=new URL(C.pathname+C.search,J);try{let B=new Headers(R.headers);if(B.set("host",e.host),$)B.set("origin",J);B.set("x-forwarded-for","127.0.0.1"),B.set("x-forwarded-proto","https"),B.set("x-forwarded-host",i);let lt=await fetch(j.toString(),{method:R.method,headers:B,body:R.body,redirect:"manual"}),mt=new Headers(lt.headers);if(s&&C.pathname.endsWith(".html")){let rn=C.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:rn}})}return new Response(lt.body,{status:lt.status,statusText:lt.statusText,headers:mt})}catch(B){return a("request",`Proxy error: ${B}`,h),new Response(`Proxy Error: ${B}`,{status:502})}},error(R){return a("server",`Bun.serve error: ${R}`,h),new Response(`Server Error: ${R.message}`,{status:500})}});Bn.add(m),os({from:t,to:i,vitePluginUsage:l,listenPort:r,ssl:!0,cleanUrls:s,verbose:h}),A()}catch(m){T(m)}});let y=Ti.createServer(u);function E(A){return Bn.add(A),new Promise((T,m)=>{A.listen(r,f,()=>{a("server",`Server listening on port ${r}`,h),os({from:t,to:i,vitePluginUsage:l,listenPort:r,ssl:!!c,cleanUrls:s,verbose:h}),T()}),A.on("error",(R)=>{a("server",`Server error: ${R}`,h),m(R)})})}return E(y)}async function E0(t){a("setup",`Setting up reverse proxy: ${fi(t)}`,t.verbose);let{from:i,to:n,fromPort:r,sourceUrl:f,ssl:e,verbose:c,cleanup:l,vitePluginUsage:h,changeOrigin:s,cleanUrls:$}=t,w=80,u=443,y="0.0.0.0",E=t.portManager||A0;try{if(n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await nn([n],c))[0]){S.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await tn([n],c),S.success(`Added ${n} to your hosts file.`)}catch(C){S.error(`Failed to add ${n} to your hosts file: ${C}`),S.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(O.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await nn([n],c))[0]){a("hosts",`${n} not found in hosts file, adding...`,c);try{await tn([n],c)}catch(C){a("hosts",`Failed to add ${n} to hosts file: ${C}`,c)}}}if(e&&!E.usedPorts.has(w)){if(!await $i(w,y,c))a("setup","Starting HTTP redirect server",c),bs(c),E.usedPorts.add(w);else if(a("setup","Port 80 is in use, skipping HTTP redirect",c),c)S.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let A=e?u:w,T=await $i(A,y,c),m;if(T){if(a("setup",`Port ${A} is already in use`,c),c)S.warn(`Port ${A} is already in use. This may be another instance of rpx or another service.`);if(A===443){if(m=await E.getNextAvailablePort(3443,!0),a("setup",`Using port ${m} instead of ${A}`,c),c)S.info(`Using port ${m} instead. Access your site at https://${n}:${m}`)}else if(m=await E.getNextAvailablePort(A+1000,!0),a("setup",`Using port ${m} instead of ${A}`,c),c)S.info(`Using port ${m} instead. Access your site at http://${n}:${m}`)}else m=A,E.usedPorts.add(m),a("setup",`Using standard ${A===443?"HTTPS":"HTTP"} port ${A} for ${n}`,c);await m0(i,n,r,m,y,f,e,h,c,$,s)}catch(A){a("setup",`Setup failed: ${A}`,c),S.error(`Failed to setup reverse proxy: ${A.message}`),Fn({domains:[n],hosts:typeof l==="boolean"?l:l?.hosts,certs:typeof l==="boolean"?l:l?.certs,verbose:c,vitePluginUsage:h})}}function bs(t){a("redirect","Starting HTTP redirect server",t);let i=Ti.createServer((n,r)=>{let f=n.headers.host||"";a("redirect",`Redirecting request from ${f}${n.url} to HTTPS`,t),r.writeHead(301,{Location:`https://${f}${n.url}`}),r.end()}).listen(80);Bn.add(i),a("redirect","HTTP redirect server started",t)}function T0(t){let i={...Ii,...t};if(a("proxy",`Starting proxy with options: ${fi(i)}`,i?.verbose),i.viaDaemon){if(!i.from||!i.to){S.error("viaDaemon mode requires both `from` and `to`");return}ff({proxies:[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}],verbose:i.verbose}).catch((h)=>{S.error(`Failed to register with rpx daemon: ${h.message}`),O.exit(1)});return}let n=i.to||"",r=n.split(".").pop()?.toLowerCase()||"",f=O.platform==="darwin"&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1"),e=["dev","app","page","new","day","foo"],c=["test","localhost","local","example","invalid"];if(f&&e.includes(r)&&i?.verbose)S.warn(`The .${r} TLD may not work reliably for local development`),S.info(` Google owns .${r} with HSTS preloading, which can bypass local DNS`),S.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)import("./chunk-6z1nzq0x.js").then(({startDnsServer:h,setupResolver:s})=>{h([n],i.verbose).then(($)=>{if($)s(i.verbose,[n]).then(()=>{if(i.verbose)if(c.includes(r))S.success(`DNS server started for .${r} domains`);else S.success(`DNS server started for .${r} domains (hosts file entry also added)`)});else a("dns",`Could not start DNS server - ${n} may not resolve in browser`,i.verbose)})}).catch((h)=>{a("dns",`Failed to start DNS server: ${h}`,i.verbose)});let l={from:i.from,to:i.to,cleanUrls:i.cleanUrls,https:Ai(i),cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,changeOrigin:i.changeOrigin,verbose:i.verbose,regenerateUntrustedCerts:i.regenerateUntrustedCerts};a("proxy",`Server options: ${fi(l)}`,i.verbose),Ac(l).catch((h)=>{a("proxy",`Failed to start proxy: ${h}`,i.verbose),S.error(`Failed to start proxy: ${h.message}`),Fn({domains:[i.to],hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose})})}function S0(t){return t?.verbose||!1}async function mc(t){let i={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(t)i={...i,...t};let n=S0(i);if(a("config",`Starting with config: ${fi(i,2)}`,n),a("config",`Is multi-proxy? ${"proxies"in i}`,n),i.viaDaemon){let E="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((A)=>({id:A.id,from:A.from,to:A.to,cleanUrls:A.cleanUrls??i.cleanUrls,changeOrigin:A.changeOrigin??i.changeOrigin,pathRewrites:A.pathRewrites})):[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}];await ff({proxies:E,verbose:n});return}if("proxies"in i&&Array.isArray(i.proxies)){a("servers",`Found ${i.proxies.length} proxies in config`,n);for(let y of i.proxies)if(y.start){let E=`${y.from}-${y.to}`;try{a("watch",`Starting command for ${E} with command: ${y.start.command}`,n),S.info(`Starting command for ${E}...`),await $f.startProcess(E,y.start,n);let A=new URL(y.from.startsWith("http")?y.from:`http://${y.from}`),T=A.hostname||"localhost",m=Number(A.port)||80;try{await Nn(T,m,n),a("watch",`Dev server is ready at ${T}:${m}`,n)}catch(R){a("watch",`Connection check failed, but continuing with proxy setup: ${R}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(A){throw a("watch",`Failed to start command for ${E}: ${A}`,n),Error(`Failed to start command for ${E}: ${A}`)}}else a("watch",`No start command for proxy ${y.from} -> ${y.to}`,n)}else if("start"in i&&i.start){a("watch","Found start command in single proxy config",n);let y=`${i.from}-${i.to}`;try{if(i.start)a("watch",`Starting command: ${i.start.command}`,n),await $f.startProcess(y,i.start,n);let E=new URL(i.from?.startsWith("http")?i.from:`http://${i.from}`),A=E.hostname||"localhost",T=Number(E.port)||80;try{await Nn(A,T,n),a("watch",`Dev server is ready at ${A}:${T}`,n)}catch(m){a("watch",`Connection check failed, but continuing with proxy setup: ${m}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(E){throw a("watch",`Failed to run start command: ${E}`,n),Error(`Failed to run start command: ${E}`)}}else a("watch","No start command found in config",n);let r="proxies"in i&&Array.isArray(i.proxies)?i.proxies[0]?.to:("to"in i)?i.to:"rpx.localhost";if(O.platform!=="win32"&&(i.https||i.cleanup?.hosts!==!1)){if(!Tn())try{a("sudo","Pre-acquiring sudo credentials for privileged operations",n),u0("sudo -v",{stdio:"inherit"})}catch{a("sudo","Could not pre-acquire sudo credentials",n)}}if(i.https){let y=await ti(i);if(!y){if(a("ssl",`No valid or trusted certificates found for ${r}, generating new ones`,i.verbose),await bi(i),y=await ti(i),!y)throw Error(`Failed to load SSL certificates after generation for ${r}`)}else a("ssl",`Using existing and trusted certificates for ${r}`,i.verbose);i._cachedSSLConfig=y}let f="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((y)=>({...y,https:i.https,cleanup:i.cleanup,cleanUrls:y.cleanUrls??("cleanUrls"in i?i.cleanUrls:!1),vitePluginUsage:i.vitePluginUsage,changeOrigin:y.changeOrigin??i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig})):[{from:"from"in i?i.from:"localhost:5173",to:"to"in i?i.to:"rpx.localhost",cleanUrls:"cleanUrls"in i?i.cleanUrls:!1,https:i.https,cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,start:"start"in i?i.start:void 0,changeOrigin:i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig}],e=f.map((y)=>y.to||"rpx.localhost"),c=i._cachedSSLConfig,l=e.filter((y)=>y&&!y.includes("localhost")&&!y.includes("127.0.0.1")),h=["dev","app","page","new","day","foo"],s=["test","localhost","local","example","invalid"],$=[...new Set(l.map((y)=>y.split(".").pop()?.toLowerCase()))],w=$.filter((y)=>!!y&&h.includes(y));if(w.length>0&&n)S.warn(`The following TLDs may not work reliably for local development: ${w.map((y)=>`.${y}`).join(", ")}`),S.info(" These TLDs have HSTS preloading which can bypass local DNS"),S.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(O.platform==="darwin"&&l.length>0){let{startDnsServer:y,setupResolver:E}=await import("./chunk-6z1nzq0x.js");if(await y(l,n)){if(await E(n,l),n)if($.every((m)=>!!m&&s.includes(m)))S.success(`DNS server started for ${$.map((m)=>`.${m}`).join(", ")} domains`);else S.success(`DNS server started for ${$.map((m)=>`.${m}`).join(", ")} domains (hosts file entries also added)`)}else a("dns","Could not start DNS server - custom domains may not resolve",n)}let u=async()=>{a("cleanup","Starting cleanup handler",i.verbose);try{let{stopDnsServer:y,removeResolver:E}=await import("./chunk-6z1nzq0x.js");y(i.verbose),await E(i.verbose)}catch(y){a("cleanup",`Error stopping DNS server: ${y}`,i.verbose)}try{await $f.stopAll(i.verbose)}catch(y){a("cleanup",`Error stopping processes: ${y}`,i.verbose)}await Fn({domains:e,hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose||!1})};if(O.on("SIGINT",u),O.on("SIGTERM",u),O.on("uncaughtException",(y)=>{a("process",`Uncaught exception: ${y}`,!0),console.error("Uncaught exception:",y),u()}),c&&f.length>1){a("proxies",`Creating shared HTTPS server for ${f.length} domains`,n);let y=new Map;for(let m of f){let R=m.to||"rpx.localhost",C=new URL(m.from?.startsWith("http")?m.from:`http://${m.from}`);if(y.set(R,{sourceHost:C.host,cleanUrls:m.cleanUrls||!1,changeOrigin:m.changeOrigin||!1,pathRewrites:m.pathRewrites}),a("proxies",`Route: ${R} → ${C.host}`,n),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await nn([R],n))[0])await tn([R],n)}catch{a("hosts",`Could not add hosts entry for ${R}`,n)}}if(!await $i(80,"0.0.0.0",n))bs(n);let A=443;if(await $i(A,"0.0.0.0",n)){if(a("proxies",`Port ${A} is already in use, cannot start shared proxy`,n),n)S.warn(`Port ${A} is in use. Shared HTTPS proxy cannot start.`);return}try{let m=Bun.serve({port:A,hostname:"0.0.0.0",tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},fetch:En((R)=>y.get(R),n),error(R){return a("server",`Shared proxy server error: ${R}`,n),new Response(`Server Error: ${R.message}`,{status:500})}});Bn.add(m),a("proxies",`Shared HTTPS proxy listening on port ${A} for ${y.size} domains`,n)}catch(m){a("proxies",`Failed to start shared proxy: ${m}`,n),console.error("Failed to start shared HTTPS proxy:",m),u()}}else for(let y of f)try{let E=y.to||"rpx.localhost";a("proxy",`Starting proxy for ${E} with SSL config: ${!!c}`,y.verbose),await Ac({from:y.from||"localhost:5173",to:E,cleanUrls:y.cleanUrls||!1,https:y.https||!1,cleanup:y.cleanup||!1,vitePluginUsage:y.vitePluginUsage||!1,verbose:y.verbose||!1,_cachedSSLConfig:c,changeOrigin:y.changeOrigin||!1})}catch(E){a("proxies",`Failed to start proxy for ${y.to}: ${E}`,y.verbose),console.error(`Failed to start proxy for ${y.to}:`,E),u()}}function os(t){if(t?.vitePluginUsage||!t?.verbose)return;if(console.log(""),console.log(` ${jt.green(jt.bold("rpx"))} ${jt.green(`v${a0}`)}`),console.log(` ${jt.green("➜")} ${jt.dim(t?.from??"")} ${jt.dim("➜")} ${jt.cyan(t?.ssl?`https://${t?.to}`:`http://${t?.to}`)}`),t?.listenPort!==(t?.ssl?443:80))console.log(` ${jt.green("➜")} Listening on port ${t?.listenPort}`);if(t?.cleanUrls)console.log(` ${jt.green("➜")} Clean URLs enabled`)}var cS=mc;export{ec as writeEntry,cc as watchRegistry,l0 as stopDaemon,Ac as startServer,T0 as startProxy,mc as startProxies,fi as safeStringify,Is as safeDeleteFile,ff as runViaDaemon,h0 as runDaemon,Hs as resolvePathRewrite,$c as removeHosts,tf as removeEntry,vi as releaseDaemonLock,hS as redactSensitive,zs as readEntry,pi as readDaemonPid,Xi as readAll,w0 as portManager,Xa as loadSSLConfig,Ws as isValidRootCA,Pi as isValidId,Ys as isSingleProxyOptions,sS as isSingleProxyConfig,$i as isPortInUse,ni as isPidAlive,Pr as isMultiProxyOptions,ka as isMultiProxyConfig,f0 as isDaemonRunning,vr as isCertTrusted,Ai as httpsConfig,Tn as getSudoPassword,ii as getRegistryDir,tc as getPrimaryDomain,ri as getDaemonRpxDir,rf as getDaemonPidPath,bi as generateCertificate,nf as gcStaleEntries,Pa as forceTrustCertificate,ks as findAvailablePort,lS as extractHostname,Qe as execSudoSync,hc as ensureDaemonRunning,xs as deriveIdFromTarget,Ks as defaultDaemonSpawnCommand,Ii as defaultConfig,cS as default,a as debugLog,En as createProxyFetchHandler,Ii as config,jt as colors,nc as cleanupCertificates,Fn as cleanup,nn as checkHosts,ti as checkExistingCertificates,tn as addHosts,Gs as acquireDaemonLock,Rn as DefaultPortManager};
|
|
158
|
+
`,h=Nc.join($w.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Si.promises.writeFile(h,c,"utf8"),await Rf(`cat "${h}" | tee "${Ut}" > /dev/null`),a("hosts","Hosts removed successfully",i)}catch(l){a("hosts","Could not clean up hosts file automatically",i)}finally{try{await Si.promises.unlink(h)}catch(l){a("hosts",`Failed to remove temporary file: ${l}`,i)}}}catch(n){a("hosts",`Failed to clean up hosts file: ${n.message}`,i)}}async function ln(t,i){a("hosts",`Checking hosts: ${t}`,i);let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch(r){a("hosts",`Error reading hosts file: ${r}`,i);try{let f=Un(),e;if(f)e=`echo '${f}' | sudo -S cat "${Ut}" 2>/dev/null`;else e=`sudo -n cat "${Ut}" 2>/dev/null || cat "${Ut}" 2>/dev/null || echo ""`;let{stdout:c}=await Sf(e);n=c}catch(f){return a("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,i),t.map(()=>!1)}}return t.map((r)=>{let f=`127.0.0.1 ${r}`,e=`::1 ${r}`;return n.includes(f)||n.includes(e)})}import*as Bf from"node:net";function ai(t,i,n){return a("port",`Checking if port ${t} is in use on ${i}`,n),new Promise((r)=>{let f=Bf.createServer(),e=setTimeout(()=>{a("port",`Checking port ${t} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout(e),c.code==="EADDRINUSE")a("port",`Port ${t} is in use`,n),r(!0);else a("port",`Error checking port ${t}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(e),a("port",`Port ${t} is available`,n),f.close(),r(!1)});try{f.listen(t,i)}catch(c){clearTimeout(e),a("port",`Exception checking port ${t}: ${c}`,n),r(!0)}})}async function uw(t,i,n,r=50){a("port",`Finding available port starting from ${t} (max attempts: ${r})`,n);let f=t,e=0;while(e<r){if(e++,!await ai(f,i,n))return a("port",`Found available port: ${f} after ${e} attempts`,n),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${e}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${t}`)}function ww(t,i,n=5000,r){return a("port",`Testing connection to ${i}:${t}`,r),new Promise((f)=>{let e=Bf.connect({host:i,port:t,timeout:n});e.once("connect",()=>{a("port",`Successfully connected to ${i}:${t}`,r),e.end(),f(!0)}),e.once("timeout",()=>{a("port",`Connection to ${i}:${t} timed out`,r),e.destroy(),f(!1)}),e.once("error",(c)=>{a("port",`Failed to connect to ${i}:${t}: ${c.message}`,r),e.destroy(),f(!1)})})}class jn{usedPorts=new Set;hostname;verbose;maxRetries;constructor(t="0.0.0.0",i,n=50){this.hostname=t,this.verbose=i,this.maxRetries=n}async getNextAvailablePort(t,i=!1){if(this.usedPorts.has(t))return this.findNextAvailablePort(t+1,i);if(await ai(t,this.hostname,this.verbose))return this.findNextAvailablePort(t+1,i);if(i){if(!await ww(t,this.hostname,3000,this.verbose))return a("port",`Port ${t} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(t+1,i)}return this.usedPorts.add(t),t}async findNextAvailablePort(t,i=!1){let n=await uw(t,this.hostname,this.verbose,this.maxRetries);if(i){if(!await ww(n,this.hostname,3000,this.verbose))if(n<t+this.maxRetries)return this.findNextAvailablePort(n+1,i);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(t){a("port",`Releasing port ${t}`,this.verbose),this.usedPorts.delete(t)}}var Ha=new jn;import{spawn as Ma}from"node:child_process";import*as Ri from"node:process";class Cf{processes=new Map;isShuttingDown=!1;async startProcess(t,i,n){if(this.processes.has(t)){a("start",`Process ${t} is already running`,n);return}let[r,...f]=i.command.split(" "),e=i.cwd||Ri.cwd();a("start",`Starting process ${t}:`,n),a("start",` Command: ${r} ${f.join(" ")}`,n),a("start",` Working directory: ${e}`,n),a("start",` Environment variables: ${ci(i.env)}`,n);let c=Ma(r,f,{cwd:e,env:{...Ri.env,...i.env},shell:!0,stdio:"inherit"});return this.processes.set(t,{command:i.command,cwd:e,process:c,env:i.env}),new Promise((h,l)=>{if(c.on("error",($)=>{if(!this.isShuttingDown)a("start",`Process ${t} failed to start: ${$}`,n),this.processes.delete(t),l($),Ri.emit("SIGINT")}),c.on("exit",($)=>{if(!this.isShuttingDown&&$!==null&&$!==0)a("start",`Process ${t} exited with code ${$}`,n),this.processes.delete(t),l(Error(`Process ${t} exited with code ${$}`)),Ri.emit("SIGINT")}),n)c.stdout?.on("data",($)=>{a("process",`[${t}] ${$.toString().trim()}`,!0)}),c.stderr?.on("data",($)=>{a("process",`[${t}] ERR: ${$.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&c.killed)this.processes.delete(t),l(Error(`Process ${t} was killed during startup`));else a("start",`Process ${t} started successfully`,n),h()},1000)})}async stopProcess(t,i){let n=this.processes.get(t);if(!n?.process){a("start",`No process found for ${t}`,i);return}return a("start",`Stopping process ${t}`,i),new Promise((r)=>{if(!n.process){r();return}n.process.once("exit",()=>{this.processes.delete(t),a("start",`Process ${t} stopped`,i),r()});try{n.process.kill("SIGTERM"),setTimeout(()=>{if(n.process){a("start",`Force killing process ${t}`,i);try{n.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){a("start",`Error stopping process ${t}: ${f}`,i),this.processes.delete(t),r()}})}async stopAll(t){if(this.isShuttingDown){a("start","Already shutting down, skipping duplicate stopAll call",t);return}this.isShuttingDown=!0,a("start","Stopping all processes",t);let i=Array.from(this.processes.keys()).map((n)=>this.stopProcess(n,t).catch((r)=>{S.error(`Failed to stop process ${n}:`,r)}));await Promise.allSettled(i),this.processes.clear(),this.isShuttingDown=!1}isRunning(t){let i=this.processes.get(t);return!!i?.process&&!i.process.killed}}var hS=new Cf;var Nf=new Cf,Ga="0.12.0",Ka=new jn("0.0.0.0"),Wn=new Set,_c=!1,Ff=null,Uc=null;async function In(t){if(_c)return a("cleanup","Cleanup already in progress, skipping",t?.verbose),Uc||Promise.resolve();_c=!0,a("cleanup","Starting cleanup process",t?.verbose),Uc=new Promise((i)=>{Ff=i});try{await Nf.stopAll(t?.verbose),S.info("Shutting down proxy servers...");let i=[],n=Array.from(Wn).map((r)=>new Promise((f)=>{r.close(()=>{a("cleanup","Server closed successfully",t?.verbose),f()})}));if(i.push(...n),t?.hosts&&t.domains?.length){a("cleanup","Cleaning up hosts file entries",t?.verbose),a("cleanup",`Original domains for cleanup: ${JSON.stringify(t.domains)}`,t?.verbose);let r=t.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(a("cleanup",`Filtered domains for cleanup: ${JSON.stringify(r)}`,t?.verbose),r.length>0)S.info("Cleaning up hosts file entries..."),i.push(Jc(r,t?.verbose).then(()=>{a("cleanup",`Removed hosts entries for ${r.join(", ")}`,t?.verbose)}).catch((f)=>{a("cleanup",`Failed to remove hosts entries: ${f}`,t?.verbose),S.warn(`Failed to clean up hosts file entries for ${r.join(", ")}:`,f)}))}if(t?.certs&&t.domains?.length){a("cleanup","Cleaning up SSL certificates",t?.verbose),S.info("Cleaning up SSL certificates...");let r=t.domains.map(async(f)=>{try{await mc(f,t?.verbose),a("cleanup",`Removed certificates for ${f}`,t?.verbose)}catch(e){a("cleanup",`Failed to remove certificates for ${f}: ${e}`,t?.verbose),S.warn(`Failed to clean up certificates for ${f}:`,e)}});i.push(...r)}await Promise.allSettled(i),a("cleanup","All cleanup tasks completed successfully",t?.verbose),S.success("All cleanup tasks completed successfully")}catch(i){a("cleanup",`Error during cleanup: ${i}`,t?.verbose),S.error("Error during cleanup:",i)}finally{if(Ff)Ff();Ff=null,_c=!1;let i=t&&"vitePluginUsage"in t&&t.vitePluginUsage===!0;if(D.env.NODE_ENV!=="test"&&D.env.BUN_ENV!=="test"&&!i)D.exit(0)}return Uc}var dc=!1;function jc(t){if(dc){a("signal",`Received second ${t} signal, forcing exit`,!0),D.exit(1);return}dc=!0,a("signal",`Received ${t} signal, initiating cleanup`,!0),In().catch((i)=>{a("signal",`Cleanup failed after ${t}: ${i}`,!0),D.exit(1)}).finally(()=>{dc=!1})}D.once("SIGINT",()=>jc("SIGINT"));D.once("SIGTERM",()=>jc("SIGTERM"));D.on("uncaughtException",(t)=>{a("process",`Uncaught exception: ${t}`,!0),S.error("Uncaught exception:",t),jc("uncaughtException")});async function Yn(t,i,n,r=5){a("connection",`Testing connection to ${t}:${i} (retries left: ${r})`,n);let f=15000,e=Date.now();if(D.env.RPX_BYPASS_CONNECTION_TEST==="true"){a("connection",`Bypassing connection test for ${t}:${i} due to RPX_BYPASS_CONNECTION_TEST flag`,n);return}let c=()=>new Promise((h,l)=>{let $=aw.connect({host:t,port:i,timeout:3000});$.once("connect",()=>{a("connection",`Successfully connected to ${t}:${i}`,n),$.end(),h()}),$.once("timeout",()=>{a("connection",`Connection to ${t}:${i} timed out`,n),$.destroy(),l(Error("Connection timed out"))}),$.once("error",(w)=>{a("connection",`Failed to connect to ${t}:${i}: ${w}`,n),$.destroy(),l(w)})});try{await c()}catch(h){if(Date.now()-e>f){a("connection",`Connection test timed out after ${f}ms, but continuing anyway`,n),S.warn(`Connection test to ${t}:${i} timed out, but RPX will try to proceed anyway.`);return}if(h.code==="ECONNREFUSED"&&r>0)return a("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${r} retries left)`,n),await new Promise(($)=>setTimeout($,2000)),Yn(t,i,n,r-1);if(r>0)try{a("connection",`Trying HTTP request to ${t}:${i}`,n),await new Promise(($,w)=>{let s=Bi.request({hostname:t,port:i,path:"/",method:"HEAD",timeout:5000},(y)=>{a("connection",`Received HTTP response with status: ${y.statusCode}`,n),$()});s.on("error",(y)=>w(y)),s.on("timeout",()=>{s.destroy(),w(Error("HTTP request timed out"))}),s.end()}),a("connection",`HTTP request to ${t}:${i} succeeded`,n);return}catch($){return a("connection",`HTTP request to ${t}:${i} failed: ${$}`,n),a("connection",`Retrying socket connection in 2 seconds... (${r} retries left)`,n),await new Promise((w)=>setTimeout(w,2000)),Yn(t,i,n,r-1)}let l=`Failed to connect to ${t}:${i} after ${5-r} attempts: ${h.message}`;a("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,n),S.warn(l),S.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function Wc(t){a("server",`Starting server with options: ${ci(t)}`,t.verbose);let i=new URL((t.from?.startsWith("http")?t.from:`http://${t.from}`)||"localhost:5173"),n=new URL((t.to?.startsWith("http")?t.to:`http://${t.to}`)||"rpx.localhost"),r=Number.parseInt(i.port)||(i.protocol.includes("https:")?443:80),f=[n.hostname];if(!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){a("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,t?.verbose);try{if(!(await ln(f,t.verbose))[0]){S.info(`Adding ${n.hostname} to hosts file...`),S.info("This may require sudo/administrator privileges");try{await cn(f,t.verbose)}catch(h){if(S.error("Failed to add hosts entry:",h.message),S.warn("You can manually add this entry to your hosts file:"),S.warn(`127.0.0.1 ${n.hostname}`),S.warn(`::1 ${n.hostname}`),D.platform==="win32")S.warn("On Windows:"),S.warn("1. Run notepad as administrator"),S.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else S.warn("On Unix systems:"),S.warn("sudo nano /etc/hosts")}}else a("hosts",`Host entry already exists for ${n.hostname}`,t.verbose)}catch(c){S.error("Failed to check hosts file:",c.message)}}try{await Yn(i.hostname,r,t.verbose)}catch(c){a("server",`Connection test failed: ${c}`,t.verbose),S.error(c.message),S.warn("Continuing with proxy setup despite connection test failure..."),S.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let e=t._cachedSSLConfig||null;if(t.https)try{if(t.https===!0)t.https=Ei({...t,to:n.hostname});if(e=await ni({...t,to:n.hostname,https:t.https}),!e){if(a("ssl",`Generating new certificates for ${n.hostname}`,t.verbose),await nn({...t,from:i.toString(),to:n.hostname,https:t.https}),e=await ni({...t,to:n.hostname,https:t.https}),!e)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw a("server",`SSL setup failed: ${c}`,t.verbose),c}a("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,t.verbose),await xa({...t,from:t.from||"localhost:5173",to:n.hostname,fromPort:r,sourceUrl:{hostname:i.hostname,host:i.host},ssl:e})}async function qa(t,i,n,r,f,e,c,h,l,$,w){a("proxy",`Creating proxy server ${t} -> ${i} with cleanUrls: ${$}`,l);function s(A){let T={};for(let[E,R]of Object.entries(A))if(!E.startsWith(":"))T[E]=R;return T}let y=(A,T)=>{a("request",`Incoming request: ${A.method} ${A.url}`,l);let E=A.url||"/",R=A.method||"GET";if(A instanceof yw.Http2ServerRequest){let B=A.headers;R=B[":method"]||R,E=B[":path"]||E}if($){if(!E.match(/\.[a-z0-9]+$/i))if(E.endsWith("/"))E=`${E}index.html`;else E=`${E}.html`}let N=s(A.headers);if(w)N.host=`${e.hostname}:${n}`,a("request",`Changed origin: setting host header to ${N.host}`,l);let J={hostname:e.hostname,port:n,path:E,method:R,headers:N};a("request",`Proxy request options: ${ci(J)}`,l);let d=Bi.request(J,(B)=>{if(a("response",`Proxy response received with status ${B.statusCode}`,l),$&&B.statusCode===404){let mt=[];if(E.endsWith(".html"))mt.push(E.slice(0,-5));else if(!E.match(/\.[a-z0-9]+$/i))mt.push(`${E}.html`);if(!E.endsWith("/"))mt.push(`${E}/index.html`);if(mt.length>0){a("cleanUrls",`Trying alternative paths: ${mt.join(", ")}`,l);let hn=(Zn)=>{if(Zn.length===0){T.writeHead(B.statusCode||404,B.headers),B.pipe(T);return}let Ic=Zn[0],mw={...J,path:Ic},Zc=Bi.request(mw,(Hn)=>{if(Hn.statusCode===200)a("cleanUrls",`Found matching path: ${Ic}`,l),T.writeHead(Hn.statusCode,Hn.headers),Hn.pipe(T);else hn(Zn.slice(1))});Zc.on("error",()=>hn(Zn.slice(1))),Zc.end()};hn(mt);return}}let $t={...B.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};T.writeHead(B.statusCode||500,$t),B.pipe(T)});d.on("error",(B)=>{a("request",`Proxy request failed: ${B}`,l),S.error("Proxy request failed:",B),T.writeHead(502),T.end(`Proxy Error: ${B.message}`)}),A.pipe(d)};if(a("server",`Creating server with SSL config: ${!!c}`,l),c)return new Promise((A,T)=>{try{let E=Bun.serve({port:r,hostname:f,tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let N=new URL(R.url);a("request",`Bun.serve received: ${R.method} ${N.pathname}`,l);let J=`http://${e.host}`,d=new URL(N.pathname+N.search,J);try{let B=new Headers(R.headers);if(B.set("host",e.host),w)B.set("origin",J);B.set("x-forwarded-for","127.0.0.1"),B.set("x-forwarded-proto","https"),B.set("x-forwarded-host",i);let $t=await fetch(d.toString(),{method:R.method,headers:B,body:R.body,redirect:"manual"}),mt=new Headers($t.headers);if($&&N.pathname.endsWith(".html")){let hn=N.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:hn}})}return new Response($t.body,{status:$t.status,statusText:$t.statusText,headers:mt})}catch(B){return a("request",`Proxy error: ${B}`,l),new Response(`Proxy Error: ${B}`,{status:502})}},error(R){return a("server",`Bun.serve error: ${R}`,l),new Response(`Server Error: ${R.message}`,{status:500})}});Wn.add(E),sw({from:t,to:i,vitePluginUsage:h,listenPort:r,ssl:!0,cleanUrls:$,verbose:l}),A()}catch(E){T(E)}});let u=Bi.createServer(y);function m(A){return Wn.add(A),new Promise((T,E)=>{A.listen(r,f,()=>{a("server",`Server listening on port ${r}`,l),sw({from:t,to:i,vitePluginUsage:h,listenPort:r,ssl:!!c,cleanUrls:$,verbose:l}),T()}),A.on("error",(R)=>{a("server",`Server error: ${R}`,l),E(R)})})}return m(u)}async function xa(t){a("setup",`Setting up reverse proxy: ${ci(t)}`,t.verbose);let{from:i,to:n,fromPort:r,sourceUrl:f,ssl:e,verbose:c,cleanup:h,vitePluginUsage:l,changeOrigin:$,cleanUrls:w}=t,s=80,y=443,u="0.0.0.0",m=t.portManager||Ka;try{if(n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await ln([n],c))[0]){S.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await cn([n],c),S.success(`Added ${n} to your hosts file.`)}catch(N){S.error(`Failed to add ${n} to your hosts file: ${N}`),S.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(D.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await ln([n],c))[0]){a("hosts",`${n} not found in hosts file, adding...`,c);try{await cn([n],c)}catch(N){a("hosts",`Failed to add ${n} to hosts file: ${N}`,c)}}}if(e&&!m.usedPorts.has(s)){if(!await ai(s,u,c))a("setup","Starting HTTP redirect server",c),Aw(c),m.usedPorts.add(s);else if(a("setup","Port 80 is in use, skipping HTTP redirect",c),c)S.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let A=e?y:s,T=await ai(A,u,c),E;if(T){if(a("setup",`Port ${A} is already in use`,c),c)S.warn(`Port ${A} is already in use. This may be another instance of rpx or another service.`);if(A===443){if(E=await m.getNextAvailablePort(3443,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at https://${n}:${E}`)}else if(E=await m.getNextAvailablePort(A+1000,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at http://${n}:${E}`)}else E=A,m.usedPorts.add(E),a("setup",`Using standard ${A===443?"HTTPS":"HTTP"} port ${A} for ${n}`,c);await qa(i,n,r,E,u,f,e,l,c,w,$)}catch(A){a("setup",`Setup failed: ${A}`,c),S.error(`Failed to setup reverse proxy: ${A.message}`),In({domains:[n],hosts:typeof h==="boolean"?h:h?.hosts,certs:typeof h==="boolean"?h:h?.certs,verbose:c,vitePluginUsage:l})}}function Aw(t){a("redirect","Starting HTTP redirect server",t);let i=Bi.createServer((n,r)=>{let f=n.headers.host||"";a("redirect",`Redirecting request from ${f}${n.url} to HTTPS`,t),r.writeHead(301,{Location:`https://${f}${n.url}`}),r.end()}).listen(80);Wn.add(i),a("redirect","HTTP redirect server started",t)}function Oa(t){let i={...Mi,...t};if(a("proxy",`Starting proxy with options: ${ci(i)}`,i?.verbose),i.viaDaemon){if(!i.from||!i.to){S.error("viaDaemon mode requires both `from` and `to`");return}Tf({proxies:[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}],verbose:i.verbose}).catch((l)=>{S.error(`Failed to register with rpx daemon: ${l.message}`),D.exit(1)});return}let n=i.to||"",r=n.split(".").pop()?.toLowerCase()||"",f=D.platform==="darwin"&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1"),e=["dev","app","page","new","day","foo"],c=["test","localhost","local","example","invalid"];if(f&&e.includes(r)&&i?.verbose)S.warn(`The .${r} TLD may not work reliably for local development`),S.info(` Google owns .${r} with HSTS preloading, which can bypass local DNS`),S.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)import("./chunk-6z1nzq0x.js").then(({startDnsServer:l,setupResolver:$})=>{l([n],i.verbose).then((w)=>{if(w)$(i.verbose,[n]).then(()=>{if(i.verbose)if(c.includes(r))S.success(`DNS server started for .${r} domains`);else S.success(`DNS server started for .${r} domains (hosts file entry also added)`)});else a("dns",`Could not start DNS server - ${n} may not resolve in browser`,i.verbose)})}).catch((l)=>{a("dns",`Failed to start DNS server: ${l}`,i.verbose)});let h={from:i.from,to:i.to,cleanUrls:i.cleanUrls,https:Ei(i),cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,changeOrigin:i.changeOrigin,verbose:i.verbose,regenerateUntrustedCerts:i.regenerateUntrustedCerts};a("proxy",`Server options: ${ci(h)}`,i.verbose),Wc(h).catch((l)=>{a("proxy",`Failed to start proxy: ${l}`,i.verbose),S.error(`Failed to start proxy: ${l.message}`),In({domains:[i.to],hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose})})}function Da(t){return t?.verbose||!1}async function Yc(t){let i={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(t)i={...i,...t};let n=Da(i);if(a("config",`Starting with config: ${ci(i,2)}`,n),a("config",`Is multi-proxy? ${"proxies"in i}`,n),i.viaDaemon){let m="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((A)=>({id:A.id,from:A.from,to:A.to,cleanUrls:A.cleanUrls??i.cleanUrls,changeOrigin:A.changeOrigin??i.changeOrigin,pathRewrites:A.pathRewrites})):[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}];await Tf({proxies:m,verbose:n});return}if("proxies"in i&&Array.isArray(i.proxies)){a("servers",`Found ${i.proxies.length} proxies in config`,n);for(let u of i.proxies)if(u.start){let m=`${u.from}-${u.to}`;try{a("watch",`Starting command for ${m} with command: ${u.start.command}`,n),S.info(`Starting command for ${m}...`),await Nf.startProcess(m,u.start,n);let A=new URL(u.from.startsWith("http")?u.from:`http://${u.from}`),T=A.hostname||"localhost",E=Number(A.port)||80;try{await Yn(T,E,n),a("watch",`Dev server is ready at ${T}:${E}`,n)}catch(R){a("watch",`Connection check failed, but continuing with proxy setup: ${R}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(A){throw a("watch",`Failed to start command for ${m}: ${A}`,n),Error(`Failed to start command for ${m}: ${A}`)}}else a("watch",`No start command for proxy ${u.from} -> ${u.to}`,n)}else if("start"in i&&i.start){a("watch","Found start command in single proxy config",n);let u=`${i.from}-${i.to}`;try{if(i.start)a("watch",`Starting command: ${i.start.command}`,n),await Nf.startProcess(u,i.start,n);let m=new URL(i.from?.startsWith("http")?i.from:`http://${i.from}`),A=m.hostname||"localhost",T=Number(m.port)||80;try{await Yn(A,T,n),a("watch",`Dev server is ready at ${A}:${T}`,n)}catch(E){a("watch",`Connection check failed, but continuing with proxy setup: ${E}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(m){throw a("watch",`Failed to run start command: ${m}`,n),Error(`Failed to run start command: ${m}`)}}else a("watch","No start command found in config",n);let r="proxies"in i&&Array.isArray(i.proxies)?i.proxies[0]?.to:("to"in i)?i.to:"rpx.localhost";if(D.platform!=="win32"&&(i.https||i.cleanup?.hosts!==!1)){if(!Un())try{a("sudo","Pre-acquiring sudo credentials for privileged operations",n),za("sudo -v",{stdio:"inherit"})}catch{a("sudo","Could not pre-acquire sudo credentials",n)}}if(i.https){let u=await ni(i);if(!u){if(a("ssl",`No valid or trusted certificates found for ${r}, generating new ones`,i.verbose),await nn(i),u=await ni(i),!u)throw Error(`Failed to load SSL certificates after generation for ${r}`)}else a("ssl",`Using existing and trusted certificates for ${r}`,i.verbose);i._cachedSSLConfig=u}let f="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((u)=>({...u,https:i.https,cleanup:i.cleanup,cleanUrls:u.cleanUrls??("cleanUrls"in i?i.cleanUrls:!1),vitePluginUsage:i.vitePluginUsage,changeOrigin:u.changeOrigin??i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig})):[{from:"from"in i?i.from:"localhost:5173",to:"to"in i?i.to:"rpx.localhost",cleanUrls:"cleanUrls"in i?i.cleanUrls:!1,https:i.https,cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,start:"start"in i?i.start:void 0,changeOrigin:i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig}],e=f.map((u)=>u.to||"rpx.localhost"),c=i._cachedSSLConfig,h=e.filter((u)=>u&&!u.includes("localhost")&&!u.includes("127.0.0.1")),l=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],w=[...new Set(h.map((u)=>u.split(".").pop()?.toLowerCase()))],s=w.filter((u)=>!!u&&l.includes(u));if(s.length>0&&n)S.warn(`The following TLDs may not work reliably for local development: ${s.map((u)=>`.${u}`).join(", ")}`),S.info(" These TLDs have HSTS preloading which can bypass local DNS"),S.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(D.platform==="darwin"&&h.length>0){let{startDnsServer:u,setupResolver:m}=await import("./chunk-6z1nzq0x.js");if(await u(h,n)){if(await m(n,h),n)if(w.every((E)=>!!E&&$.includes(E)))S.success(`DNS server started for ${w.map((E)=>`.${E}`).join(", ")} domains`);else S.success(`DNS server started for ${w.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else a("dns","Could not start DNS server - custom domains may not resolve",n)}let y=async()=>{a("cleanup","Starting cleanup handler",i.verbose);try{let{stopDnsServer:u,removeResolver:m}=await import("./chunk-6z1nzq0x.js");u(i.verbose),await m(i.verbose)}catch(u){a("cleanup",`Error stopping DNS server: ${u}`,i.verbose)}try{await Nf.stopAll(i.verbose)}catch(u){a("cleanup",`Error stopping processes: ${u}`,i.verbose)}await In({domains:e,hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose||!1})};if(D.on("SIGINT",y),D.on("SIGTERM",y),D.on("uncaughtException",(u)=>{a("process",`Uncaught exception: ${u}`,!0),console.error("Uncaught exception:",u),y()}),c&&f.length>1){a("proxies",`Creating shared HTTPS server for ${f.length} domains`,n);let u=new Map;for(let E of f){let R=E.to||"rpx.localhost",N=new URL(E.from?.startsWith("http")?E.from:`http://${E.from}`);if(u.set(R,{sourceHost:N.host,cleanUrls:E.cleanUrls||!1,changeOrigin:E.changeOrigin||!1,pathRewrites:E.pathRewrites}),a("proxies",`Route: ${R} → ${N.host}`,n),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await ln([R],n))[0])await cn([R],n)}catch{a("hosts",`Could not add hosts entry for ${R}`,n)}}if(!await ai(80,"0.0.0.0",n))Aw(n);let A=443;if(await ai(A,"0.0.0.0",n)){if(a("proxies",`Port ${A} is already in use, cannot start shared proxy`,n),n)S.warn(`Port ${A} is in use. Shared HTTPS proxy cannot start.`);return}try{let E=Bun.serve({port:A,hostname:"0.0.0.0",tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_n((R)=>u.get(R),n),error(R){return a("server",`Shared proxy server error: ${R}`,n),new Response(`Server Error: ${R.message}`,{status:500})}});Wn.add(E),a("proxies",`Shared HTTPS proxy listening on port ${A} for ${u.size} domains`,n)}catch(E){a("proxies",`Failed to start shared proxy: ${E}`,n),console.error("Failed to start shared HTTPS proxy:",E),y()}}else for(let u of f)try{let m=u.to||"rpx.localhost";a("proxy",`Starting proxy for ${m} with SSL config: ${!!c}`,u.verbose),await Wc({from:u.from||"localhost:5173",to:m,cleanUrls:u.cleanUrls||!1,https:u.https||!1,cleanup:u.cleanup||!1,vitePluginUsage:u.vitePluginUsage||!1,verbose:u.verbose||!1,_cachedSSLConfig:c,changeOrigin:u.changeOrigin||!1})}catch(m){a("proxies",`Failed to start proxy for ${u.to}: ${m}`,u.verbose),console.error(`Failed to start proxy for ${u.to}:`,m),y()}}function sw(t){if(t?.vitePluginUsage||!t?.verbose)return;if(console.log(""),console.log(` ${dt.green(dt.bold("rpx"))} ${dt.green(`v${Ga}`)}`),console.log(` ${dt.green("➜")} ${dt.dim(t?.from??"")} ${dt.dim("➜")} ${dt.cyan(t?.ssl?`https://${t?.to}`:`http://${t?.to}`)}`),t?.listenPort!==(t?.ssl?443:80))console.log(` ${dt.green("➜")} Listening on port ${t?.listenPort}`);if(t?.cleanUrls)console.log(` ${dt.green("➜")} Clean URLs enabled`)}var DS=Yc;export{Rc as writeEntry,Bc as watchRegistry,V$ as verifyHttpsChain,$f as trustRootCaForBrowsers,Ya as stopDaemon,Wc as startServer,Oa as startProxy,Yc as startProxies,ci as safeStringify,v$ as safeDeleteFile,Tf as runViaDaemon,Wa as runDaemon,tw as resolvePathRewrite,Jc as removeHosts,Af as removeEntry,fn as releaseDaemonLock,LS as redactSensitive,nw as readEntry,en as readDaemonPid,Cn as readCertSha256Fingerprint,L$ as readCertCommonName,Ti as readAll,Jn as pruneStaleRootCas,Ha as portManager,o$ as parseSha256HashesFromSecurityListing,sc as normalizeSha256Fingerprint,Ta as loadSSLConfig,yc as listCertSha256HashesByCommonName,X$ as isValidRootCA,rn as isValidId,P$ as isSingleProxyOptions,VS as isSingleProxyConfig,pi as isRootCaTrustedForSsl,Qi as isRootCaFingerprintInKeychains,ai as isPortInUse,fi as isPidAlive,wf as isMultiProxyOptions,ya as isMultiProxyConfig,_a as isDaemonRunning,Ec as isCertTrusted,Ei as httpsConfig,Un as getSudoPassword,ma as getSharedDaemonCertPaths,sf as getRootCAPaths,ri as getRegistryDir,Ac as getPrimaryDomain,hf as getMacosTrustKeychains,vi as getMacosLoginKeychainPath,ei as getDaemonRpxDir,Ef as getDaemonPidPath,nn as generateCertificate,mf as gcStaleEntries,Sa as forceTrustCertificate,uw as findAvailablePort,kS as extractHostname,Fn as execSudoSync,Cc as ensureDaemonRunning,hw as deriveIdFromTarget,ew as defaultDaemonSpawnCommand,Mi as defaultConfig,DS as default,a as debugLog,_n as createProxyFetchHandler,Mi as config,dt as colors,Q$ as clearSslConfigCache,mc as cleanupCertificates,In as cleanup,ln as checkHosts,ni as checkExistingCertificates,k$ as certIncludesSanHostnames,cn as addHosts,fw as acquireDaemonLock,lf as RPX_ROOT_CA_COMMON_NAME,si as MACOS_SYSTEM_KEYCHAIN,ii as MACOS_CA_TRUST_FLAGS,jn as DefaultPortManager};
|