@stacksjs/rpx 0.11.7 → 0.11.10

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/index.js CHANGED
@@ -1,155 +1,8 @@
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 y of u)if(y.trim()&&!y.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!L()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let h=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
3
- `;if(l)h+=`${l}
4
- `;h=h.replace(this.ANSI_PATTERN,""),await this.writeToFile(h)}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,l=this.formatConsoleTimestamp(c),s=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)s+=` ${JSON.stringify(n)}`;if(s+=`
5
- `,s=s.replace(this.ANSI_PATTERN,""),this.fancy&&!L()){let $=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:K.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!L())console.error(s.trim());await this.writeToFile(s)}}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 pn(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(!af(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return _c(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=ei.isBuffer(t)?t:ei.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),l=c$("aes-256-gcm",n,f);return l.setAuthTag(e),ei.concat([l.update(c),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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(($)=>$.length))+2,l=`┌${"─".repeat(c)}┐`,h=`└${"─".repeat(c)}┘`,s=e.map(($)=>{let w=" ".repeat(c-$.length-2);return`│ ${$}${w} │`});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(l)})),s.forEach(($)=>console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan($),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(h),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();nt.stdin.removeListener("data",n);try{if(typeof nt.stdin.setRawMode==="function")nt.stdin.setRawMode(!1)}catch{}nt.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof nt.stdin.setRawMode==="function")nt.stdin.setRawMode(!0)}catch{}nt.stdin.resume(),nt.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,l=0;if(n=t.replace(c,(h,s)=>{if(s==="%")return"%";if(l>=i.length)return h;let $=i[l++];switch(s){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return h}}),l<i.length)n+=` ${i.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}if(this.fancy&&!L()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",l=K.blue("◐");console.error(`${l} ${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,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,c)),l!==void 0)this.activeProgressBar.message=l;let h=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,h)},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,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;nt.stdout.write(`${"\r".padEnd(nt.stdout.columns||80)}\r`),this.log(l,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||L()||!nt.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)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),s=t.message?` ${t.message}`:"",$=i||n===100?K.green("✓"):K.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",u=`\r${$}${w} ${l} ${h}${s}`,y=nt.stdout.columns||80,E=" ".repeat(Math.max(0,y-u.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${u}${E}`,nt.stdout.write(t.lastRenderedLine),i)nt.stdout.write(`
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 E)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:d.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!g()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let $=`${e} ${this.environment}.${t.toUpperCase()}: ${s}
11
- `;if(l)$+=`${l}
12
- `;if($=$.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile($)}progress(t,i=""){let n={update:(l,h)=>{},finish:(l)=>{},interrupt:(l,h)=>{}};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:(l,h)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),h!==void 0)this.activeProgressBar.message=h;if(this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,h="info")=>{if(!g()&&_.stdout.isTTY)_.stdout.write(`
13
- `);if(this[h==="warning"?"warn":h](l),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?d.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":d.blue("◐"),tag:n,message:`${d.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,l=this.formatConsoleTimestamp(c),s=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)s+=` ${JSON.stringify(n)}`;if(s+=`
14
- `,s=s.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":d.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!g())console.error(s.trim());if(this.shouldWriteToFile())await this.writeToFile(s)}}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(g())throw Error("createReadStream is not supported in browser environments");if(!dn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ic(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=qt.isBuffer(t)?t:qt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=u$("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),s=l.final(),$=h.length+s.length,w=qt.allocUnsafe($);return h.copy(w,0),s.copy(w,h.length),w.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 l=f.split(`
15
- `),h=Math.max(...l.map((u)=>u.length))+2,s=`┌${"─".repeat(h)}┐`,$=`└${"─".repeat(h)}┘`,w=l.map((u)=>{return this.formatConsoleMessage({timestamp:n,message:d.cyan(u),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan(s),showTimestamp:!1})),w.forEach((u)=>console.error(u)),console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan($),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(`${d.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 h=/%([sdijfo%])/g,s=0;if(n=t.replace(h,($,w)=>{if(w==="%")return"%";if(s>=i.length)return $;let u=i[s++];switch(w){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return $}}),s<i.length)n+=` ${i.slice(s).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",s=this.options.showIcons===!1?"":`${d.blue("◐")} `;console.error(`${s}${h} ${d.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}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=d.green("━".repeat(r)),c=d.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),s=t.message?` ${t.message}`:"",$=this.options.showIcons===!1?"":i||n===100?d.green("✓"):d.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",u=`\r${$}${w} ${l} ${h}${s}`,y=_.stdout.columns||80,E=" ".repeat(Math.max(0,y-u.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${u}${E}`,_.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 Wn(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 Ci(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 Yn(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 yh(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise((s)=>setTimeout(s,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function uh(t){return t instanceof Et}function tw(t){return t instanceof ir}function iw(t){if(uh(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 hr{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:l=!1,trackPerformance:h=!0}=n,s=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let $=r||this.generateEnvPrefix(t),w={...i};return this.processObject(w,[],$,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return ln.track("applyEnvironmentVariables",s,{configName:t});return s()}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],l=c.map(($)=>this.formatEnvKey($,r.useCamelCase)),h=`${n}_${l.join("_")}`,s=r.useBackwardCompatibility?`${n}_${c.map(($)=>$.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let $=In.env[h]||(s?In.env[s]:void 0);if($!==void 0){if(r.verbose){let w=In.env[h]?h:s}try{t[f]=this.parseEnvironmentValue($,typeof e,h,r.customParsers,r.configName)}catch(w){if(w instanceof nr)throw w;throw ci.envVar(h,$,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 ci.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(In.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],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,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
-
20
- `;for(let r of t)n+=`${r.key}
21
- `,n+=` Type: ${r.type}
22
- `,n+=` Description: ${r.description}
23
- `,n+=` Example: ${r.example}
24
-
25
- `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
26
-
27
- `;n+=`| Variable | Type | Description | Example |
28
- `,n+=`|----------|------|-------------|----------|
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}
31
- export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
32
- `;t$(r,e,{mode:438})}function ww(t){let i=null,n=null,r=()=>{if(!n)n=Eh(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)dt.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 l=f[c];return r(),l},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,l){if(!i)i={...f};return i[c]=l,!0}})}function yw(t){let i=Kc(C$.cwd(),t?.configDir||"./config");function n(){if(!N$(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=F$(i).filter((h)=>f.has(Rf(h))).map((h)=>({base:h.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:h})),l=new Map;for(let{base:h,file:s}of c){let $=Rf(s).toLowerCase(),w=l.get(h);if(!w){l.set(h,s);continue}let u=Rf(w).toLowerCase();if(e.indexOf($)<e.indexOf(u))l.set(h,s)}return Array.from(l.entries()).map(([h,s])=>({base:h,file:s})).sort((h,s)=>h.base.localeCompare(s.base))}function r(){let f=n(),e=f.map((s)=>s.base),c=e.length?e.map((s)=>`'${s}'`).join(" | "):"string",l=f.length?`{
33
- ${f.map((s)=>{let $=Kc(i,s.file).replace(/\\/g,"/");return` '${s.base}': typeof import('${$}').default`}).join(`,
34
- `)}
35
- }`:"Record<string, any>";return`export type ConfigNames = ${c}
36
- export type ConfigByName = ${l}
37
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
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 E)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}`),l)console.error(l)}let $=`${e} ${this.environment}.${t.toUpperCase()}: ${s}
41
- `;if(l)$+=`${l}
42
- `;if($=$.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile($)}progress(t,i=""){let n={update:(l,h)=>{},finish:(l)=>{},interrupt:(l,h)=>{}};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:(l,h)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),h!==void 0)this.activeProgressBar.message=h;if(this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,h="info")=>{if(!X()&&U.stdout.isTTY)U.stdout.write(`
43
- `);if(this[h==="warning"?"warn":h](l),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,l=this.formatConsoleTimestamp(c),s=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)s+=` ${JSON.stringify(n)}`;if(s+=`
44
- `,s=s.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":Y.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!X())console.error(s.trim());if(this.shouldWriteToFile())await this.writeToFile(s)}}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 sr(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(!Hn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Dc(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=Dt.isBuffer(t)?t:Dt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=j$("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),s=l.final(),$=h.length+s.length,w=Dt.allocUnsafe($);return h.copy(w,0),s.copy(w,h.length),w.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 l=f.split(`
45
- `),h=Math.max(...l.map((u)=>u.length))+2,s=`┌${"─".repeat(h)}┐`,$=`└${"─".repeat(h)}┘`,w=l.map((u)=>{return this.formatConsoleMessage({timestamp:n,message:Y.cyan(u),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan(s),showTimestamp:!1})),w.forEach((u)=>console.error(u)),console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan($),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 h=/%([sdijfo%])/g,s=0;if(n=t.replace(h,($,w)=>{if(w==="%")return"%";if(s>=i.length)return $;let u=i[s++];switch(w){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return $}}),s<i.length)n+=` ${i.slice(s).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",s=this.options.showIcons===!1?"":`${Y.blue("◐")} `;console.error(`${s}${h} ${Y.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}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)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),s=t.message?` ${t.message}`:"",$=this.options.showIcons===!1?"":i||n===100?Y.green("✓"):Y.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",u=`\r${$}${w} ${l} ${h}${s}`,y=U.stdout.columns||80,E=" ".repeat(Math.max(0,y-u.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${u}${E}`,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 Mn(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 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 zn(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 pA=new sr("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 jh 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 fr 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 dh 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 Wh 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 Pf 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 Yh 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 Ih 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 er 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 Zh 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 Hh 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 Yi={configNotFound(t,i,n){return new jh(t,i,n)},configLoad(t,i,n){return new fr(t,i,n)},configValidation(t,i,n){return new dh(t,i,n)},configMerge(t,i,n,r){return new Wh(t,i,n,r)},envVar(t,i,n,r){return new Pf(t,i,n,r)},fileSystem(t,i,n){return new Yh(t,i,n)},typeGeneration(t,i,n){return new Ih(t,i,n)},schemaValidation(t,i,n){return new er(t,i,n)},browserConfig(t,i,n,r){return new Zh(t,i,n,r)},plugin(t,i,n){return new Hh(t,i,n)}};async function Xw(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise((s)=>setTimeout(s,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class vf{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:l=!1,trackPerformance:h=!0}=n,s=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let $=r||this.generateEnvPrefix(t),w={...i};return this.processObject(w,[],$,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return Of.track("applyEnvironmentVariables",s,{configName:t});return s()}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],l=c.map(($)=>this.formatEnvKey($,r.useCamelCase)),h=`${n}_${l.join("_")}`,s=r.useBackwardCompatibility?`${n}_${c.map(($)=>$.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let $=Kn.env[h]||(s?Kn.env[s]:void 0);if($!==void 0){if(r.verbose){let w=Kn.env[h]?h:s}try{t[f]=this.parseEnvironmentValue($,typeof e,h,r.customParsers,r.configName)}catch(w){if(w instanceof Pf)throw w;throw Yi.envVar(h,$,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 Yi.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(Kn.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],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,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
-
50
- `;for(let r of t)n+=`${r.key}
51
- `,n+=` Type: ${r.type}
52
- `,n+=` Description: ${r.description}
53
- `,n+=` Example: ${r.example}
54
-
55
- `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
56
-
57
- `;n+=`| Variable | Type | Description | Example |
58
- `,n+=`|----------|------|-------------|----------|
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 y of u)if(y.trim()&&!y.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:q.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let h=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
62
- `;if(l)h+=`${l}
63
- `;h=h.replace(this.ANSI_PATTERN,""),await this.writeToFile(h)}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,l=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
64
- `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let s=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:q.green("✓"),tag:s,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!k())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new Mr(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(!ee(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bh(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=hi.isBuffer(t)?t:hi.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),l=my("aes-256-gcm",n,f);return l.setAuthTag(e),hi.concat([l.update(c),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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(($)=>$.length))+2,l=`┌${"─".repeat(c)}┐`,h=`└${"─".repeat(c)}┘`,s=e.map(($)=>{let w=" ".repeat(c-$.length-2);return`│ ${$}${w} │`});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(l)})),s.forEach(($)=>console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan($),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(h),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();et.stdin.removeListener("data",n);try{if(typeof et.stdin.setRawMode==="function")et.stdin.setRawMode(!1)}catch{}et.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof et.stdin.setRawMode==="function")et.stdin.setRawMode(!0)}catch{}et.stdin.resume(),et.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,l)=>{if(l==="%")return"%";if(e>=i.length)return c;let h=i[e++];switch(l){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 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;et.stdout.write(`${"\r".padEnd(et.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()||!et.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)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),s=t.message?` ${t.message}`:"",$=i||n===100?q.green("✓"):q.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",u=`\r${$}${w} ${l} ${h}${s}`,y=et.stdout.columns||80,E=" ".repeat(Math.max(0,y-u.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${u}${E}`,et.stdout.write(t.lastRenderedLine),i)et.stdout.write(`
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 E)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}`),l)console.error(l)}if(!this.shouldLog(t))return;let $=`${e} ${this.environment}.${t.toUpperCase()}: ${s}
70
- `;if(l)$+=`${l}
71
- `;if($=$.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile($)}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,l=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
73
- `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":W.green("✓"),tag:s,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new Gr(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(!yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return tl(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=Vt.isBuffer(t)?t:Vt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=Fy("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),s=l.final(),$=h.length+s.length,w=Vt.allocUnsafe($);return h.copy(w,0),s.copy(w,h.length),w.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 l=f.split(`
74
- `),h=Math.max(...l.map((u)=>u.length))+2,s=`┌${"─".repeat(h)}┐`,$=`└${"─".repeat(h)}┘`,w=l.map((u)=>{return this.formatConsoleMessage({timestamp:n,message:W.cyan(u),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan(s),showTimestamp:!1})),w.forEach((u)=>console.error(u)),console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan($),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,l=0;if(n=t.replace(c,(h,s)=>{if(s==="%")return"%";if(l>=i.length)return h;let $=i[l++];switch(s){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return h}}),l<i.length)n+=` ${i.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).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)):"",l=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${l}${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)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),s=t.message?` ${t.message}`:"",$=this.options.showIcons===!1?"":i||n===100?W.green("✓"):W.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",u=`\r${$}${w} ${l} ${h}${s}`,y=H.stdout.columns||80,E=" ".repeat(Math.max(0,y-u.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${u}${E}`,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 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=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 ar(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 Dl(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise((s)=>setTimeout(s,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function xl(t){return t instanceof Tt}function wu(t){return t instanceof Kr}function yu(t){if(xl(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 Vr{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:l=!1,trackPerformance:h=!0}=n,s=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let $=r||this.generateEnvPrefix(t),w={...i};return this.processObject(w,[],$,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return mn.track("applyEnvironmentVariables",s,{configName:t});return s()}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],l=c.map(($)=>this.formatEnvKey($,r.useCamelCase)),h=`${n}_${l.join("_")}`,s=r.useBackwardCompatibility?`${n}_${c.map(($)=>$.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let $=Ar.env[h]||(s?Ar.env[s]:void 0);if($!==void 0){if(r.verbose){let w=Ar.env[h]?h:s}try{t[f]=this.parseEnvironmentValue($,typeof e,h,r.customParsers,r.configName)}catch(w){if(w instanceof qr)throw w;throw si.envVar(h,$,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 si.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(Ar.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],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,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
-
79
- `;for(let r of t)n+=`${r.key}
80
- `,n+=` Type: ${r.type}
81
- `,n+=` Description: ${r.description}
82
- `,n+=` Example: ${r.example}
83
-
84
- `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
85
-
86
- `;n+=`| Variable | Type | Description | Example |
87
- `,n+=`|----------|------|-------------|----------|
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}
90
- export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
91
- `;$y(r,e,{mode:438})}function Nu(t){let i=null,n=null,r=()=>{if(!n)n=ol(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 l=f[c];return r(),l},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,l){if(!i)i={...f};return i[c]=l,!0}})}function Fu(t){let i=cl(Hy.cwd(),t?.configDir||"./config");function n(){if(!Iy(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=Zy(i).filter((h)=>f.has(we(h))).map((h)=>({base:h.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:h})),l=new Map;for(let{base:h,file:s}of c){let $=we(s).toLowerCase(),w=l.get(h);if(!w){l.set(h,s);continue}let u=we(w).toLowerCase();if(e.indexOf($)<e.indexOf(u))l.set(h,s)}return Array.from(l.entries()).map(([h,s])=>({base:h,file:s})).sort((h,s)=>h.base.localeCompare(s.base))}function r(){let f=n(),e=f.map((h)=>h.base),c=e.length?e.map((h)=>`'${h}'`).join(" | "):"string",l=f.length?`{
92
- ${f.map((h)=>{let s=cl(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${s}').default`}).join(`,
93
- `)}
94
- }`:"Record<string, any>";return`export type ConfigNames = ${c}
95
- export type ConfigByName = ${l}
96
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
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 E)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}`),l)console.error(l)}let $=`${e} ${this.environment}.${t.toUpperCase()}: ${s}
100
- `;if(l)$+=`${l}
101
- `;if($=$.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile($)}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,l=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
103
- `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":I.green("✓"),tag:s,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new br(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(!Er(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ll(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),l=Ky("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),s=l.final(),$=h.length+s.length,w=gt.allocUnsafe($);return h.copy(w,0),s.copy(w,h.length),w.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 l=f.split(`
104
- `),h=Math.max(...l.map((u)=>u.length))+2,s=`┌${"─".repeat(h)}┐`,$=`└${"─".repeat(h)}┘`,w=l.map((u)=>{return this.formatConsoleMessage({timestamp:n,message:I.cyan(u),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan(s),showTimestamp:!1})),w.forEach((u)=>console.error(u)),console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan($),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,l=0;if(n=t.replace(c,(h,s)=>{if(s==="%")return"%";if(l>=i.length)return h;let $=i[l++];switch(s){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return h}}),l<i.length)n+=` ${i.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).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)):"",l=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${l}${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)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),s=t.message?` ${t.message}`:"",$=this.options.showIcons===!1?"":i||n===100?I.green("✓"):I.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",u=`\r${$}${w} ${l} ${h}${s}`,y=M.stdout.columns||80,E=" ".repeat(Math.max(0,y-u.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${u}${E}`,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 Tr(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=Oi(this.config.logDirectory,r);if(t.before)try{if((await xi(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 Sr(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 v1=new br("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 ns 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 xr 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 rs 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 fs 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 ke 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 es 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 cs 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 Or 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 hs 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 ls 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 Vi={configNotFound(t,i,n){return new ns(t,i,n)},configLoad(t,i,n){return new xr(t,i,n)},configValidation(t,i,n){return new rs(t,i,n)},configMerge(t,i,n,r){return new fs(t,i,n,r)},envVar(t,i,n,r){return new ke(t,i,n,r)},fileSystem(t,i,n){return new es(t,i,n)},typeGeneration(t,i,n){return new cs(t,i,n)},schemaValidation(t,i,n){return new Or(t,i,n)},browserConfig(t,i,n,r){return new hs(t,i,n,r)},plugin(t,i,n){return new ls(t,i,n)}};async function ca(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise((s)=>setTimeout(s,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class oe{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:l=!1,trackPerformance:h=!0}=n,s=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let $=r||this.generateEnvPrefix(t),w={...i};return this.processObject(w,[],$,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return ze.track("applyEnvironmentVariables",s,{configName:t});return s()}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],l=c.map(($)=>this.formatEnvKey($,r.useCamelCase)),h=`${n}_${l.join("_")}`,s=r.useBackwardCompatibility?`${n}_${c.map(($)=>$.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let $=Rr.env[h]||(s?Rr.env[s]:void 0);if($!==void 0){if(r.verbose){let w=Rr.env[h]?h:s}try{t[f]=this.parseEnvironmentValue($,typeof e,h,r.customParsers,r.configName)}catch(w){if(w instanceof ke)throw w;throw Vi.envVar(h,$,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 Vi.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(Rr.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],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,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
-
109
- `;for(let r of t)n+=`${r.key}
110
- `,n+=` Type: ${r.type}
111
- `,n+=` Description: ${r.description}
112
- `,n+=` Example: ${r.example}
113
-
114
- `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
115
-
116
- `;n+=`| Variable | Type | Description | Example |
117
- `,n+=`|----------|------|-------------|----------|
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 Ts(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 Ve(t){let i=Yt.join(Aa.homedir(),".stacks","ssl"),n=t.basePath&&t.basePath.trim()!==""?t.basePath:o.basePath&&o.basePath.trim()!==""?o.basePath:i,r=t.certPath?Yt.isAbsolute(t.certPath)?t.certPath:Yt.join(n,t.certPath):Yt.join(n,o.certPath),f=t.keyPath?Yt.isAbsolute(t.keyPath)?t.keyPath:Yt.join(n,t.keyPath):Yt.join(n,o.keyPath),e=t.caCertPath?Yt.isAbsolute(t.caCertPath)?t.caCertPath:Yt.join(n,t.caCertPath):Yt.join(n,o.caCertPath);return{certPath:r,keyPath:f,caCertPath:e,basePath:n}}function Ss(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 N(F.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function ge(t){let i=t.notBeforeDays??Zt.DEFAULT_NOT_BEFORE_DAYS,n=t.validityDays??(t.validityYears?t.validityYears*365:Zt.DEFAULT_VALIDITY_DAYS);N(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),N(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},ut={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 wn(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=wn(i.length);return Buffer.concat([Buffer.from([t]),n,i])}function An(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 He(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 Rs(t,i=0){return Rt(Ht.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function Bs(t){return Rt(Ht.OCTET_STRING,t)}function St(...t){return Rt(Ht.SEQUENCE,Buffer.concat(t))}function Na(...t){return Rt(Ht.SET,Buffer.concat(t))}function Fa(t){return Rt(Ht.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function Ca(t){return Rt(Ht.UTF8_STRING,Buffer.from(t,"utf8"))}function Ja(){return Buffer.from([Ht.NULL,0])}function dl(t,i,n=!0){let r=160|t|(n?0:0),f=wn(i.length);return Buffer.concat([Buffer.from([r]),f,i])}function Wl(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"),l=t.getUTCSeconds().toString().padStart(2,"0"),h=`${n}${r}${f}${e}${c}${l}Z`;return Rt(Ht.UTC_TIME,Buffer.from(h,"ascii"))}}function _a(t,i){return St(Wl(t),Wl(i))}function Yl(t){let i=[];for(let n of t){let r;switch(n.shortName){case"CN":r=ut.COMMON_NAME;break;case"C":r=ut.COUNTRY;break;case"L":r=ut.LOCALITY;break;case"ST":r=ut.STATE;break;case"O":r=ut.ORGANIZATION;break;case"OU":r=ut.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?Fa(n.value):Ca(n.value),e=St(An(r),f);i.push(Na(e))}return St(...i)}function Ns(t){return St(An(t),Ja())}function Ua(t){return t.export({type:"spki",format:"der"})}function ja(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(":"):[],l=8-e.length-c.length,h=Array.from({length:l},()=>"0");i=[...e,...h,...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 da(t){let i=[];for(let n of t)if(n.type===2&&n.value){let r=wn(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=ja(n.ip),f=wn(r.length);i.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=wn(n.value.length);i.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return St(...i)}function Wa(t,i){if(t){if(i!==void 0)return St(Rt(1,Buffer.from([255])),He(i));return St(Rt(1,Buffer.from([255])))}return St()}function Ya(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 Rs(Buffer.from([i]),n)}function Ia(t){let i=[];if(t.serverAuth)i.push(An(ut.SERVER_AUTH));if(t.clientAuth)i.push(An(ut.CLIENT_AUTH));return St(...i)}function sn(t,i,n){let r=[An(t)];if(i)r.push(Rt(1,Buffer.from([255])));return r.push(Bs(n)),St(...r)}function Za(t){let i=[];if(i.push(dl(0,He(2))),i.push(He(t.serialNumber)),i.push(Ns(ut.SHA256_WITH_RSA)),i.push(Yl(t.issuer)),i.push(_a(t.notBefore,t.notAfter)),i.push(Yl(t.subject)),i.push(Ua(t.publicKey)),t.extensions){let n=[];if(t.extensions.basicConstraints)n.push(sn(ut.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,Wa(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)n.push(sn(ut.KEY_USAGE,t.extensions.keyUsage.critical??!0,Ya(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)n.push(sn(ut.EXTENDED_KEY_USAGE,!1,Ia(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)n.push(sn(ut.SUBJECT_ALT_NAME,!1,da(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)n.push(sn(ut.SUBJECT_KEY_IDENTIFIER,!1,Bs(t.extensions.subjectKeyIdentifier)));if(n.length>0)i.push(dl(3,St(...n)))}return St(...i)}function Ha(t,i){let n=gi.createSign("SHA256");n.update(t);let r=n.sign(i);return St(t,Ns(ut.SHA256_WITH_RSA),Rs(r))}function Ma(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
- ${r.join(`
122
- `)}
123
- -----END ${i}-----
124
- `}function be(){return gi.randomBytes(20)}function Fs(t=2048){let{privateKey:i,publicKey:n}=gi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:n}}function za(t){let i=t.export({type:"spki",format:"der"});return gi.createHash("sha1").update(i).digest()}function Cs(t){let i={serialNumber:t.serialNumber||be(),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:za(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=Za(i),r=Ha(n,t.signingKey);return{certificate:Ma(r,"CERTIFICATE"),certificateDer:r}}function Js(t){return t.export({type:"pkcs8",format:"pem"})}function Ga(t){return gi.createPrivateKey(t)}function Ka(t){let i=new gi.X509Certificate(t),n=i.publicKey,r=[],f=i.subject.split(`
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
126
- echo "Trusting RPX Root CA"
127
- sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${f.caCertPath}"
128
- echo "Root CA trusted! Please restart your browser."
129
- echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
130
- `;await V.writeFile($,w,{mode:493})}catch($){if(t.verbose)S.warn(`Could not add Root CA to trust store automatically: ${$}`);let w=at(r,"trust-rpx-cert.sh"),u=`#!/bin/bash
131
- echo "Trusting RPX Root CA"
132
- sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${f.caCertPath}"
133
- echo "Root CA trusted! Please restart your browser."
134
- echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
135
- `;if(await V.writeFile(w,u,{mode:493}),t.verbose)S.info(`Created a trust helper script at: ${w}`),S.info(`If you're still having certificate issues, run: sh ${w}`)}else if(zt.platform==="linux")try{let{exec:$}=await import("node:child_process"),w="/usr/local/share/ca-certificates/rpx",u=`
136
- mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
137
- cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
138
- update-ca-certificates
139
- echo "RPX Root CA installed. Please restart your browser."
140
- `,y=at(pe.tmpdir(),`rpx-trust-${Date.now()}.sh`);await V.writeFile(y,u,{mode:493}),await new Promise((E)=>{$(`sudo bash "${y}"`,(A)=>{if(A){if(t.verbose)S.warn(`Could not trust certificates: ${A}`);E(!1)}else{if(t.verbose)S.success("Successfully added certificates to system trust store");E(!0)}})}),await V.unlink(y).catch(()=>{}),s=!0}catch($){if(t.verbose)S.warn(`Failed to trust certificates: ${$}`)}else if(zt.platform==="win32")try{let $=`
141
- $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
142
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
143
- $store.Open("ReadWrite")
144
- $store.Add($cert)
145
- $store.Close()
146
- 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 pi(t);if(n!==null&&ni(n))throw Error(`rpx daemon already running (pid=${n})`);await Gt.unlink(i).catch(()=>{})}}async function vi(t=ri()){await Gt.unlink(rf(t)).catch(()=>{})}function e0(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}}async function c0(t){let i={https:t.https??!0,to:"rpx.localhost",verbose:t.verbose,regenerateUntrustedCerts:!0},n=await ti(i);if(!n)a("daemon","no usable cert on disk, generating one",t.verbose),await bi(i),n=await ti(i);if(!n)throw Error("failed to bootstrap TLS for rpx daemon");return n}async function h0(t={}){let i=t.verbose??!1,n=t.rpxDir??ri(),r=t.registryDir??Qi.join(n,"registry.d"),f=t.httpsPort??443,e=t.httpPort??80,c=t.hostname??"0.0.0.0",l=t.gcIntervalMs??r0,h=await Gs(n),s=new Map,$=(B)=>s.get(B);function w(B){let lt=new Map;for(let mt of B)lt.set(mt.to,e0(mt));s=lt,a("daemon",`routing table now covers ${lt.size} host(s): ${Array.from(lt.keys()).join(", ")||"<empty>"}`,i)}await nf(r,i).catch((B)=>{a("daemon",`initial gc failed: ${B}`,i)}),w(await Xi(r,i));let u=await c0(t),y=Bun.serve({port:f,hostname:c,tls:{key:u.key,cert:u.cert,ca:u.ca,requestCert:!1,rejectUnauthorized:!1},fetch:En($,i),error(B){return a("daemon",`https server error: ${B}`,i),new Response(`Server Error: ${B.message}`,{status:500})}}),E=null;if(e>0)E=Bun.serve({port:e,hostname:c,fetch(B){let lt=new URL(B.url),mt=(B.headers.get("host")??lt.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${mt}${lt.pathname}${lt.search}`}})}});if(i)S.success(`rpx daemon listening on https://${c}:${f}${E?` (http→https on :${e})`:""}`),S.info(`pid file: ${h}`),S.info(`registry: ${r}`);let A=cc((B)=>{w(B)},{dir:r,verbose:i}),T=setInterval(()=>{nf(r,i).then((B)=>{if(B>0)a("daemon",`gc reaped ${B} stale entries`,i)}).catch((B)=>{a("daemon",`periodic gc failed: ${B}`,i)})},l);if(typeof T.unref==="function")T.unref();let m=!1,R,C=new Promise((B)=>{R=B});async function J(){if(m)return C;if(m=!0,clearInterval(T),A.close(),y.stop(!1),E?.stop(!1),await vi(n),i)S.info("rpx daemon stopped");return R(),C}let j=(B)=>{a("daemon",`received ${B}, shutting down`,i),J().catch(()=>{})};return it.once("SIGINT",j),it.once("SIGTERM",j),{stop:J,done:C,httpsPort:typeof y.port==="number"?y.port:f,httpPort:E&&typeof E.port==="number"?E.port:e,pidPath:h}}function Ks(){let t=it.execPath,i=Qi.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&it.argv[1])return[t,it.argv[1],"daemon:start"];return[t,"daemon:start"]}async function hc(t={}){let i=t.rpxDir??ri(),n=t.verbose??!1,r=await pi(i);if(r!==null&&ni(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 vi(i);await Gt.mkdir(i,{recursive:!0});let f=t.spawnCommand??Ks();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,n);let e=i0(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??it.cwd(),env:t.spawnEnv?{...it.env,...t.spawnEnv}:it.env});e.unref();let c=null;e.once("error",($)=>{c=$});let l=t.startupTimeoutMs??5000,h=t.pollIntervalMs??50,s=Date.now()+l;while(Date.now()<s){if(c)throw c;let $=await pi(i);if($!==null&&ni($))return a("daemon",`daemon registered with pid=${$}`,n),{pid:$,spawned:!0};await new Promise((w)=>setTimeout(w,h))}if(c)throw c;throw Error(`rpx daemon failed to start within ${l}ms (rpxDir=${i})`)}async function l0(t={}){let i=t.rpxDir??ri(),n=t.verbose??!1,r=t.timeoutMs??5000,f=t.pollIntervalMs??50,e=t.forceAfterTimeout??!0,c=await pi(i);if(c===null||!ni(c)){if(c!==null)await vi(i);return{stopped:!1,pid:c,forced:!1}}try{it.kill(c,"SIGTERM")}catch(h){if(h.code==="ESRCH")return await vi(i),{stopped:!1,pid:c,forced:!1};throw h}let l=Date.now()+r;while(Date.now()<l){if(!ni(c))return a("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((h)=>setTimeout(h,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{it.kill(c,"SIGKILL")}catch(h){if(h.code!=="ESRCH")throw h}return await vi(i),{stopped:!0,pid:c,forced:!0}}function xs(t){let i=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function ff(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((w)=>{let u=w.id??xs(w.to);if(!Pi(u))throw Error(`invalid registry id "${u}" derived from to="${w.to}"`);if(r.has(u))throw Error(`duplicate registry id "${u}" — set an explicit \`id\` on one of the proxies`);return r.add(u),{...w,id:u}});for(let w of f)await ec({id:w.id,from:w.from,to:w.to,pid:Kt.pid,cwd:Kt.cwd(),createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites},n,i);let e=await hc({rpxDir:t.rpxDir,verbose:i,spawnCommand:t.spawnCommand});for(let w of f)S.success(`https://${w.to} → ${w.from}`);if(S.info(`(via rpx daemon pid=${e.pid}; \`rpx daemon:status\` to inspect)`),t.detached)return;let c=!1,l=n??ii(),h=f.map((w)=>w.id),s=async()=>{if(c)return;c=!0;for(let w of h)await tf(w,n,i).catch((u)=>{a("runner",`removeEntry(${w}) failed: ${u}`,i)})},$=(w)=>{a("runner",`received ${w}, unregistering ${h.length} entries`,i),s().finally(()=>Kt.exit(0))};Kt.once("SIGINT",$),Kt.once("SIGTERM",$),Kt.once("exit",()=>{if(c)return;for(let w of h)try{qs.unlinkSync(Ds.join(l,`${w}.json`))}catch{}}),await new Promise(()=>{})}import{exec as s0}from"node:child_process";import mi from"node:fs";import Os from"node:os";import sc from"node:path";import*as Sn from"node:process";import{promisify as $0}from"node:util";var ef=$0(s0),Ut=Sn.platform==="win32"?sc.join(Sn.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",lc=!1;async function cf(t){if(Sn.platform==="win32")throw Error("Administrator privileges required on Windows");let i=Tn(),n=t.replace(/'/g,"'\\''");try{if(i){let{stdout:f}=await ef(`echo '${i}' | sudo -S sh -c '${n}' 2>/dev/null`);return lc=!0,f}if(lc)try{let{stdout:f}=await ef(`sudo -n sh -c '${n}'`);return f}catch(f){a("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:r}=await ef(`sudo sh -c '${n}'`);return lc=!0,r}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}async function tn(t,i){a("hosts",`Adding hosts: ${t.join(", ")}`,i),a("hosts",`Using hosts file at: ${Ut}`,i);try{let n;try{n=await mi.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await cf(`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 l=`127.0.0.1 ${c}`,h=`::1 ${c}`;return!n.includes(l)&&!n.includes(h)});if(r.length===0){a("hosts","All hosts already exist in hosts file",i);return}let f=r.map((c)=>`
1
+ import{$ as PD,A as E_,B as AD,C as M_,D as Y_,E as $_,F as VD,G as G_,H as W_,I as RD,J as zD,K as ED,L as MD,M as SD,N as FD,O as TD,P as ID,Q as wD,R as HD,S as jD,T as kD,U as CD,V as qD,W as xD,X as UD,Y as fD,Z as yD,_ as OD,a as X,aa as LD,b as B_,ba as hD,c as g_,ca as cD,d as i_,da as uD,e as n_,ea as mD,f as t_,fa as vD,g as r_,ga as bD,h as s_,ha as lD,i as o_,ia as aD,j as e_,ja as dD,k as _D,ka as pD,l as DD,la as gD,m as BD,ma as X_,n as KD,na as iD,o as ND,oa as nD,p as YD,q as $D,r as GD,s as WD,t as XD,u as JD,v as QD,w as K_,x as ZD,y as c,z as N_}from"./chunk-ppbddztz.js";import{Aa as KB,Ba as NB,Ca as YB,Da as $B,pa as z_,qa as m,ra as r2,sa as K,ta as s2,ua as C,va as o2,wa as e2,xa as _B,ya as DB,za as BB}from"./chunk-97manwts.js";import{execSync as m_}from"node:child_process";import*as O from"node:http";import*as f_ from"node:http2";import*as y_ from"node:net";import*as F from"node:process";var n=(D,_)=>(B)=>`\x1B[${D}m${B}\x1B[${_}m`,j={bold:n(1,22),dim:n(2,22),green:n(32,39),cyan:n(36,39)};import*as H_ from"node:fs";import*as j_ from"node:path";import*as k from"node:process";function k_(D){let _=D.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return _.length>0?_:"rpx"}async function t(D){if(D.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let _=D.verbose??!1,B=D.registryDir,N=new Set,Y=D.proxies.map((R)=>{let G=R.id??k_(R.to);if(!$_(G))throw Error(`invalid registry id "${G}" derived from to="${R.to}"`);if(N.has(G))throw Error(`duplicate registry id "${G}" — set an explicit \`id\` on one of the proxies`);return N.add(G),{...R,id:G}}),W=new Date().toISOString();for(let R of Y)await G_({id:R.id,from:R.from,to:R.to,pid:D.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:W,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites},B,_);let $=await X_({rpxDir:D.rpxDir,verbose:_,spawnCommand:D.spawnCommand,startupTimeoutMs:D.startupTimeoutMs,spawnEnv:D.spawnEnv});for(let R of Y)X.success(`https://${R.to} → ${R.from}`);if(X.info(`(via rpx daemon pid=${$.pid}; \`rpx daemon:status\` to inspect)`),D.detached)return;let V=!1,J=B??Y_(),A=Y.map((R)=>R.id),T=async()=>{if(V)return;V=!0;for(let R of A)await W_(R,B,_).catch((G)=>{K("runner",`removeEntry(${R}) failed: ${G}`,_)})},I=(R)=>{K("runner",`received ${R}, unregistering ${A.length} entries`,_),T().finally(()=>k.exit(0))};k.once("SIGINT",I),k.once("SIGTERM",I),k.once("exit",()=>{if(V)return;for(let R of A)try{H_.unlinkSync(j_.join(J,`${R}.json`))}catch{}}),await new Promise(()=>{})}import{exec as L_}from"node:child_process";import f from"node:fs";import C_ from"node:os";import Q_ from"node:path";import*as v from"node:process";import{promisify as h_}from"node:util";var r=h_(L_),H=v.platform==="win32"?Q_.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",J_=!1;async function s(D){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");let _=m(),B=D.replace(/'/g,"'\\''");try{if(_){let{stdout:Y}=await r(`echo '${_}' | sudo -S sh -c '${B}' 2>/dev/null`);return J_=!0,Y}if(J_)try{let{stdout:Y}=await r(`sudo -n sh -c '${B}'`);return Y}catch(Y){K("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:N}=await r(`sudo sh -c '${B}'`);return J_=!0,N}catch(N){throw Error(`Failed to execute sudo command: ${N.message}`)}}async function L(D,_){K("hosts",`Adding hosts: ${D.join(", ")}`,_),K("hosts",`Using hosts file at: ${H}`,_);try{let B;try{B=await f.promises.readFile(H,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{B=await s(`cat "${H}"`)}catch($){throw console.log(" Could not read hosts file — skipping hosts setup"),K("hosts",`sudo read also failed: ${$}`,_),Error(`Cannot read hosts file: ${$}`)}}let N=D.filter(($)=>{let V=`127.0.0.1 ${$}`,J=`::1 ${$}`;return!B.includes(V)&&!B.includes(J)});if(N.length===0){K("hosts","All hosts already exist in hosts file",_);return}let Y=N.map(($)=>`
149
2
  # Added by rpx
150
- 127.0.0.1 ${c}
151
- ::1 ${c}`).join(`
152
- `),e=sc.join(Os.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await mi.promises.writeFile(e,n+f,"utf8"),await cf(`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((l)=>{console.log(` 127.0.0.1 ${l}`),console.log(` ::1 ${l}`)}),console.log(` Or run: sudo nano ${Ut}`)}finally{try{await mi.promises.unlink(e)}catch{}}}catch(n){a("hosts",`Failed to manage hosts file: ${n.message}`,i)}}async function $c(t,i){a("hosts",`Removing hosts: ${t.join(", ")}`,i);try{let n;try{n=await mi.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await cf(`cat "${Ut}"`)}catch(h){throw a("hosts",`sudo read also failed: ${h}`,i),Error(`Cannot read hosts file: ${h}`)}}let r=n.split(`
153
- `),f=!1,e=r.filter((h)=>{if(t.some(($)=>h.includes(` ${$}`)&&(h.includes("127.0.0.1")||h.includes("::1"))))return f=!0,!1;if(h.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(`
3
+ 127.0.0.1 ${$}
4
+ ::1 ${$}`).join(`
5
+ `),W=Q_.join(C_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(W,B+Y,"utf8"),await s(`cat "${W}" | tee "${H}" > /dev/null`),console.log(` Hosts updated: ${N.join(", ")}`)}catch($){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),N.forEach((V)=>{console.log(` 127.0.0.1 ${V}`),console.log(` ::1 ${V}`)}),console.log(` Or run: sudo nano ${H}`)}finally{try{await f.promises.unlink(W)}catch{}}}catch(B){K("hosts",`Failed to manage hosts file: ${B.message}`,_)}}async function Z_(D,_){K("hosts",`Removing hosts: ${D.join(", ")}`,_);try{let B;try{B=await f.promises.readFile(H,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{B=await s(`cat "${H}"`)}catch(J){throw K("hosts",`sudo read also failed: ${J}`,_),Error(`Cannot read hosts file: ${J}`)}}let N=B.split(`
6
+ `),Y=!1,W=N.filter((J)=>{if(D.some((T)=>J.includes(` ${T}`)&&(J.includes("127.0.0.1")||J.includes("::1"))))return Y=!0,!1;if(J.trim()==="# Added by rpx")return Y=!0,!1;return!0});if(!Y){K("hosts","No matching hosts found to remove",_);return}while(W[W.length-1]?.trim()==="")W.pop();let $=`${W.join(`
154
7
  `)}
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};
8
+ `,V=Q_.join(C_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(V,$,"utf8"),await s(`cat "${V}" | tee "${H}" > /dev/null`),K("hosts","Hosts removed successfully",_)}catch(J){K("hosts","Could not clean up hosts file automatically",_)}finally{try{await f.promises.unlink(V)}catch(J){K("hosts",`Failed to remove temporary file: ${J}`,_)}}}catch(B){K("hosts",`Failed to clean up hosts file: ${B.message}`,_)}}async function h(D,_){K("hosts",`Checking hosts: ${D}`,_);let B;try{B=await f.promises.readFile(H,"utf-8")}catch(N){K("hosts",`Error reading hosts file: ${N}`,_);try{let Y=m(),W;if(Y)W=`echo '${Y}' | sudo -S cat "${H}" 2>/dev/null`;else W=`sudo -n cat "${H}" 2>/dev/null || cat "${H}" 2>/dev/null || echo ""`;let{stdout:$}=await r(W);B=$}catch(Y){return K("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,_),D.map(()=>!1)}}return D.map((N)=>{let Y=`127.0.0.1 ${N}`,W=`::1 ${N}`;return B.includes(Y)||B.includes(W)})}import*as o from"node:net";function x(D,_,B){return K("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((N)=>{let Y=o.createServer(),W=setTimeout(()=>{K("port",`Checking port ${D} timed out, assuming it's in use`,B),Y.close(),N(!0)},3000);Y.once("error",($)=>{if(clearTimeout(W),$.code==="EADDRINUSE")K("port",`Port ${D} is in use`,B),N(!0);else K("port",`Error checking port ${D}: ${$.message}`,B),N(!0)}),Y.once("listening",()=>{clearTimeout(W),K("port",`Port ${D} is available`,B),Y.close(),N(!1)});try{Y.listen(D,_)}catch($){clearTimeout(W),K("port",`Exception checking port ${D}: ${$}`,B),N(!0)}})}async function x_(D,_,B,N=50){K("port",`Finding available port starting from ${D} (max attempts: ${N})`,B);let Y=D,W=0;while(W<N){if(W++,!await x(Y,_,B))return K("port",`Found available port: ${Y} after ${W} attempts`,B),Y;K("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${W}/${N})`,B),Y++}throw Error(`Unable to find available port after ${N} attempts starting from ${D}`)}function q_(D,_,B=5000,N){return K("port",`Testing connection to ${_}:${D}`,N),new Promise((Y)=>{let W=o.connect({host:_,port:D,timeout:B});W.once("connect",()=>{K("port",`Successfully connected to ${_}:${D}`,N),W.end(),Y(!0)}),W.once("timeout",()=>{K("port",`Connection to ${_}:${D} timed out`,N),W.destroy(),Y(!1)}),W.once("error",($)=>{K("port",`Failed to connect to ${_}:${D}: ${$.message}`,N),W.destroy(),Y(!1)})})}class b{usedPorts=new Set;hostname;verbose;maxRetries;constructor(D="0.0.0.0",_,B=50){this.hostname=D,this.verbose=_,this.maxRetries=B}async getNextAvailablePort(D,_=!1){if(this.usedPorts.has(D))return this.findNextAvailablePort(D+1,_);if(await x(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await q_(D,this.hostname,3000,this.verbose))return K("port",`Port ${D} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(D+1,_)}return this.usedPorts.add(D),D}async findNextAvailablePort(D,_=!1){let B=await x_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await q_(B,this.hostname,3000,this.verbose))if(B<D+this.maxRetries)return this.findNextAvailablePort(B+1,_);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(B),B}releasePort(D){K("port",`Releasing port ${D}`,this.verbose),this.usedPorts.delete(D)}}var c_=new b;import{spawn as u_}from"node:child_process";import*as y from"node:process";class e{processes=new Map;isShuttingDown=!1;async startProcess(D,_,B){if(this.processes.has(D)){K("start",`Process ${D} is already running`,B);return}let[N,...Y]=_.command.split(" "),W=_.cwd||y.cwd();K("start",`Starting process ${D}:`,B),K("start",` Command: ${N} ${Y.join(" ")}`,B),K("start",` Working directory: ${W}`,B),K("start",` Environment variables: ${C(_.env)}`,B);let $=u_(N,Y,{cwd:W,env:{...y.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:W,process:$,env:_.env}),new Promise((V,J)=>{if($.on("error",(A)=>{if(!this.isShuttingDown)K("start",`Process ${D} failed to start: ${A}`,B),this.processes.delete(D),J(A),y.emit("SIGINT")}),$.on("exit",(A)=>{if(!this.isShuttingDown&&A!==null&&A!==0)K("start",`Process ${D} exited with code ${A}`,B),this.processes.delete(D),J(Error(`Process ${D} exited with code ${A}`)),y.emit("SIGINT")}),B)$.stdout?.on("data",(A)=>{K("process",`[${D}] ${A.toString().trim()}`,!0)}),$.stderr?.on("data",(A)=>{K("process",`[${D}] ERR: ${A.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&$.killed)this.processes.delete(D),J(Error(`Process ${D} was killed during startup`));else K("start",`Process ${D} started successfully`,B),V()},1000)})}async stopProcess(D,_){let B=this.processes.get(D);if(!B?.process){K("start",`No process found for ${D}`,_);return}return K("start",`Stopping process ${D}`,_),new Promise((N)=>{if(!B.process){N();return}B.process.once("exit",()=>{this.processes.delete(D),K("start",`Process ${D} stopped`,_),N()});try{B.process.kill("SIGTERM"),setTimeout(()=>{if(B.process){K("start",`Force killing process ${D}`,_);try{B.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){K("start",`Error stopping process ${D}: ${Y}`,_),this.processes.delete(D),N()}})}async stopAll(D){if(this.isShuttingDown){K("start","Already shutting down, skipping duplicate stopAll call",D);return}this.isShuttingDown=!0,K("start","Stopping all processes",D);let _=Array.from(this.processes.keys()).map((B)=>this.stopProcess(B,D).catch((N)=>{X.error(`Failed to stop process ${B}:`,N)}));await Promise.allSettled(_),this.processes.clear(),this.isShuttingDown=!1}isRunning(D){let _=this.processes.get(D);return!!_?.process&&!_.process.killed}}var A2=new e;var D_=new e,v_="0.12.0",b_=new b("0.0.0.0"),l=new Set,A_=!1,__=null,V_=null;async function d(D){if(A_)return K("cleanup","Cleanup already in progress, skipping",D?.verbose),V_||Promise.resolve();A_=!0,K("cleanup","Starting cleanup process",D?.verbose),V_=new Promise((_)=>{__=_});try{await D_.stopAll(D?.verbose),X.info("Shutting down proxy servers...");let _=[],B=Array.from(l).map((N)=>new Promise((Y)=>{N.close(()=>{K("cleanup","Server closed successfully",D?.verbose),Y()})}));if(_.push(...B),D?.hosts&&D.domains?.length){K("cleanup","Cleaning up hosts file entries",D?.verbose),K("cleanup",`Original domains for cleanup: ${JSON.stringify(D.domains)}`,D?.verbose);let N=D.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(K("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,D?.verbose),N.length>0)X.info("Cleaning up hosts file entries..."),_.push(Z_(N,D?.verbose).then(()=>{K("cleanup",`Removed hosts entries for ${N.join(", ")}`,D?.verbose)}).catch((Y)=>{K("cleanup",`Failed to remove hosts entries: ${Y}`,D?.verbose),X.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,Y)}))}if(D?.certs&&D.domains?.length){K("cleanup","Cleaning up SSL certificates",D?.verbose),X.info("Cleaning up SSL certificates...");let N=D.domains.map(async(Y)=>{try{await E_(Y,D?.verbose),K("cleanup",`Removed certificates for ${Y}`,D?.verbose)}catch(W){K("cleanup",`Failed to remove certificates for ${Y}: ${W}`,D?.verbose),X.warn(`Failed to clean up certificates for ${Y}:`,W)}});_.push(...N)}await Promise.allSettled(_),K("cleanup","All cleanup tasks completed successfully",D?.verbose),X.success("All cleanup tasks completed successfully")}catch(_){K("cleanup",`Error during cleanup: ${_}`,D?.verbose),X.error("Error during cleanup:",_)}finally{if(__)__();__=null,A_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(F.env.NODE_ENV!=="test"&&F.env.BUN_ENV!=="test"&&!_)F.exit(0)}return V_}var R_=!1;function S_(D){if(R_){K("signal",`Received second ${D} signal, forcing exit`,!0),F.exit(1);return}R_=!0,K("signal",`Received ${D} signal, initiating cleanup`,!0),d().catch((_)=>{K("signal",`Cleanup failed after ${D}: ${_}`,!0),F.exit(1)}).finally(()=>{R_=!1})}F.once("SIGINT",()=>S_("SIGINT"));F.once("SIGTERM",()=>S_("SIGTERM"));F.on("uncaughtException",(D)=>{K("process",`Uncaught exception: ${D}`,!0),X.error("Uncaught exception:",D),S_("uncaughtException")});async function a(D,_,B,N=5){K("connection",`Testing connection to ${D}:${_} (retries left: ${N})`,B);let Y=15000,W=Date.now();if(F.env.RPX_BYPASS_CONNECTION_TEST==="true"){K("connection",`Bypassing connection test for ${D}:${_} due to RPX_BYPASS_CONNECTION_TEST flag`,B);return}let $=()=>new Promise((V,J)=>{let A=y_.connect({host:D,port:_,timeout:3000});A.once("connect",()=>{K("connection",`Successfully connected to ${D}:${_}`,B),A.end(),V()}),A.once("timeout",()=>{K("connection",`Connection to ${D}:${_} timed out`,B),A.destroy(),J(Error("Connection timed out"))}),A.once("error",(T)=>{K("connection",`Failed to connect to ${D}:${_}: ${T}`,B),A.destroy(),J(T)})});try{await $()}catch(V){if(Date.now()-W>Y){K("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,B),X.warn(`Connection test to ${D}:${_} timed out, but RPX will try to proceed anyway.`);return}if(V.code==="ECONNREFUSED"&&N>0)return K("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,B),await new Promise((A)=>setTimeout(A,2000)),a(D,_,B,N-1);if(N>0)try{K("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((A,T)=>{let I=O.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(R)=>{K("connection",`Received HTTP response with status: ${R.statusCode}`,B),A()});I.on("error",(R)=>T(R)),I.on("timeout",()=>{I.destroy(),T(Error("HTTP request timed out"))}),I.end()}),K("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(A){return K("connection",`HTTP request to ${D}:${_} failed: ${A}`,B),K("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,B),await new Promise((T)=>setTimeout(T,2000)),a(D,_,B,N-1)}let J=`Failed to connect to ${D}:${_} after ${5-N} attempts: ${V.message}`;K("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,B),X.warn(J),X.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 F_(D){K("server",`Starting server with options: ${C(D)}`,D.verbose);let _=new URL((D.from?.startsWith("http")?D.from:`http://${D.from}`)||"localhost:5173"),B=new URL((D.to?.startsWith("http")?D.to:`http://${D.to}`)||"rpx.localhost"),N=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),Y=[B.hostname];if(!B.hostname.includes("localhost")&&!B.hostname.includes("127.0.0.1")){K("hosts",`Checking if hosts file entry exists for: ${B.hostname}`,D?.verbose);try{if(!(await h(Y,D.verbose))[0]){X.info(`Adding ${B.hostname} to hosts file...`),X.info("This may require sudo/administrator privileges");try{await L(Y,D.verbose)}catch(V){if(X.error("Failed to add hosts entry:",V.message),X.warn("You can manually add this entry to your hosts file:"),X.warn(`127.0.0.1 ${B.hostname}`),X.warn(`::1 ${B.hostname}`),F.platform==="win32")X.warn("On Windows:"),X.warn("1. Run notepad as administrator"),X.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else X.warn("On Unix systems:"),X.warn("sudo nano /etc/hosts")}}else K("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch($){X.error("Failed to check hosts file:",$.message)}}try{await a(_.hostname,N,D.verbose)}catch($){K("server",`Connection test failed: ${$}`,D.verbose),X.error($.message),X.warn("Continuing with proxy setup despite connection test failure..."),X.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let W=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=N_({...D,to:B.hostname});if(W=await c({...D,to:B.hostname,https:D.https}),!W){if(K("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await K_({...D,from:_.toString(),to:B.hostname,https:D.https}),W=await c({...D,to:B.hostname,https:D.https}),!W)throw Error(`Failed to load SSL configuration after generating certificates for ${B.hostname}`)}}catch($){throw K("server",`SSL setup failed: ${$}`,D.verbose),$}K("server",`Setting up reverse proxy with SSL config for ${B.hostname}`,D.verbose),await a_({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:N,sourceUrl:{hostname:_.hostname,host:_.host},ssl:W})}async function l_(D,_,B,N,Y,W,$,V,J,A,T){K("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${A}`,J);function I(Z){let E={};for(let[Q,z]of Object.entries(Z))if(!Q.startsWith(":"))E[Q]=z;return E}let R=(Z,E)=>{K("request",`Incoming request: ${Z.method} ${Z.url}`,J);let Q=Z.url||"/",z=Z.method||"GET";if(Z instanceof f_.Http2ServerRequest){let S=Z.headers;z=S[":method"]||z,Q=S[":path"]||Q}if(A){if(!Q.match(/\.[a-z0-9]+$/i))if(Q.endsWith("/"))Q=`${Q}index.html`;else Q=`${Q}.html`}let w=I(Z.headers);if(T)w.host=`${W.hostname}:${B}`,K("request",`Changed origin: setting host header to ${w.host}`,J);let U={hostname:W.hostname,port:B,path:Q,method:z,headers:w};K("request",`Proxy request options: ${C(U)}`,J);let p=O.request(U,(S)=>{if(K("response",`Proxy response received with status ${S.statusCode}`,J),A&&S.statusCode===404){let q=[];if(Q.endsWith(".html"))q.push(Q.slice(0,-5));else if(!Q.match(/\.[a-z0-9]+$/i))q.push(`${Q}.html`);if(!Q.endsWith("/"))q.push(`${Q}/index.html`);if(q.length>0){K("cleanUrls",`Trying alternative paths: ${q.join(", ")}`,J);let u=(g)=>{if(g.length===0){E.writeHead(S.statusCode||404,S.headers),S.pipe(E);return}let I_=g[0],P_={...U,path:I_},w_=O.request(P_,(i)=>{if(i.statusCode===200)K("cleanUrls",`Found matching path: ${I_}`,J),E.writeHead(i.statusCode,i.headers),i.pipe(E);else u(g.slice(1))});w_.on("error",()=>u(g.slice(1))),w_.end()};u(q);return}}let P={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};E.writeHead(S.statusCode||500,P),S.pipe(E)});p.on("error",(S)=>{K("request",`Proxy request failed: ${S}`,J),X.error("Proxy request failed:",S),E.writeHead(502),E.end(`Proxy Error: ${S.message}`)}),Z.pipe(p)};if(K("server",`Creating server with SSL config: ${!!$}`,J),$)return new Promise((Z,E)=>{try{let Q=Bun.serve({port:N,hostname:Y,tls:{key:$.key,cert:$.cert,ca:$.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(z){let w=new URL(z.url);K("request",`Bun.serve received: ${z.method} ${w.pathname}`,J);let U=`http://${W.host}`,p=new URL(w.pathname+w.search,U);try{let S=new Headers(z.headers);if(S.set("host",W.host),T)S.set("origin",U);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",_);let P=await fetch(p.toString(),{method:z.method,headers:S,body:z.body,redirect:"manual"}),q=new Headers(P.headers);if(A&&w.pathname.endsWith(".html")){let u=w.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:u}})}return new Response(P.body,{status:P.status,statusText:P.statusText,headers:q})}catch(S){return K("request",`Proxy error: ${S}`,J),new Response(`Proxy Error: ${S}`,{status:502})}},error(z){return K("server",`Bun.serve error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});l.add(Q),U_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!0,cleanUrls:A,verbose:J}),Z()}catch(Q){E(Q)}});let G=O.createServer(R);function M(Z){return l.add(Z),new Promise((E,Q)=>{Z.listen(N,Y,()=>{K("server",`Server listening on port ${N}`,J),U_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!!$,cleanUrls:A,verbose:J}),E()}),Z.on("error",(z)=>{K("server",`Server error: ${z}`,J),Q(z)})})}return M(G)}async function a_(D){K("setup",`Setting up reverse proxy: ${C(D)}`,D.verbose);let{from:_,to:B,fromPort:N,sourceUrl:Y,ssl:W,verbose:$,cleanup:V,vitePluginUsage:J,changeOrigin:A,cleanUrls:T}=D,I=80,R=443,G="0.0.0.0",M=D.portManager||b_;try{if(B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await h([B],$))[0]){X.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await L([B],$),X.success(`Added ${B} to your hosts file.`)}catch(w){X.error(`Failed to add ${B} to your hosts file: ${w}`),X.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(F.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await h([B],$))[0]){K("hosts",`${B} not found in hosts file, adding...`,$);try{await L([B],$)}catch(w){K("hosts",`Failed to add ${B} to hosts file: ${w}`,$)}}}if(W&&!M.usedPorts.has(I)){if(!await x(I,G,$))K("setup","Starting HTTP redirect server",$),O_($),M.usedPorts.add(I);else if(K("setup","Port 80 is in use, skipping HTTP redirect",$),$)X.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Z=W?R:I,E=await x(Z,G,$),Q;if(E){if(K("setup",`Port ${Z} is already in use`,$),$)X.warn(`Port ${Z} is already in use. This may be another instance of rpx or another service.`);if(Z===443){if(Q=await M.getNextAvailablePort(3443,!0),K("setup",`Using port ${Q} instead of ${Z}`,$),$)X.info(`Using port ${Q} instead. Access your site at https://${B}:${Q}`)}else if(Q=await M.getNextAvailablePort(Z+1000,!0),K("setup",`Using port ${Q} instead of ${Z}`,$),$)X.info(`Using port ${Q} instead. Access your site at http://${B}:${Q}`)}else Q=Z,M.usedPorts.add(Q),K("setup",`Using standard ${Z===443?"HTTPS":"HTTP"} port ${Z} for ${B}`,$);await l_(_,B,N,Q,G,Y,W,J,$,T,A)}catch(Z){K("setup",`Setup failed: ${Z}`,$),X.error(`Failed to setup reverse proxy: ${Z.message}`),d({domains:[B],hosts:typeof V==="boolean"?V:V?.hosts,certs:typeof V==="boolean"?V:V?.certs,verbose:$,vitePluginUsage:J})}}function O_(D){K("redirect","Starting HTTP redirect server",D);let _=O.createServer((B,N)=>{let Y=B.headers.host||"";K("redirect",`Redirecting request from ${Y}${B.url} to HTTPS`,D),N.writeHead(301,{Location:`https://${Y}${B.url}`}),N.end()}).listen(80);l.add(_),K("redirect","HTTP redirect server started",D)}function d_(D){let _={...B_,...D};if(K("proxy",`Starting proxy with options: ${C(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){X.error("viaDaemon mode requires both `from` and `to`");return}t({proxies:[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}],verbose:_.verbose}).catch((J)=>{X.error(`Failed to register with rpx daemon: ${J.message}`),F.exit(1)});return}let B=_.to||"",N=B.split(".").pop()?.toLowerCase()||"",Y=F.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),W=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"];if(Y&&W.includes(N)&&_?.verbose)X.warn(`The .${N} TLD may not work reliably for local development`),X.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),X.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-krj531r2.js").then(({setupDevelopmentDns:J})=>{J({domains:[B],verbose:_.verbose}).then((A)=>{if(A)Promise.resolve().then(()=>{if(_.verbose)if($.includes(N))X.success(`DNS server started for .${N} domains`);else X.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else K("dns",`Could not start DNS server - ${B} may not resolve in browser`,_.verbose)})}).catch((J)=>{K("dns",`Failed to start DNS server: ${J}`,_.verbose)});let V={from:_.from,to:_.to,cleanUrls:_.cleanUrls,https:N_(_),cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,changeOrigin:_.changeOrigin,verbose:_.verbose,regenerateUntrustedCerts:_.regenerateUntrustedCerts};K("proxy",`Server options: ${C(V)}`,_.verbose),F_(V).catch((J)=>{K("proxy",`Failed to start proxy: ${J}`,_.verbose),X.error(`Failed to start proxy: ${J.message}`),d({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function p_(D){return D?.verbose||!1}async function T_(D){let _={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(D)_={..._,...D};let B=p_(_);if(K("config",`Starting with config: ${C(_,2)}`,B),K("config",`Is multi-proxy? ${"proxies"in _}`,B),_.viaDaemon){let M="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,cleanUrls:Z.cleanUrls??_.cleanUrls,changeOrigin:Z.changeOrigin??_.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await t({proxies:M,verbose:B});return}if("proxies"in _&&Array.isArray(_.proxies)){K("servers",`Found ${_.proxies.length} proxies in config`,B);for(let G of _.proxies)if(G.start){let M=`${G.from}-${G.to}`;try{K("watch",`Starting command for ${M} with command: ${G.start.command}`,B),X.info(`Starting command for ${M}...`),await D_.startProcess(M,G.start,B);let Z=new URL(G.from.startsWith("http")?G.from:`http://${G.from}`),E=Z.hostname||"localhost",Q=Number(Z.port)||80;try{await a(E,Q,B),K("watch",`Dev server is ready at ${E}:${Q}`,B)}catch(z){K("watch",`Connection check failed, but continuing with proxy setup: ${z}`,B),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw K("watch",`Failed to start command for ${M}: ${Z}`,B),Error(`Failed to start command for ${M}: ${Z}`)}}else K("watch",`No start command for proxy ${G.from} -> ${G.to}`,B)}else if("start"in _&&_.start){K("watch","Found start command in single proxy config",B);let G=`${_.from}-${_.to}`;try{if(_.start)K("watch",`Starting command: ${_.start.command}`,B),await D_.startProcess(G,_.start,B);let M=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),Z=M.hostname||"localhost",E=Number(M.port)||80;try{await a(Z,E,B),K("watch",`Dev server is ready at ${Z}:${E}`,B)}catch(Q){K("watch",`Connection check failed, but continuing with proxy setup: ${Q}`,B),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw K("watch",`Failed to run start command: ${M}`,B),Error(`Failed to run start command: ${M}`)}}else K("watch","No start command found in config",B);let N="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(F.platform!=="win32"&&(_.https||_.cleanup?.hosts!==!1)){if(!m())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",B),m_("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let G=await c(_);if(!G){if(K("ssl",`No valid or trusted certificates found for ${N}, generating new ones`,_.verbose),await K_(_),G=await c(_),!G)throw Error(`Failed to load SSL certificates after generation for ${N}`)}else K("ssl",`Using existing and trusted certificates for ${N}`,_.verbose);_._cachedSSLConfig=G}let Y="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((G)=>({...G,https:_.https,cleanup:_.cleanup,cleanUrls:G.cleanUrls??("cleanUrls"in _?_.cleanUrls:!1),vitePluginUsage:_.vitePluginUsage,changeOrigin:G.changeOrigin??_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig})):[{from:"from"in _?_.from:"localhost:5173",to:"to"in _?_.to:"rpx.localhost",cleanUrls:"cleanUrls"in _?_.cleanUrls:!1,https:_.https,cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,start:"start"in _?_.start:void 0,changeOrigin:_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig}],W=Y.map((G)=>G.to||"rpx.localhost"),$=_._cachedSSLConfig,V=W.filter((G)=>G&&!G.includes("localhost")&&!G.includes("127.0.0.1")),J=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"],T=[...new Set(V.map((G)=>G.split(".").pop()?.toLowerCase()))],I=T.filter((G)=>!!G&&J.includes(G));if(I.length>0&&B)X.warn(`The following TLDs may not work reliably for local development: ${I.map((G)=>`.${G}`).join(", ")}`),X.info(" These TLDs have HSTS preloading which can bypass local DNS"),X.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(F.platform==="darwin"&&V.length>0){let{setupDevelopmentDns:G}=await import("./chunk-krj531r2.js");if(await G({domains:V,verbose:B})){if(B)if(T.every((E)=>!!E&&A.includes(E)))X.success(`DNS server started for ${T.map((E)=>`.${E}`).join(", ")} domains`);else X.success(`DNS server started for ${T.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else K("dns","Could not start DNS server - custom domains may not resolve",B)}let R=async()=>{K("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:G}=await import("./chunk-krj531r2.js");await G({verbose:_.verbose})}catch(G){K("cleanup",`Error stopping DNS server: ${G}`,_.verbose)}try{await D_.stopAll(_.verbose)}catch(G){K("cleanup",`Error stopping processes: ${G}`,_.verbose)}await d({domains:W,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(F.on("SIGINT",R),F.on("SIGTERM",R),F.on("uncaughtException",(G)=>{K("process",`Uncaught exception: ${G}`,!0),console.error("Uncaught exception:",G),R()}),$&&Y.length>1){K("proxies",`Creating shared HTTPS server for ${Y.length} domains`,B);let G=new Map;for(let Q of Y){let z=Q.to||"rpx.localhost",w=new URL(Q.from?.startsWith("http")?Q.from:`http://${Q.from}`);if(G.set(z,{sourceHost:w.host,cleanUrls:Q.cleanUrls||!1,changeOrigin:Q.changeOrigin||!1,pathRewrites:Q.pathRewrites}),K("proxies",`Route: ${z} → ${w.host}`,B),!z.includes("localhost")&&!z.includes("127.0.0.1"))try{if(!(await h([z],B))[0])await L([z],B)}catch{K("hosts",`Could not add hosts entry for ${z}`,B)}}if(!await x(80,"0.0.0.0",B))O_(B);let Z=443;if(await x(Z,"0.0.0.0",B)){if(K("proxies",`Port ${Z} is already in use, cannot start shared proxy`,B),B)X.warn(`Port ${Z} is in use. Shared HTTPS proxy cannot start.`);return}try{let Q=Bun.serve({port:Z,hostname:"0.0.0.0",tls:{key:$.key,cert:$.cert,ca:$.ca,requestCert:!1,rejectUnauthorized:!1},fetch:M_((z)=>G.get(z),B),error(z){return K("server",`Shared proxy server error: ${z}`,B),new Response(`Server Error: ${z.message}`,{status:500})}});l.add(Q),K("proxies",`Shared HTTPS proxy listening on port ${Z} for ${G.size} domains`,B)}catch(Q){K("proxies",`Failed to start shared proxy: ${Q}`,B),console.error("Failed to start shared HTTPS proxy:",Q),R()}}else for(let G of Y)try{let M=G.to||"rpx.localhost";K("proxy",`Starting proxy for ${M} with SSL config: ${!!$}`,G.verbose),await F_({from:G.from||"localhost:5173",to:M,cleanUrls:G.cleanUrls||!1,https:G.https||!1,cleanup:G.cleanup||!1,vitePluginUsage:G.vitePluginUsage||!1,verbose:G.verbose||!1,_cachedSSLConfig:$,changeOrigin:G.changeOrigin||!1})}catch(M){K("proxies",`Failed to start proxy for ${G.to}: ${M}`,G.verbose),console.error(`Failed to start proxy for ${G.to}:`,M),R()}}function U_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${j.green(j.bold("rpx"))} ${j.green(`v${v_}`)}`),console.log(` ${j.green("➜")} ${j.dim(D?.from??"")} ${j.dim("➜")} ${j.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${j.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${j.green("➜")} Clean URLs enabled`)}var t2=T_;export{G_ as writeEntry,MD as watchRegistry,r_ as verifyHttpsChain,GD as trustRootCaForBrowsers,hD as tearDownDevelopmentDns,LD as syncDevelopmentDnsFromRegistry,qD as stopDnsServer,iD as stopDaemon,F_ as startServer,d_ as startProxy,T_ as startProxies,CD as startDnsServer,yD as setupResolver,PD as setupDevelopmentDns,C as safeStringify,$B as safeDeleteFile,t as runViaDaemon,pD as runDaemon,UD as resolverFilePath,wD as resolverBasenamesForDomains,ID as resolverBasenameForDomain,YB as resolvePathRewrite,cD as removeResolver,OD as removeLegacyTldResolvers,Z_ as removeHosts,W_ as removeEntry,dD as releaseDaemonLock,s2 as redactSensitive,uD as reconcileStaleDevelopmentDns,nD as reconcileDevelopmentDnsOnIdle,RD as readEntry,bD as readDaemonPid,i_ as readCertSha256Fingerprint,n_ as readCertCommonName,zD as readAll,ND as pruneStaleRootCas,c_ as portManager,s_ as parseSha256HashesFromSecurityListing,g_ as normalizeSha256Fingerprint,TD as normalizeDevDomain,JD as loadSSLConfig,KD as listCertSha256HashesByCommonName,e2 as isValidRootCA,$_ as isValidId,KB as isSingleProxyOptions,NB as isSingleProxyConfig,YD as isRootCaTrustedForSsl,$D as isRootCaFingerprintInKeychains,x as isPortInUse,VD as isPidAlive,BB as isMultiProxyOptions,DB as isMultiProxyConfig,xD as isDnsServerRunning,lD as isDaemonRunning,AD as isCertTrusted,N_ as httpsConfig,m as getSudoPassword,XD as getSharedDaemonCertPaths,WD as getRootCAPaths,Y_ as getRegistryDir,_B as getPrimaryDomain,BD as getMacosTrustKeychains,DD as getMacosLoginKeychainPath,mD as getDaemonRpxDir,vD as getDaemonPidPath,K_ as generateCertificate,ED as gcStaleEntries,QD as forceTrustCertificate,x_ as findAvailablePort,o2 as extractHostname,r2 as execSudoSync,X_ as ensureDaemonRunning,HD as devDomainsFromHosts,k_ as deriveIdFromTarget,gD as defaultDaemonSpawnCommand,B_ as defaultConfig,t2 as default,K as debugLog,M_ as createProxyFetchHandler,fD as contentLooksLikeRpxResolver,B_ as config,j as colors,ZD as clearSslConfigCache,E_ as cleanupCertificates,d as cleanup,h as checkHosts,c as checkExistingCertificates,t_ as certIncludesSanHostnames,L as addHosts,aD as acquireDaemonLock,_D as RPX_ROOT_CA_COMMON_NAME,kD as RPX_RESOLVER_MARKER,e_ as MACOS_SYSTEM_KEYCHAIN,o_ as MACOS_CA_TRUST_FLAGS,FD as LEGACY_TLD_RESOLVER_LABELS,b as DefaultPortManager,SD as DNS_STATE_VERSION,jD as DNS_PORT};