@stacksjs/rpx 0.11.13 → 0.11.14

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.
@@ -0,0 +1,157 @@
1
+ import{Aa as O,Ca as fn,Da as a,Ha as Fh,Ia as xf,Ka as Kr,La as Jh,Na as Zh,Oa as jh}from"./chunk-3pgh05pc.js";import Wo from"node:dgram";import*as ph from"node:fs/promises";import*as Ph from"node:path";import*as ti from"node:process";import{spawn as xh}from"node:child_process";import*as Mt from"node:fs/promises";import{homedir as ts}from"node:os";import*as Lt from"node:path";import*as F from"node:process";var L={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)};import{execSync as Gi}from"node:child_process";import D from"node:fs/promises";import*as qf from"node:os";import{homedir as qr}from"node:os";import{join as Q}from"node:path";import*as Ot from"node:process";import{createRequire as nu}from"node:module";import vr from"node:os";import Qr from"node:path";import{existsSync as ws,statSync as os}from"fs";import{existsSync as ru,mkdirSync as Qo,readdirSync as ta,readFileSync as eu,writeFileSync as ia}from"fs";import{homedir as wi}from"os";import{dirname as ea,resolve as St}from"path";import Xn from"process";import{existsSync as as,statSync as ms}from"fs";import{existsSync as Ee,mkdirSync as fu,readdirSync as su,writeFileSync as lu}from"fs";import{homedir as oi}from"os";import{dirname as As,resolve as ht}from"path";import hi from"process";import{join as cu,relative as hu,resolve as ds}from"path";import On from"process";import{existsSync as fl,mkdirSync as oa,readdirSync as aa,writeFileSync as ma}from"fs";import{homedir as te}from"os";import{dirname as Ea,resolve as ct}from"path";import bi from"process";import{join as uu,relative as $u,resolve as Es}from"path";import Zn from"process";import{existsSync as sl,mkdirSync as Ca,readdirSync as ga,writeFileSync as Ua}from"fs";import{dirname as Ja,resolve as Ln}from"path";import Te from"process";import{Buffer as ii}from"buffer";import{createCipheriv as yu,createDecipheriv as wu,randomBytes as ie}from"crypto";import{closeSync as ne,createReadStream as Ts,createWriteStream as ou,existsSync as re,fsyncSync as Ss,openSync as Rs,writeFileSync as au}from"fs";import{access as mu,constants as Bs,mkdir as Au,readdir as mn,rename as Cs,stat as ai,unlink as An,writeFile as ee}from"fs/promises";import{join as mi}from"path";import nt from"process";import{pipeline as du}from"stream/promises";import{createGzip as gs}from"zlib";import Ai from"process";import Kt from"process";import{Buffer as Ht}from"buffer";import{createCipheriv as Eu,createDecipheriv as Tu,randomBytes as fe}from"crypto";import{closeSync as se,createReadStream as Us,createWriteStream as Su,existsSync as dn,fsyncSync as Fs,openSync as Js,writeFileSync as Ru}from"fs";import{access as Bu,constants as js,mkdir as Cu,readdir as En,rename as Ns,stat as di,unlink as Tn,writeFile as le}from"fs/promises";import{isAbsolute as gu,join as Ei,resolve as Uu}from"path";import Y from"process";import{pipeline as Fu}from"stream/promises";import{createGzip as _s}from"zlib";import Ti from"process";import qt from"process";import Sn from"process";import{existsSync as Rn}from"fs";import{resolve as ce}from"path";import{existsSync as Ju}from"fs";import{existsSync as ju,readdirSync as Nu}from"fs";import{extname as he,resolve as Ys}from"path";import _u from"process";import{join as Yu,relative as Wu,resolve as Ws}from"path";import Mn from"process";import{Buffer as zt}from"buffer";import{createCipheriv as Iu,createDecipheriv as Ou,randomBytes as ue}from"crypto";import{closeSync as $e,createReadStream as Is,createWriteStream as Zu,existsSync as Bn,fsyncSync as Os,openSync as Zs,writeFileSync as Lu}from"fs";import{access as Mu,constants as Ls,mkdir as Hu,readdir as Cn,rename as Ms,stat as Si,unlink as gn,writeFile as ye}from"fs/promises";import{isAbsolute as zu,join as Ri,resolve as Gu}from"path";import W from"process";import{pipeline as Ku}from"stream/promises";import{createGzip as Hs}from"zlib";import Bi from"process";import xt from"process";import Un from"process";import{existsSync as Fn}from"fs";import{resolve as we}from"path";import{existsSync as qu}from"fs";import{exec as $y}from"node:child_process";import Qs from"node:fs";import yy from"node:os";import Jt from"node:path";import Kl from"node:process";import{promisify as wy}from"node:util";import Fi from"node:crypto";import kt from"node:fs";import We from"node:path";import{execSync as el}from"node:child_process";import Pn from"node:os";var bo=nu(import.meta.url);class ll{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 e=this.generateKey(t,n),f=r??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),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(!ws(t))return!0;return os(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 e=ws(n)?os(n):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},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,e)=>r+e.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 cl{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-r;return this.recordMetric({operation:t,duration:s,timestamp:e,...n}),f}catch(f){let s=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...n}),f}}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((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((e)=>e.duration),r=n.reduce((e,f)=>e+f,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 Hn=new ll,Ie=new cl,xu=Object.defineProperty,ku=(t)=>t;function Du(t,i){this[t]=ku.bind(null,i)}var Vu=(t,i)=>{for(var n in i)xu(t,n,{get:i[n],enumerable:!0,configurable:!0,set:Du.bind(i,n)})},bu=(t,i)=>()=>(t&&(i=t(t=0)),i),hl={};Vu(hl,{withErrorRecovery:()=>yl,tryLoadConfig:()=>A$,loadConfigWithResult:()=>a$,loadConfig:()=>Al,isRetryableError:()=>h$,isConfigNotFoundError:()=>c$,isBunfigError:()=>wl,globalPerformanceMonitor:()=>vi,globalCache:()=>gi,getEnvOrDefault:()=>u$,generateConfigTypes:()=>d$,defaultGeneratedDir:()=>gl,defaultConfigDir:()=>Cl,deepMergeWithArrayStrategy:()=>He,deepMerge:()=>ol,createLibraryConfig:()=>E$,config:()=>m$,bunfigPlugin:()=>T$,applyEnvVarsToConfig:()=>Di,TypeGenerationError:()=>Fe,SchemaValidationError:()=>Pi,PluginError:()=>je,PerformanceMonitor:()=>Ze,FileSystemError:()=>Ue,ErrorFactory:()=>ri,EnvVarError:()=>kn,EnvProcessor:()=>vn,ConfigValidator:()=>ze,ConfigValidationError:()=>Ce,ConfigNotFoundError:()=>xn,ConfigMergeError:()=>ge,ConfigLoader:()=>Ge,ConfigLoadError:()=>pi,ConfigFileLoader:()=>Qn,ConfigCache:()=>Oe,CacheUtils:()=>El,BunfigError:()=>mt,BrowserConfigError:()=>Je,ArrayMergeStrategies:()=>Rl});class Oe{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 e=this.generateKey(t,n),f=r??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),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(!as(t))return!0;return ms(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 e=as(n)?ms(n):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},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,e)=>r+e.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 Ze{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-r;return this.recordMetric({operation:t,duration:s,timestamp:e,...n}),f}catch(f){let s=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...n}),f}}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((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((e)=>e.duration),r=n.reduce((e,f)=>e+f,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 pu(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function Pu(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Xu(t){return t.getStats().size*2}function Le(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(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(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let r=[...i];for(let e of t)if(G(e)&&"name"in e){if(!r.find((f)=>G(f)&&("name"in f)&&f.name===e.name))r.push(e)}else if(G(e)&&"path"in e){if(!r.find((f)=>G(f)&&("path"in f)&&f.path===e.path))r.push(e)}else if(!r.some((f)=>zn(f,e)))r.push(e);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}if(!G(i)||!G(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let e=i[r];if(e===null||e===void 0)continue;else if(G(e)&&G(n[r]))n[r]=Le(n[r],e);else if(Array.isArray(e)&&Array.isArray(n[r]))if(e.length>0&&n[r].length>0&&G(e[0])&&G(n[r][0])){let f=[...e];for(let s of n[r])if(G(s)&&"name"in s){if(!f.find((c)=>G(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((c)=>G(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>zn(c,s)))f.push(s);n[r]=f}else if(e.every((f)=>typeof f==="string")&&n[r].every((f)=>typeof f==="string")){let f=[...e];for(let s of n[r])if(!f.includes(s))f.push(s);n[r]=f}else n[r]=e;else n[r]=e}return n}function zn(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(!zn(t[n],i[n]))return!1;return!0}if(G(t)&&G(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!zn(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function vu(t,i){if(!sl(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 Le(i,r)}catch{return null}}catch{return null}}async function Qu({name:t="",cwd:i,defaultConfig:n}){let r=i||Te.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Ln(r,`${s}${c}`),h=await vu(l,n);if(h!==null)return h}try{let s=Ln(r,"package.json");if(sl(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Le(n,c)}catch{}}}catch{}return n}function t$(t,i={}){let n=Zn.cwd();while(n.includes("storage"))n=Es(n,"..");let r=Es(n,t||"");if(i?.relative)return $u(Zn.cwd(),r);return r}async function i$(){try{let t=await Qu({name:"clarity",defaultConfig:_n,cwd:Zn.cwd(),endpoint:"",headers:{}});return{..._n,...t}}catch{return _n}}function q(){if(Kt.env.NODE_ENV==="test"||Kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function n$(){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 ul{async format(t){let i=await n$(),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:Ai.pid,hostname:i(),environment:Ai.env.NODE_ENV||"development",platform:Ai.platform,version:Ai.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ai.env.NODE_ENV||Ai.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gn{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={...Re},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ul,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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Yn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Yn};return{...Yn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Re.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,e=0,f=3,s=1000;while(e<f)try{try{try{await mu(this.config.logDirectory,Bs.F_OK|Bs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Au(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ii.from(t);try{if(!re(this.currentLogFile))await ee(this.currentLogFile,"",{mode:420});if(r=Rs(this.currentLogFile,"a",420),au(r,c,{flag:"a"}),Ss(r),r!==void 0)ne(r),r=void 0;if((await ai(this.currentLogFile)).size===0){if(await ee(this.currentLogFile,c,{flag:"w",mode:420}),(await ai(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let $=s*2**e;await new Promise((w)=>setTimeout(w,$)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(r!==void 0)try{ne(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return mi(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 mi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return mi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(q())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(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(r.length>f)for(let[s]of r.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return ie(16).toString("hex")}generateKey(){return ie(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=ie(16),r=yu("aes-256-gcm",i,n),e=ii.concat([r.update(t,"utf8"),r.final()]),f=r.getAuthTag();return{encrypted:ii.concat([n,e,f]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=gs(),e=[];r.on("data",(f)=>e.push(f)),r.on("end",()=>i(ii.from(ii.concat(e)))),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(q())return;let t=await ai(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 e=await mn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${n}.${s}`;if(await ai(n).catch(()=>null))try{if(await Cs(n,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await An(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await ee(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=n.replace(/\.log$/,`-${e}.log`);if(await ai(n).catch(()=>null))await Cs(n,f)}if(this.currentLogFile=r,i.maxFiles){let e=(await mn(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await An(mi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let n=Ts(t),r=ou(i),e=gs();await du(n,e,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()})),re(this.currentLogFile))try{let t=Rs(this.currentLogFile,"r+");Ss(t),ne(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(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await mn(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await An(mi(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?H.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:e,level:f,showTimestamp:s=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(i);if(f==="warning")y.push("WARN");else if(f==="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(e),y.join(" ")}let l=nt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${n} ${e}`;else if(f==="info"||f==="success")h=`${n} ${r} ${e}`;else h=`${n} ${r} ${H.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,l-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let n=/%([sdijfo%])/g,r=0,e=t.replace(n,(f,s)=>{if(s==="%")return"%";if(r>=i.length)return f;let c=i[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(r<i.length)e+=` ${i.slice(r).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...n){let r=new Date,e=this.formatConsoleTimestamp(r),f=this.formatFileTimestamp(r),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,n);if(this.fancy&&!q()){let h=Tl[t],u=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",$;switch(t){case"debug":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:H.gray(s),level:t}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:H.green(s),level:t}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error($),c){let w=c.split(`
2
+ `);for(let y of w)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:H.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!q()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
3
+ `;if(c)l+=`${c}
4
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!q()){let n=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:H.blue("◐"),tag:n,message:`${H.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),e=Math.round(r-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
5
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:H.green("✓"),tag:h,message:`${f}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!q())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new Gn(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(q())throw Error("createReadStream is not supported in browser environments");if(!re(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ts(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=ii.isBuffer(t)?t:ii.from(t,"base64"),e=r.slice(0,16),f=r.slice(-16),s=r.slice(16,-16),c=wu("aes-256-gcm",n,e);return c.setAuthTag(f),ii.concat([c.update(s),c.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 q()}isServerMode(){return!q()}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&&!q()){let f=t.split(`
6
+ `),s=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((u)=>{let $=" ".repeat(s-u.length-2);return`│ ${u}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:H.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:H.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:H.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:H.cyan(l),showTimestamp:!1}))}else if(!q())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let e=`${r} ${this.environment}.INFO: [BOX] ${t}
7
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(q())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${H.cyan("?")} ${t} (y/n) `);let n=(r)=>{let e=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(e==="y"||e==="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 e=/%([sdijfo%])/g,f=0;if(n=t.replace(e,(s,c)=>{if(c==="%")return"%";if(f>=i.length)return s;let l=i[f++];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 s}}),f<i.length)n+=` ${i.slice(f).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!q()){let e=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",f=H.blue("◐");console.error(`${f} ${e} ${H.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(t,i=""){if(!this.enabled||!this.fancy||q()||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,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,r)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())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,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;nt.stdout.write(`${"\r".padEnd(nt.stdout.columns||80)}\r`),this.log(e,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||q()||!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),e=t.barLength-r,f=H.green("━".repeat(r)),s=H.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${n}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||n===100?H.green("✓"):H.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${l}${h}`,y=nt.stdout.columns||80,m=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${m}`,nt.stdout.write(t.lastRenderedLine),i)nt.stdout.write(`
9
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||q()||!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(q()){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=mi(this.config.logDirectory,r);if(t.before)try{if((await ai(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);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 An(r),console.warn(`Deleted log file: ${r}`)}catch(e){console.error(`Failed to delete log file ${r}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Nn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&I(i[0])&&"id"in i[0]&&i[0].id===3&&I(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(I(i)&&I(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(I(t)&&"arr"in t&&Array.isArray(t.arr)&&I(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&I(i[0])&&I(t[0])){let r=[...i];for(let e of t)if(I(e)&&"name"in e){if(!r.find((f)=>I(f)&&("name"in f)&&f.name===e.name))r.push(e)}else if(I(e)&&"path"in e){if(!r.find((f)=>I(f)&&("path"in f)&&f.path===e.path))r.push(e)}else if(!r.some((f)=>Kn(f,e)))r.push(e);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}if(!I(i)||!I(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let e=i[r];if(e===null||e===void 0)continue;else if(I(e)&&I(n[r]))n[r]=Nn(n[r],e);else if(Array.isArray(e)&&Array.isArray(n[r]))if(e.length>0&&n[r].length>0&&I(e[0])&&I(n[r][0])){let f=[...e];for(let s of n[r])if(I(s)&&"name"in s){if(!f.find((c)=>I(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(I(s)&&"path"in s){if(!f.find((c)=>I(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Kn(c,s)))f.push(s);n[r]=f}else if(e.every((f)=>typeof f==="string")&&n[r].every((f)=>typeof f==="string")){let f=[...e];for(let s of n[r])if(!f.includes(s))f.push(s);n[r]=f}else n[r]=e;else n[r]=e}return n}function Me(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Nn(t,i);if(Array.isArray(t))return n==="replace"?i:Nn(t,i);if(!I(i)||!I(t))return i;let r={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=r[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(n==="replace")r[e]=f;else r[e]=Nn(s,f);else if(I(f)&&I(s))r[e]=Me(s,f,n);else r[e]=f}return r}function Kn(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(!Kn(t[n],i[n]))return!1;return!0}if(I(t)&&I(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Kn(t[e],i[e]))return!1}return!0}return!1}function I(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Jn(t,i,n="replace"){if(!fl(t))return null;try{let r=await import(t),e=r.default||r;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Me(i,e,n)}catch{return null}}catch{return null}}function r$(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let $=[...c,h],w=(o)=>o.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${r}_${$.map(w).join("_")}`,m=`${r}_${$.map((o)=>o.toUpperCase()).join("_")}`;if(n)et.info(`Checking environment variable ${y} for config ${t}.${$.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[h]=f(u,$);else{let o=bi.env[y]||bi.env[m];if(o!==void 0){if(n)et.info(`Using environment variable ${o?y:m} for config ${t}.${$.join(".")}`);if(typeof u==="number")l[h]=Number(o);else if(typeof u==="boolean")l[h]=o.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(o);if(Array.isArray(A))l[h]=A;else l[h]=o.split(",").map((d)=>d.trim())}catch{l[h]=o.split(",").map((A)=>A.trim())}else l[h]=o}}}return l}return f(e)}async function e$({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?r$(t,e,f):e,h=n||bi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let $=[t,`.${t}`].filter(Boolean),w=[`${t}.config`,`.${t}.config`].filter(Boolean),y=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],o=Array.from(new Set([h,ct(h,"config"),ct(h,".config"),r?ct(h,r):void 0].filter(Boolean)));for(let A of o){if(f)et.info(`Searching for configuration in: ${A}`);let d=[ct(h,"config"),ct(h,".config")].concat(r?[ct(h,r)]:[]).includes(A)?[...$,...w,...y,...m]:[...w,...$,...m,...y];for(let T of d)for(let N of u){let _=ct(A,`${T}${N}`),M=await Jn(_,l,c);if(M!==null){if(f)et.success(`Configuration loaded from: ${_}`);return M}}}if(t){let A=ct(te(),".config",t),d=["config",`${t}.config`];if(i)d.push(`${i}.config`);if(f)et.info(`Checking user config directory: ${A}`);for(let T of d)for(let N of u){let _=ct(A,`${T}${N}`),M=await Jn(_,l,c);if(M!==null){if(f)et.success(`Configuration loaded from user config directory: ${_}`);return M}}}if(t){let A=ct(te(),".config"),d=[`.${t}.config`];if(i)d.push(`.${i}.config`);if(f)et.info(`Checking user config directory for dotfile configs: ${A}`);for(let T of d)for(let N of u){let _=ct(A,`${T}${N}`),M=await Jn(_,l,c);if(M!==null){if(f)et.success(`Configuration loaded from user config directory dotfile: ${_}`);return M}}}if(t){let A=te(),d=[`.${t}.config`,`.${t}`];if(i)d.push(`.${i}.config`),d.push(`.${i}`);if(f)et.info(`Checking user home directory for dotfile configs: ${A}`);for(let T of d)for(let N of u){let _=ct(A,`${T}${N}`),M=await Jn(_,l,c);if(M!==null){if(f)et.success(`Configuration loaded from user home directory: ${_}`);return M}}}try{let A=ct(h,"package.json");if(fl(A)){let d=await import(A),T=d[t];if(!T&&i){if(T=d[i],T&&f)et.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)et.success(`Configuration loaded from package.json: ${T===d[t]?t:i}`);return Me(l,T,c)}catch(N){if(f)et.warn("Failed to merge package.json config:",N)}}}catch(A){if(f)et.warn("Failed to load package.json:",A)}if(f)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function f$(t,i={}){let n=On.cwd();while(n.includes("storage"))n=ds(n,"..");let r=ds(n,t||"");if(i?.relative)return hu(On.cwd(),r);return r}async function s$(){try{let t=await e$({name:"clarity",alias:"logging",defaultConfig:Wn,cwd:On.cwd()});return{...Wn,...t||{}}}catch{return Wn}}function V(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function l$(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof qt<"u"){let t=qt.type;if(t==="renderer"||t==="worker")return!1;return!!(qt.versions&&(qt.versions.node||qt.versions.bun))}return!1}class $l{async format(t){let i=await l$(),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:Ti.pid,hostname:i(),environment:Ti.env.NODE_ENV||"development",platform:Ti.platform,version:Ti.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ti.env.NODE_ENV||Ti.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Be},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new $l,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??Y.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,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{...In,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...In};return{...In,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Be.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!V()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,e=0,f=3,s=1000;while(e<f)try{try{try{await Bu(this.config.logDirectory,js.F_OK|js.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Cu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Ht.from(t);try{if(!dn(this.currentLogFile))await le(this.currentLogFile,"",{mode:420});if(r=Js(this.currentLogFile,"a",420),Ru(r,c,{flag:"a"}),Fs(r),r!==void 0)se(r),r=void 0;if((await di(this.currentLogFile)).size===0){if(await le(this.currentLogFile,c,{flag:"w",mode:420}),(await di(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let $=s*2**e;await new Promise((w)=>setTimeout(w,$)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(r!==void 0)try{se(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ei(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 Ei(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ei(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(V())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(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(r.length>f)for(let[s]of r.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return fe(16).toString("hex")}generateKey(){return fe(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=fe(16),r=Eu("aes-256-gcm",i,n),e=Ht.isBuffer(t)?t:Ht.from(t,"utf8"),f=r.update(e),s=r.final(),c=f.length+s.length,l=r.getAuthTag(),h=Ht.allocUnsafe(16+c+16);return n.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=_s(),e=[];r.on("data",(f)=>e.push(f)),r.on("end",()=>i(Ht.from(Ht.concat(e)))),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(V())return;if(!this.shouldWriteToFile())return;let t=await di(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 e=await En(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${n}.${s}`;if(await di(n).catch(()=>null))try{if(await Ns(n,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Tn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await le(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=n.replace(/\.log$/,`-${e}.log`);if(await di(n).catch(()=>null))await Ns(n,f)}if(this.currentLogFile=r,i.maxFiles){let e=(await En(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Tn(Ei(this.config.logDirectory,f))}}}async compressLogFile(t,i){let n=Us(t),r=Su(i),e=_s();await Fu(n,e,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=Js(this.currentLogFile,"r+");Fs(t),se(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(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await En(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Tn(Ei(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()?g.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||V())return!1;let t=typeof Y.env.NO_COLOR<"u",i=Y.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof Y.stderr<"u"&&Y.stderr.isTTY||typeof Y.stdout<"u"&&Y.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:e,level:f,showTimestamp:s=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(i);if(f==="warning")y.push("WARN");else if(f==="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(e),y.join(" ")}let l=Y.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${n} ${e}`;else if(f==="info"||f==="success")h=`${n} ${r} ${e}`;else h=`${n} ${r} ${g.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,l-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let n=/%([sdijfo%])/g,r=0,e=t.replace(n,(f,s)=>{if(s==="%")return"%";if(r>=i.length)return f;let c=i[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(r<i.length)e+=` ${i.slice(r).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,e)=>{let f=g.underline(g.blue(r)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(n,r)=>g.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>g.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>g.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>g.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>g.strikethrough(r)),i}supportsHyperlinks(){if(V())return!1;let t=Y.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=Y.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(gu(i)||i.startsWith("./")||i.startsWith("../"))i=Uu(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,e=this.formatConsoleTimestamp(r),f=this.formatFileTimestamp(r),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,n);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Sl[t],w=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:g.gray(l),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:g.green(l),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.error(y),c){let m=c.split(`
10
+ `);for(let o of m)if(o.trim()&&!o.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:g.gray(` ${o}`),level:t,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
11
+ `;if(c)u+=`${c}
12
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let n={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};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()&&!V()&&Y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!V()&&Y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!V()&&Y.stdout.isTTY)Y.stdout.write(`
13
+ `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!V()&&Y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:n,message:`${g.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),e=Math.round(r-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
14
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":g.green("✓"),tag:h,message:`${f}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!V())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new qn(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(V())throw Error("createReadStream is not supported in browser environments");if(!dn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Us(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=Ht.isBuffer(t)?t:Ht.from(t,"base64"),e=r.subarray(0,16),f=r.subarray(r.length-16),s=r.subarray(16,r.length-16),c=Tu("aes-256-gcm",n,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,$=Ht.allocUnsafe(u);return l.copy($,0),h.copy($,l.length),$.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 V()}isServerMode(){return!V()}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:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
15
+ `),l=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:n,message:g.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:g.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:n,message:g.cyan(u),showTimestamp:!1}))}else if(!V())console.error(`${r} ${this.environment}.INFO: [BOX] ${f}`);let s=`${r} ${this.environment}.INFO: [BOX] ${f}
16
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(V())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${g.cyan("?")} ${t} (y/n) `);let n=(r)=>{let e=r.toString().trim().toLowerCase();Y.stdin.removeListener("data",n);try{if(typeof Y.stdin.setRawMode==="function")Y.stdin.setRawMode(!1)}catch{}Y.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof Y.stdin.setRawMode==="function")Y.stdin.setRawMode(!0)}catch{}Y.stdin.resume(),Y.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 s=/%([sdijfo%])/g,c=0;if(n=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let u=i[c++];switch(h){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 l}}),c<i.length)n+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:e}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${c}${s} ${g.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!Y.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),e=t.barLength-r,f=g.green("━".repeat(r)),s=g.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${n}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||n===100?g.green("✓"):g.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${l}${h}`,y=Y.stdout.columns||80,m=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${m}`,Y.stdout.write(t.lastRenderedLine),i)Y.stdout.write(`
18
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||V()||!Y.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(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await En(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=Ei(this.config.logDirectory,r);if(t.before)try{if((await di(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);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 Tn(r),console.warn(`Deleted log file: ${r}`)}catch(e){console.error(`Failed to delete log file ${r}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function yl(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=n;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===n||!e(s))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function wl(t){return t instanceof mt}function c$(t){return t instanceof xn}function h$(t){if(wl(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 vn{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:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=n,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return vi.track("applyEnvironmentVariables",h,{configName:t});return h()}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[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${n}_${c.join("_")}`,h=r.useBackwardCompatibility?`${n}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,n,r);else{let u=Sn.env[l]||(h?Sn.env[h]:void 0);if(u!==void 0){if(r.verbose){let $=Sn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,r.customParsers,r.configName)}catch($){if($ instanceof kn)throw $;throw ri.envVar(l,u,typeof f,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,e){for(let[f,s]of Object.entries(r))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ri.envVar(n,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,e]of Object.entries(Sn.env))if(r.startsWith(n)&&e!==void 0)i[r]=e;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(e){r.push(`Cannot parse value "${i}" as ${n}: ${e}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:e="text"}=n,f=r||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,n,r){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${n}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,n,r);else r.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}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 u$(t,i){let n=dl("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 al(t,i,n,new WeakMap)}function al(t,i,n,r){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=n;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return ml(t,i,e,r);if(!Rt(i)||!Rt(t))return i;return o$(t,i,n,r)}function ml(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 $$(t,i);case"smart":return y$(t,i,r);default:return i}return i}function $$(t,i){let n=[...i];for(let r of t)if(!n.some((e)=>Se(e,r)))n.push(r);return n}function y$(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Rt(i[0])&&Rt(t[0]))return w$(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}function w$(t,i,n){let r=[...i];for(let e of t){if(!Rt(e)){r.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(r.find((l)=>Rt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)r.push(e)}return r}function o$(t,i,n,r){let e=i;if(Rt(e)&&r.has(e))return r.get(e);let f={...t};if(Rt(e))r.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(n.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Rt(c)&&Rt(l))f[s]=al(l,c,n,r);else if(Array.isArray(c)||Array.isArray(l))f[s]=ml(l,c,n.arrayMergeMode||"smart",r);else f[s]=c}return f}function He(t,i,n="replace"){return ol(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Se(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(!Se(t[n],i[n]))return!1;return!0}if(Rt(t)&&Rt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Se(t[e],i[e]))return!1}return!0}return!1}function Rt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Qn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=n;if(e){let h=gi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Rn(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new pi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new pi(t,Error("Configuration must export a valid object"),"unknown");let m={config:He(i,$,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)gi.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ri.configLoad(t,h):ri.configLoad(t,Error(String(h)))}};if(s)return vi.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let e=await this.loadFromPath(r,i,n);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(n.verbose)console.warn(`Failed to load config from ${r}:`,e)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),e=[];for(let f of r)for(let s of this.extensions)e.push(ce(i,`${f}${s}`));return e}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 yl(async()=>{return Rn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Rn(t))return r;if(i||n){let e=this.generateNamePatterns(i||"",n);for(let f of e)for(let s of this.extensions){let c=ce(t,`${f}${s}`);if(await this.checkFileAccess(c))r.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=ce(t,s);if(await this.checkFileAccess(c))r.push(c)}}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(!Rn(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:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}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 e=await this.loadFromPath(r,{},i);if(e)n.set(r,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${r}:`,e)}})),n}}class ze{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=n,h=async()=>{let u=[],$=[],w={stopOnFirstError:r,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await vi.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,n){try{if(!Ju(i))throw new Pi(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),e=r.default||r;if(Array.isArray(e))return this.validateWithRules(t,e,n);else return this.validateWithJSONSchema(t,e,n)}catch(r){throw new Pi(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],e=[];return this.validateObjectAgainstSchema(t,i,"",r,e,n),{isValid:r.length===0,errors:r,warnings:e}}validateObjectAgainstSchema(t,i,n,r,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(r.push({path:n,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.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"}),f.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 s=0;s<t.length;s++){let c=n?`${n}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,r,e,f),f.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(r.push({path:n?`${n}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=n?`${n}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,r,e,f),f.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(r.push(...c),n.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:e}}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 e=Array.isArray(t)?"array":typeof t;if(e!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,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 e=i.validator(t);if(e)r.push({path:n,message:i.message||e,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let e of n)if(r&&typeof r==="object"&&e in r)r=r[e];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,e,f,s]=r;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}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:Bl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ge{fileLoader=new Qn;envProcessor=new vn;validator=new ze;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:e,validate:f,...s}=t;try{if(n?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,n)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),$=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),w=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw l;if($&&(!h||!w))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(n?.enabled&&c)this.cacheResult(s.name||"",c,n,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)jt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw jt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||hi.cwd(),w=[],y=await this.loadLocalConfiguration(r,e,$,s,c,h,u,l,n);if(y)return w.push(...this.getLocalSearchPaths(r,e,$,s)),this.finalizeResult(y,w,l,r,u);let m=await this.loadHomeConfiguration(r,e,c,h,u,l);if(m)return w.push(...this.getHomeSearchPaths(r,e)),this.finalizeResult(m,w,l,r,u);let o=await this.loadPackageJsonConfiguration(r,e,$,c,h,u,l);if(o)return w.push(ht($,"package.json")),this.finalizeResult(o,w,l,r,u);if(w.push(...this.getAllSearchPaths(r,e,$,s)),i)throw ri.configNotFound(r,w,e);return{...await this.applyEnvironmentVariables(r,c,l,u),warnings:[`No configuration file found for "${r}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,e,f,s,c,l){let h=c?Di(t,e,s):e,u=this.getLocalDirectories(n,r);for(let $ of u){if(s)jt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(y){if(s)jt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,e,f){if(!t)return null;let s=f?Di(t,n,e):n,c=[ht(oi(),".config",t),ht(oi(),".config"),oi()];for(let l of c){if(e)jt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:r,verbose:e});if(u){if(e)jt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,n,r,e,f,s){let c=s?Di(t,r,f):r;try{let l=ht(n,"package.json");if(!Ee(l))return null;let h=await import(l),u=h[t],$=t;if(!u&&i)u=h[i],$=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)jt.success(`Configuration loaded from package.json: ${$}`);return{config:He(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)jt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Di(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let e=[];if(n){let f=n(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ri.configValidation(r||"unknown",e,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return gi.get(n)||null}cacheResult(t,i,n,r){let e=this.generateCacheKey(t,r);gi.set(e,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,ht(t,"config"),ht(t,".config"),i?ht(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let e=[];return e.push(...this.getLocalSearchPaths(t,i,n,r)),e.push(...this.getHomeSearchPaths(t,i)),e.push(ht(n,"package.json")),e}getLocalSearchPaths(t,i,n,r){let e=this.getLocalDirectories(n,r),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let n=[ht(oi(),".config",t),ht(oi(),".config"),oi()],r=[];for(let e of n)r.push(...this.fileLoader.generateConfigPaths(t,e,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function zs(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 a$(t){return Dt.loadConfig({...t,__strictErrorHandling:!0})}async function Al(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 Dt.loadConfig(t);else r=await Dt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let e=r instanceof Error?r.name:"UnknownError",f=r instanceof Error?r.message:String(r);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)jt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let s=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Dt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function m$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await Dt.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"&&zs(n)))return(await Dt.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await Dt.loadConfig({...t,cwd:t.cwd||hi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&zs(i)))return(await Dt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function A$(t,i,n="replace"){let r=new Qn;try{let e=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function Di(t,i,n=!1){let r=new vn,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((o)=>o.toUpperCase()).join("")}`,`${e}_${$.map((o)=>o.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,m;for(let o of w)if(y=hi.env[o],y!==void 0){m=o;break}if(y!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let o=Number(y);if(!Number.isNaN(o))l[h]=o}else if(Array.isArray(u))try{l[h]=JSON.parse(y)}catch{l[h]=y.split(",").map((o)=>o.trim())}else l[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,$)}return l}return f(i)}function d$(t){let i=ht(hi.cwd(),t.configDir),n=ht(hi.cwd(),t.generatedDir),r=ht(n,"config-types.ts");if(!Ee(As(r)))fu(As(r),{recursive:!0,mode:511});let e=Ee(i)?su(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${V$}
31
+ export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
32
+ `;lu(r,f,{mode:438})}function E$(t){let i=null,n=null,r=()=>{if(!n)n=Al(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)jt.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return n},e="defaultConfig"in t?t.defaultConfig:{};return i=e,r(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return r(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function T$(t){let i=Ys(_u.cwd(),t?.configDir||"./config");function n(){if(!ju(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Nu(i).filter((l)=>e.has(he(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let u=he(h).toLowerCase(),$=c.get(l);if(!$){c.set(l,h);continue}let w=he($).toLowerCase();if(f.indexOf(u)<f.indexOf(w))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function r(){let e=n(),f=e.map((l)=>l.base),s=f.length?f.map((l)=>`'${l}'`).join(" | "):"string",c=e.length?`{
33
+ ${e.map((l)=>{let h=Ys(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${h}').default`}).join(`,
34
+ `)}
35
+ }`:"Record<string, any>";return`export type ConfigNames = ${s}
36
+ export type ConfigByName = ${c}
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(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var dl,gi,vi,El,S$,R$,Gs,_n,Re,rt,H,B$,Ks,C$,qs,g$,U$,oe,F$,xs,ks,ae,J$,j$,N$,_$,Yn,Tl,Y$,et,W$,I$,Ds,Wn,Be,b,g,O$,Vs,Z$,bs,L$,M$,me,H$,ps,Ps,z$,Ae,G$,K$,q$,x$,k$,In,Sl,D$,V$="0.15.6",mt,xn,pi,Ce,ge,kn,Ue,Fe,Pi,Je,je,ri,Rl,Bl,jt,Dt,Cl,gl,b$=bu(async()=>{dl=import.meta.require,gi=new Oe,vi=new Ze,El={createKey:pu,isEquivalent:Pu,estimateMemoryUsage:Xu},S$=Ln(Te.cwd(),"config"),R$=Ln(Te.cwd(),"src/generated"),Gs=Zn.env.CLARITY_LOG_DIR||uu(t$(),"logs"),_n={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Re=await i$(),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"},H=rt,B$=rt.red,Ks=rt.green,C$=rt.yellow,qs=rt.blue,g$=rt.magenta,U$=rt.cyan,oe=rt.white,F$=rt.gray,xs=rt.bgRed,ks=rt.bgYellow,ae=rt.bold,J$=rt.dim,j$=rt.italic,N$=rt.underline,_$=rt.reset,Yn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tl={debug:"\uD83D\uDD0D",info:qs("ℹ"),success:Ks("✓"),warning:ks(oe(ae(" WARN "))),error:xs(oe(ae(" ERROR ")))},Y$=new Gn("stacks"),et=new Gn("bunfig",{showTags:!0}),W$=ct(bi.cwd(),"config"),I$=ct(bi.cwd(),"src/generated"),Ds=On.env.CLARITY_LOG_DIR||cu(f$(),"logs"),Wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ds,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Be=await s$(),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"},g=b,O$=b.red,Vs=b.green,Z$=b.yellow,bs=b.blue,L$=b.magenta,M$=b.cyan,me=b.white,H$=b.gray,ps=b.bgRed,Ps=b.bgYellow,z$=b.bgGray,Ae=b.bold,G$=b.dim,K$=b.italic,q$=b.underline,x$=b.strikethrough,k$=b.reset,In={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sl={debug:"\uD83D\uDD0D",info:bs("ℹ"),success:Vs("✓"),warning:Ps(me(Ae(" WARN "))),error:ps(me(Ae(" ERROR ")))},D$=new qn("stacks"),mt=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}`}},xn=class extends mt{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})}},pi=class 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}},Ce=class 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})}},ge=class 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}},kn=class 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})}},Ue=class 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}},Fe=class 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}},Pi=class 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})}},Je=class 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})}},je=class 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}},ri={configNotFound(t,i,n){return new xn(t,i,n)},configLoad(t,i,n){return new pi(t,i,n)},configValidation(t,i,n){return new Ce(t,i,n)},configMerge(t,i,n,r){return new ge(t,i,n,r)},envVar(t,i,n,r){return new kn(t,i,n,r)},fileSystem(t,i,n){return new Ue(t,i,n)},typeGeneration(t,i,n){return new Fe(t,i,n)},schemaValidation(t,i,n){return new Pi(t,i,n)},browserConfig(t,i,n,r){return new Je(t,i,n,r)},plugin(t,i,n){return new je(t,i,n)}},Rl={replace:"replace",concat:"concat",smart:"smart"},Bl=/^https?:\/\//,jt=new qn("bunfig",{showTags:!0}),Dt=new Ge,Cl=ht(hi.cwd(),"config"),gl=ht(hi.cwd(),"src/generated")});function p$(t,i={}){let n=Mn.cwd();while(n.includes("storage"))n=Ws(n,"..");let r=Ws(n,t||"");if(i?.relative)return Wu(Mn.cwd(),r);return r}var P$=Mn.env.CLARITY_LOG_DIR||Yu(p$(),"logs"),Ul={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:P$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dn={...Ul},Em=(async()=>{try{let{loadConfig:t}=await b$().then(()=>hl),i=await t({name:"clarity",alias:"logging",defaultConfig:Ul,cwd:Mn.cwd()});if(i)Object.assign(Dn,i)}catch{}return Dn})();function p(){if(xt.env.NODE_ENV==="test"||xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function X$(){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 Fl{async format(t){let i=await X$(),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:Bi.pid,hostname:i(),environment:Bi.env.NODE_ENV||"development",platform:Bi.platform,version:Bi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Bi.env.NODE_ENV||Bi.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"},J=tt,Tm=tt.red,v$=tt.green,Sm=tt.yellow,Q$=tt.blue,Rm=tt.magenta,Bm=tt.cyan,Xs=tt.white,Cm=tt.gray,ty=tt.bgRed,iy=tt.bgYellow,gm=tt.bgGray,vs=tt.bold,Um=tt.dim,Fm=tt.italic,Jm=tt.underline,jm=tt.strikethrough,Nm=tt.reset,de={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ny={debug:"\uD83D\uDD0D",info:Q$("ℹ"),success:v$("✓"),warning:iy(Xs(vs(" WARN "))),error:ty(Xs(vs(" ERROR ")))};class tr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Dn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Fl,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??W.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,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{...de,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...de};return{...de,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Dn.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,e=0,f=3,s=1000;while(e<f)try{try{try{await Mu(this.config.logDirectory,Ls.F_OK|Ls.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Hu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:zt.from(t);try{if(!Bn(this.currentLogFile))await ye(this.currentLogFile,"",{mode:420});if(r=Zs(this.currentLogFile,"a",420),Lu(r,c,{flag:"a"}),Os(r),r!==void 0)$e(r),r=void 0;if((await Si(this.currentLogFile)).size===0){if(await ye(this.currentLogFile,c,{flag:"w",mode:420}),(await Si(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let $=s*2**e;await new Promise((w)=>setTimeout(w,$)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(r!==void 0)try{$e(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ri(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 Ri(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ri(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(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(r.length>f)for(let[s]of r.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return ue(16).toString("hex")}generateKey(){return ue(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=ue(16),r=Iu("aes-256-gcm",i,n),e=zt.isBuffer(t)?t:zt.from(t,"utf8"),f=r.update(e),s=r.final(),c=f.length+s.length,l=r.getAuthTag(),h=zt.allocUnsafe(16+c+16);return n.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Hs(),e=[];r.on("data",(f)=>e.push(f)),r.on("end",()=>i(zt.from(zt.concat(e)))),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 Si(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 e=await Cn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${n}.${s}`;if(await Si(n).catch(()=>null))try{if(await Ms(n,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await gn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await ye(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=n.replace(/\.log$/,`-${e}.log`);if(await Si(n).catch(()=>null))await Ms(n,f)}if(this.currentLogFile=r,i.maxFiles){let e=(await Cn(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await gn(Ri(this.config.logDirectory,f))}}}async compressLogFile(t,i){let n=Is(t),r=Zu(i),e=Hs();await Ku(n,e,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()})),Bn(this.currentLogFile))try{let t=Zs(this.currentLogFile,"r+");Os(t),$e(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 Cn(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await gn(Ri(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()?J.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof W.env.NO_COLOR<"u",i=W.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof W.stderr<"u"&&W.stderr.isTTY||typeof W.stdout<"u"&&W.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:e,level:f,showTimestamp:s=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(i);if(f==="warning")y.push("WARN");else if(f==="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(e),y.join(" ")}let l=W.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${n} ${e}`;else if(f==="info"||f==="success")h=`${n} ${r} ${e}`;else h=`${n} ${r} ${J.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,l-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let n=/%([sdijfo%])/g,r=0,e=t.replace(n,(f,s)=>{if(s==="%")return"%";if(r>=i.length)return f;let c=i[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(r<i.length)e+=` ${i.slice(r).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,e)=>{let f=J.underline(J.blue(r)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(n,r)=>J.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>J.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>J.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>J.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>J.strikethrough(r)),i}supportsHyperlinks(){if(p())return!1;let t=W.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=W.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(zu(i)||i.startsWith("./")||i.startsWith("../"))i=Gu(i);else return null;return Bn(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,e=this.formatConsoleTimestamp(r),f=this.formatFileTimestamp(r),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,n);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":ny[t],w=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:J.gray(l),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:J.green(l),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.error(y),c){let m=c.split(`
40
+ `);for(let o of m)if(o.trim()&&!o.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:J.gray(` ${o}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
41
+ `;if(c)u+=`${c}
42
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let n={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};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()&&W.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!p()&&W.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!p()&&W.stdout.isTTY)W.stdout.write(`
43
+ `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&W.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":J.blue("◐"),tag:n,message:`${J.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),e=Math.round(r-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
44
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":J.green("✓"),tag:h,message:`${f}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new 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(p())throw Error("createReadStream is not supported in browser environments");if(!Bn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Is(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=zt.isBuffer(t)?t:zt.from(t,"base64"),e=r.subarray(0,16),f=r.subarray(r.length-16),s=r.subarray(16,r.length-16),c=Ou("aes-256-gcm",n,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,$=zt.allocUnsafe(u);return l.copy($,0),h.copy($,l.length),$.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:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
45
+ `),l=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:n,message:J.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:J.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:n,message:J.cyan(u),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${f}`);let s=`${r} ${this.environment}.INFO: [BOX] ${f}
46
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${J.cyan("?")} ${t} (y/n) `);let n=(r)=>{let e=r.toString().trim().toLowerCase();W.stdin.removeListener("data",n);try{if(typeof W.stdin.setRawMode==="function")W.stdin.setRawMode(!1)}catch{}W.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof W.stdin.setRawMode==="function")W.stdin.setRawMode(!0)}catch{}W.stdin.resume(),W.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 s=/%([sdijfo%])/g,c=0;if(n=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let u=i[c++];switch(h){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 l}}),c<i.length)n+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:e}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${J.blue("◐")} `;console.error(`${c}${s} ${J.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!W.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),e=t.barLength-r,f=J.green("━".repeat(r)),s=J.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${n}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||n===100?J.green("✓"):J.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${J.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${l}${h}`,y=W.stdout.columns||80,m=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${m}`,W.stdout.write(t.lastRenderedLine),i)W.stdout.write(`
48
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!W.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 Cn(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=Ri(this.config.logDirectory,r);if(t.before)try{if((await Si(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await gn(r),console.warn(`Deleted log file: ${r}`)}catch(e){console.error(`Failed to delete log file ${r}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var _m=new tr("stacks");class Yt 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 Jl extends Yt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],e="";if(r.length===1)e=` or alias "${r[0]}"`;else if(r.length>1)e=` or aliases ${r.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class Vn extends Yt{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 jl extends Yt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class Nl extends Yt{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 Yt{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 _l extends Yt{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 Yl extends Yt{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 bn extends Yt{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 Wl extends Yt{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 Il extends Yt{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 Ui={configNotFound(t,i,n){return new Jl(t,i,n)},configLoad(t,i,n){return new Vn(t,i,n)},configValidation(t,i,n){return new jl(t,i,n)},configMerge(t,i,n,r){return new Nl(t,i,n,r)},envVar(t,i,n,r){return new Ke(t,i,n,r)},fileSystem(t,i,n){return new _l(t,i,n)},typeGeneration(t,i,n){return new Yl(t,i,n)},schemaValidation(t,i,n){return new bn(t,i,n)},browserConfig(t,i,n,r){return new Wl(t,i,n,r)},plugin(t,i,n){return new Il(t,i,n)}};async function ry(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=n;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===n||!e(s))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class qe{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:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=n,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Ie.track("applyEnvironmentVariables",h,{configName:t});return h()}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[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${n}_${c.join("_")}`,h=r.useBackwardCompatibility?`${n}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,n,r);else{let u=Un.env[l]||(h?Un.env[h]:void 0);if(u!==void 0){if(r.verbose){let $=Un.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,r.customParsers,r.configName)}catch($){if($ instanceof Ke)throw $;throw Ui.envVar(l,u,typeof f,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,e){for(let[f,s]of Object.entries(r))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Ui.envVar(n,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,e]of Object.entries(Un.env))if(r.startsWith(n)&&e!==void 0)i[r]=e;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(e){r.push(`Cannot parse value "${i}" as ${n}: ${e}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:e="text"}=n,f=r||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,n,r){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${n}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,n,r);else r.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}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 ey(t,i,n={}){return Ol(t,i,n,new WeakMap)}function Ol(t,i,n,r){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=n;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Zl(t,i,e,r);if(!Bt(i)||!Bt(t))return i;return cy(t,i,n,r)}function Zl(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 fy(t,i);case"smart":return sy(t,i,r);default:return i}return i}function fy(t,i){let n=[...i];for(let r of t)if(!n.some((e)=>Ne(e,r)))n.push(r);return n}function sy(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return ly(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}function ly(t,i,n){let r=[...i];for(let e of t){if(!Bt(e)){r.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(r.find((l)=>Bt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)r.push(e)}return r}function cy(t,i,n,r){let e=i;if(Bt(e)&&r.has(e))return r.get(e);let f={...t};if(Bt(e))r.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(n.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=Ol(l,c,n,r);else if(Array.isArray(c)||Array.isArray(l))f[s]=Zl(l,c,n.arrayMergeMode||"smart",r);else f[s]=c}return f}function Ll(t,i,n="replace"){return ey(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ne(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(!Ne(t[n],i[n]))return!1;return!0}if(Bt(t)&&Bt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Ne(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Ml{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=n;if(e){let h=Hn.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Fn(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new Vn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Vn(t,Error("Configuration must export a valid object"),"unknown");let m={config:Ll(i,$,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Hn.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?Ui.configLoad(t,h):Ui.configLoad(t,Error(String(h)))}};if(s)return Ie.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let e=await this.loadFromPath(r,i,n);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(n.verbose)console.warn(`Failed to load config from ${r}:`,e)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),e=[];for(let f of r)for(let s of this.extensions)e.push(we(i,`${f}${s}`));return e}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 f of r){if(!f)continue;if(n.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)n.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return n.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return ry(async()=>{return Fn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Fn(t))return r;if(i||n){let e=this.generateNamePatterns(i||"",n);for(let f of e)for(let s of this.extensions){let c=we(t,`${f}${s}`);if(await this.checkFileAccess(c))r.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=we(t,s);if(await this.checkFileAccess(c))r.push(c)}}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(!Fn(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:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}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 e=await this.loadFromPath(r,{},i);if(e)n.set(r,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${r}:`,e)}})),n}}var hy=/^https?:\/\//;class Hl{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=n,h=async()=>{let u=[],$=[],w={stopOnFirstError:r,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await Ie.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,n){try{if(!qu(i))throw new bn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),e=r.default||r;if(Array.isArray(e))return this.validateWithRules(t,e,n);else return this.validateWithJSONSchema(t,e,n)}catch(r){throw new bn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],e=[];return this.validateObjectAgainstSchema(t,i,"",r,e,n),{isValid:r.length===0,errors:r,warnings:e}}validateObjectAgainstSchema(t,i,n,r,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(r.push({path:n,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.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"}),f.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 s=0;s<t.length;s++){let c=n?`${n}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,r,e,f),f.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(r.push({path:n?`${n}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=n?`${n}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,r,e,f),f.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(r.push(...c),n.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:e}}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 e=Array.isArray(t)?"array":typeof t;if(e!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,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 e=i.validator(t);if(e)r.push({path:n,message:i.message||e,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let e of n)if(r&&typeof r==="object"&&e in r)r=r[e];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,e,f,s]=r;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}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:hy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Gt=new tr("bunfig",{showTags:!0});function uy(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 zl{fileLoader=new Ml;envProcessor=new qe;validator=new Hl;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:e,validate:f,...s}=t;try{if(n?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,n)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),$=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),w=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw l;if($&&(!h||!w))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(n?.enabled&&c)this.cacheResult(s.name||"",c,n,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Gt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw Gt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||Xn.cwd(),w=[],y=await this.loadLocalConfiguration(r,e,$,s,c,h,u,l,n);if(y)return w.push(...this.getLocalSearchPaths(r,e,$,s)),this.finalizeResult(y,w,l,r,u);let m=await this.loadHomeConfiguration(r,e,c,h,u,l);if(m)return w.push(...this.getHomeSearchPaths(r,e)),this.finalizeResult(m,w,l,r,u);let o=await this.loadPackageJsonConfiguration(r,e,$,c,h,u,l);if(o)return w.push(St($,"package.json")),this.finalizeResult(o,w,l,r,u);if(w.push(...this.getAllSearchPaths(r,e,$,s)),i)throw Ui.configNotFound(r,w,e);return{...await this.applyEnvironmentVariables(r,c,l,u),warnings:[`No configuration file found for "${r}"${uy(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,e,f,s,c,l){let h=c?jn(t,e,s):e,u=this.getLocalDirectories(n,r);for(let $ of u){if(s)Gt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(y){if(s)Gt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,e,f){if(!t)return null;let s=f?jn(t,n,e):n,c=[St(wi(),".config",t),St(wi(),".config"),wi()];for(let l of c){if(e)Gt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:r,verbose:e});if(u){if(e)Gt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,n,r,e,f,s){let c=s?jn(t,r,f):r;try{let l=St(n,"package.json");if(!ru(l))return null;let h={};try{h=JSON.parse(eu(l,"utf8"))}catch(w){if(f)Gt.warn("Failed to parse package.json:",[w instanceof Error?w:Error(String(w))]);return null}let u=h[t],$=t;if(!u&&i){let w=Array.isArray(i)?i:[i];for(let y of w){if(!y)continue;if(h[y]){u=h[y],$=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Gt.success(`Configuration loaded from package.json: ${$}`);return{config:Ll(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Gt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:jn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let e=[];if(n){let f=n(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Ui.configValidation(r||"unknown",e,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Hn.get(n)||null}cacheResult(t,i,n,r){let e=this.generateCacheKey(t,r);Hn.set(e,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,St(t,"config"),St(t,".config"),i?St(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let e=[];return e.push(...this.getLocalSearchPaths(t,i,n,r)),e.push(...this.getHomeSearchPaths(t,i)),e.push(St(n,"package.json")),e}getLocalSearchPaths(t,i,n,r){let e=this.getLocalDirectories(n,r),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let n=[St(wi(),".config",t),St(wi(),".config"),wi()],r=[];for(let e of n)r.push(...this.fileLoader.generateConfigPaths(t,e,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ym=new zl;function jn(t,i,n=!1){let r=new qe,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((o)=>o.toUpperCase()).join("")}`,`${e}_${$.map((o)=>o.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,m;for(let o of w)if(y=Xn.env[o],y!==void 0){m=o;break}if(y!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let o=Number(y);if(!Number.isNaN(o))l[h]=o}else if(Array.isArray(u))try{l[h]=JSON.parse(y)}catch{l[h]=y.split(",").map((o)=>o.trim())}else l[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,$)}return l}return f(i)}var Wm=St(Xn.cwd(),"config"),Im=St(Xn.cwd(),"src/generated"),Gl={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:Qr.join(vr.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Qr.join(vr.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Qr.join(vr.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},k=Gl,Nt={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Ci={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 _e(t,i){let n=[];function r(e){let f;try{f=Qs.readdirSync(e)}catch{return}for(let s of f){let c=Jt.join(e,s);try{if(Qs.statSync(c).isDirectory())r(c);else if(s===i)n.push(e)}catch{continue}}}return r(t),n}function E(t,i,n){if(n||k.verbose)console.debug(`[tlsx:${t}] ${i}`)}var oy=wy($y);function ql(){return Kl.env.SUDO_PASSWORD}var tl="[redacted]",ay=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),my=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Ay(t){let i=t.toLowerCase();return ay.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function pn(t){if(Array.isArray(t))return t.map((n)=>pn(n));if(typeof t==="string")return my.test(t)?tl:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(Ay(n)){i[n]=tl;continue}i[n]=pn(r)}return i}function ir(t){return JSON.stringify(pn(t))}function dy(t){let i=ql();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 ni(t,i={}){let n=dy(t);try{let{stdout:r,stderr:e}=await oy(n,{cwd:i.cwd||Kl.cwd(),timeout:i.timeout||30000});return{stdout:r.trim(),stderr:e.trim()}}catch(r){let e=Error(`Failed to execute command: ${t}
61
+ Error: ${r.message}`);throw e.stack=r.stack,e}}function xl(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 xe(t){let i=Jt.join(yy.homedir(),".stacks","ssl"),n=t.basePath&&t.basePath.trim()!==""?t.basePath:k.basePath&&k.basePath.trim()!==""?k.basePath:i,r=t.certPath?Jt.isAbsolute(t.certPath)?t.certPath:Jt.join(n,t.certPath):Jt.join(n,k.certPath),e=t.keyPath?Jt.isAbsolute(t.keyPath)?t.keyPath:Jt.join(n,t.keyPath):Jt.join(n,k.keyPath),f=t.caCertPath?Jt.isAbsolute(t.caCertPath)?t.caCertPath:Jt.join(n,t.caCertPath):Jt.join(n,k.caCertPath);return{certPath:r,keyPath:e,caCertPath:f,basePath:n}}function kl(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 E(S.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function ke(t){let i=t.notBeforeDays??Nt.DEFAULT_NOT_BEFORE_DAYS,n=t.validityDays??(t.validityYears?t.validityYears*365:Nt.DEFAULT_VALIDITY_DAYS);E(S.CERT,"Calculating certificate validity dates",t.verbose);let r=new Date(Date.now()-86400*i*1000),e=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),E(S.CERT,`Validity period: ${r.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:r,notAfter:e}}var _t={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 Vi(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 dt(t,i){let n=Vi(i.length);return Buffer.concat([Buffer.from([t]),n,i])}function Xi(t){let i=t.split(".").map(Number),n=[];n.push(40*i[0]+i[1]);for(let r=2;r<i.length;r++){let e=i[r],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;n.push(...f)}return dt(_t.OID,Buffer.from(n))}function Ye(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 dt(_t.INTEGER,i)}function Dl(t,i=0){return dt(_t.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function Vl(t){return dt(_t.OCTET_STRING,t)}function At(...t){return dt(_t.SEQUENCE,Buffer.concat(t))}function Ey(...t){return dt(_t.SET,Buffer.concat(t))}function Ty(t){return dt(_t.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function Sy(t){return dt(_t.UTF8_STRING,Buffer.from(t,"utf8"))}function Ry(){return Buffer.from([_t.NULL,0])}function il(t,i,n=!0){let r=160|t|(n?0:0),e=Vi(i.length);return Buffer.concat([Buffer.from([r]),e,i])}function nl(t){let i=t.getUTCFullYear();if(i>=2050){let n=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return dt(_t.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(i%100).toString().padStart(2,"0"),r=(t.getUTCMonth()+1).toString().padStart(2,"0"),e=t.getUTCDate().toString().padStart(2,"0"),f=t.getUTCHours().toString().padStart(2,"0"),s=t.getUTCMinutes().toString().padStart(2,"0"),c=t.getUTCSeconds().toString().padStart(2,"0"),l=`${n}${r}${e}${f}${s}${c}Z`;return dt(_t.UTC_TIME,Buffer.from(l,"ascii"))}}function By(t,i){return At(nl(t),nl(i))}function rl(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 e=n.shortName==="C"?Ty(n.value):Sy(n.value),f=At(Xi(r),e);i.push(Ey(f))}return At(...i)}function bl(t){return At(Xi(t),Ry())}function Cy(t){return t.export({type:"spki",format:"der"})}function gy(t){if(t.includes(":")){let i=t;if(t.includes("::")){let e=t.split("::"),f=e[0]?e[0].split(":"):[],s=e[1]?e[1].split(":"):[],c=8-f.length-s.length,l=Array.from({length:c},()=>"0");i=[...f,...l,...s].join(":")}let n=i.split(":"),r=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(n[e]||"0",16);r.writeUInt16BE(f,e*2)}return r}else{let i=t.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(i)}}function Uy(t){let i=[];for(let n of t)if(n.type===2&&n.value){let r=Vi(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=gy(n.ip),e=Vi(r.length);i.push(Buffer.concat([Buffer.from([135]),e,r]))}else if(n.type===6&&n.value){let r=Vi(n.value.length);i.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return At(...i)}function Fy(t,i){if(t){if(i!==void 0)return At(dt(1,Buffer.from([255])),Ye(i));return At(dt(1,Buffer.from([255])))}return At()}function Jy(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 Dl(Buffer.from([i]),n)}function jy(t){let i=[];if(t.serverAuth)i.push(Xi(ut.SERVER_AUTH));if(t.clientAuth)i.push(Xi(ut.CLIENT_AUTH));return At(...i)}function ki(t,i,n){let r=[Xi(t)];if(i)r.push(dt(1,Buffer.from([255])));return r.push(Vl(n)),At(...r)}function Ny(t){let i=[];if(i.push(il(0,Ye(2))),i.push(Ye(t.serialNumber)),i.push(bl(ut.SHA256_WITH_RSA)),i.push(rl(t.issuer)),i.push(By(t.notBefore,t.notAfter)),i.push(rl(t.subject)),i.push(Cy(t.publicKey)),t.extensions){let n=[];if(t.extensions.basicConstraints)n.push(ki(ut.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,Fy(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)n.push(ki(ut.KEY_USAGE,t.extensions.keyUsage.critical??!0,Jy(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)n.push(ki(ut.EXTENDED_KEY_USAGE,!1,jy(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)n.push(ki(ut.SUBJECT_ALT_NAME,!1,Uy(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)n.push(ki(ut.SUBJECT_KEY_IDENTIFIER,!1,Vl(t.extensions.subjectKeyIdentifier)));if(n.length>0)i.push(il(3,At(...n)))}return At(...i)}function _y(t,i){let n=Fi.createSign("SHA256");n.update(t);let r=n.sign(i);return At(t,bl(ut.SHA256_WITH_RSA),Dl(r))}function Yy(t,i){let n=t.toString("base64"),r=[];for(let e=0;e<n.length;e+=64)r.push(n.slice(e,e+64));return`-----BEGIN ${i}-----
62
+ ${r.join(`
63
+ `)}
64
+ -----END ${i}-----
65
+ `}function De(){return Fi.randomBytes(20)}function pl(t=2048){let{privateKey:i,publicKey:n}=Fi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:n}}function Wy(t){let i=t.export({type:"spki",format:"der"});return Fi.createHash("sha1").update(i).digest()}function Pl(t){let i={serialNumber:t.serialNumber||De(),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:Wy(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=Ny(i),r=_y(n,t.signingKey);return{certificate:Yy(r,"CERTIFICATE"),certificateDer:r}}function Xl(t){return t.export({type:"pkcs8",format:"pem"})}function Iy(t){return Fi.createPrivateKey(t)}function Oy(t){let i=new Fi.X509Certificate(t),n=i.publicKey,r=[],e=i.subject.split(`
66
+ `);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)r.push({shortName:s.trim(),value:l.trim()})}return{publicKey:n,subject:r}}async function Ve(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Nt.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=pl(i),e=[{shortName:"C",value:t.countryName||k.countryName},{shortName:"ST",value:t.stateName||k.stateName},{shortName:"L",value:t.localityName||k.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:f,notAfter:s}=ke({validityYears:t.validityYears||Nt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=Pl({serialNumber:De(),notBefore:f,notAfter:s,subject:e,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:Xl(n),notBefore:f,notAfter:s}}async function be(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${ir(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}=Oy(t.rootCA.certificate),n=Iy(t.rootCA.privateKey);E("ca",`Generating ${Nt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let r=Nt.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=pl(r),s=t.commonName||xl(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||k.countryName},{shortName:"ST",value:t.stateName||k.stateName},{shortName:"L",value:t.localityName||k.localityName},{shortName:"O",value:t.organizationName||k.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=ke({validityDays:t.validityDays||Nt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),u=kl(t),$=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},w=t.extKeyUsage||{serverAuth:!0},{certificate:y}=Pl({serialNumber:De(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:w,subjectAltName:u});return{certificate:y,privateKey:Xl(e),notBefore:l,notAfter:h}}function vl(t,i){E(S.STORAGE,`Storing certificate and private key with options: ${ir(i)}`,i?.verbose);let{certPath:n,keyPath:r}=xe({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(S.STORAGE,`Certificate path: ${n}`,i?.verbose),E(S.STORAGE,`Private key path: ${r}`,i?.verbose);let e=We.dirname(n);if(!kt.existsSync(e))E(S.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),kt.mkdirSync(e,{recursive:!0});E(S.STORAGE,"Writing certificate file",i?.verbose),kt.writeFileSync(n,t.certificate);let f=We.dirname(r);if(!kt.existsSync(f))E(S.STORAGE,`Creating private key directory: ${f}`,i?.verbose),kt.mkdirSync(f,{recursive:!0});return E(S.STORAGE,"Writing private key file",i?.verbose),kt.writeFileSync(r,t.privateKey),E(S.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function Ql(t,i){E(S.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=xe({basePath:i?.basePath,caCertPath:i?.caCertPath});E(S.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=We.dirname(n);if(!kt.existsSync(r))E(S.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),kt.mkdirSync(r,{recursive:!0});return E(S.STORAGE,"Writing CA certificate file",i?.verbose),kt.writeFileSync(n,t),E(S.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function Zy(t,i){if(Pn.platform()!=="darwin")return!1;try{let n=el(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return E(S.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(el("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return E(S.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(S.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return E(S.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var Ly={platform:"darwin",async addCertificate(t,i){if(await Zy(t,i?.verbose)){E(S.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Ci.success("Certificate is already trusted in system keychain");return}E(S.TRUST,"Adding certificate to macOS keychain",i?.verbose),await ni(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||k.commonName;E(S.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await ni(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),E(S.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(e){throw E(S.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},My={platform:"win32",async addCertificate(t,i){E(S.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await ni(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||k.commonName;E(S.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await ni(`certutil -delstore -enterprise Root "${r}"`),E(S.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(e){throw E(S.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Hy={platform:"linux",async addCertificate(t,i){E(S.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=Pn.homedir(),r=Nt.LINUX_CERT_DB_FILENAME,e=Nt.LINUX_TRUST_ARGS;E(S.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let f=_e(n,r);if(f.length===0){Ci.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(S.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(S.TRUST,`Attempting to delete existing cert for ${k.commonName}`,i?.verbose),await ni(`certutil -d sql:${s} -D -n ${k.commonName}`)}catch(c){E(S.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(S.TRUST,`Adding new certificate to ${s}`,i?.verbose),await ni(`certutil -d sql:${s} -A -t ${e} -n ${k.commonName} -i ${t}`),Ci.info(`Cert added to ${s}`)}},async removeCertificate(t,i,n){let r=n||k.commonName;E(S.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let e=Pn.homedir(),f=Nt.LINUX_CERT_DB_FILENAME;E(S.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=_e(e,f);if(s.length===0){Ci.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(S.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await ni(`certutil -d sql:${c} -D -n "${r}"`),Ci.info(`Cert removed from ${c}`)}catch(l){E(S.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},zy={darwin:Ly,win32:My,linux:Hy};async function pe(t,i,n){E(S.TRUST,`Adding certificate to system trust store with options: ${ir(n)}`,n?.verbose),E(S.TRUST,"Storing certificate and private key",n?.verbose);let r=vl(t,n);E(S.TRUST,"Storing CA certificate",n?.verbose);let e=Ql(i,n),f=Pn.platform();E(S.TRUST,`Detected platform: ${f}`,n?.verbose);let s=zy[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(S.TRUST,`Error: ${c}`,n?.verbose),Error(c)}return await s.addCertificate(e,n),E(S.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as Mf}from"node:os";import{join as Hf,resolve as hd}from"node:path";import{existsSync as tc,statSync as ic}from"fs";import{existsSync as Gy,mkdirSync as BA,readdirSync as CA,readFileSync as Ky,writeFileSync as gA}from"fs";import{homedir as Ji}from"os";import{dirname as JA,resolve as Ct}from"path";import Or from"process";import{existsSync as nc,statSync as rc}from"fs";import{existsSync as mf,mkdirSync as qy,readdirSync as xy,writeFileSync as ky}from"fs";import{homedir as ji}from"os";import{dirname as ec,resolve as yt}from"path";import ui from"process";import{join as Dy,relative as Vy,resolve as fc}from"path";import Rr from"process";import{existsSync as Kc,mkdirSync as MA,readdirSync as HA,writeFileSync as zA}from"fs";import{homedir as Pe}from"os";import{dirname as qA,resolve as $t}from"path";import tn from"process";import{join as by,relative as py,resolve as sc}from"path";import Br from"process";import{existsSync as qc,mkdirSync as bA,readdirSync as pA,writeFileSync as PA}from"fs";import{dirname as vA,resolve as Cr}from"path";import Af from"process";import{Buffer as ei}from"buffer";import{createCipheriv as Py,createDecipheriv as Xy,randomBytes as Xe}from"crypto";import{closeSync as ve,createReadStream as lc,createWriteStream as vy,existsSync as Qe,fsyncSync as cc,openSync as hc,writeFileSync as Qy}from"fs";import{access as t0,constants as uc,mkdir as i0,readdir as nr,rename as $c,stat as Ni,unlink as rr,writeFile as tf}from"fs/promises";import{join as _i}from"path";import ft from"process";import{pipeline as n0}from"stream/promises";import{createGzip as yc}from"zlib";import Yi from"process";import Pt from"process";import{Buffer as Vt}from"buffer";import{createCipheriv as r0,createDecipheriv as e0,randomBytes as nf}from"crypto";import{closeSync as rf,createReadStream as wc,createWriteStream as f0,existsSync as er,fsyncSync as oc,openSync as ac,writeFileSync as s0}from"fs";import{access as l0,constants as mc,mkdir as c0,readdir as fr,rename as Ac,stat as Wi,unlink as sr,writeFile as ef}from"fs/promises";import{isAbsolute as h0,join as Ii,resolve as u0}from"path";import B from"process";import{pipeline as $0}from"stream/promises";import{createGzip as dc}from"zlib";import Oi from"process";import Xt from"process";import lr from"process";import{existsSync as cr}from"fs";import{resolve as ff}from"path";import{existsSync as y0}from"fs";import{existsSync as w0,readdirSync as o0}from"fs";import{extname as sf,resolve as Ec}from"path";import a0 from"process";import{join as m0,relative as A0,resolve as Tc}from"path";import gr from"process";import{Buffer as bt}from"buffer";import{createCipheriv as d0,createDecipheriv as E0,randomBytes as lf}from"crypto";import{closeSync as cf,createReadStream as Sc,createWriteStream as T0,existsSync as hr,fsyncSync as Rc,openSync as Bc,writeFileSync as S0}from"fs";import{access as R0,constants as Cc,mkdir as B0,readdir as ur,rename as gc,stat as Zi,unlink as $r,writeFile as hf}from"fs/promises";import{isAbsolute as C0,join as Li,resolve as g0}from"path";import C from"process";import{pipeline as U0}from"stream/promises";import{createGzip as Uc}from"zlib";import Mi from"process";import vt from"process";import wr from"process";import{existsSync as or}from"fs";import{resolve as af}from"path";import{existsSync as Dw}from"fs";class zc{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 e=this.generateKey(t,n),f=r??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),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(!tc(t))return!0;return ic(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 e=tc(n)?ic(n):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},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,e)=>r+e.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 Gc{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-r;return this.recordMetric({operation:t,duration:s,timestamp:e,...n}),f}catch(f){let s=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...n}),f}}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((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((e)=>e.duration),r=n.reduce((e,f)=>e+f,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 Sr=new zc,Jf=new Gc;var F0=Object.defineProperty,J0=(t)=>t;function j0(t,i){this[t]=J0.bind(null,i)}var N0=(t,i)=>{for(var n in i)F0(t,n,{get:i[n],enumerable:!0,configurable:!0,set:j0.bind(i,n)})},_0=(t,i)=>()=>(t&&(i=t(t=0)),i),xc={};N0(xc,{withErrorRecovery:()=>Vc,tryLoadConfig:()=>tw,loadConfigWithResult:()=>v0,loadConfig:()=>vc,isRetryableError:()=>D0,isConfigNotFoundError:()=>k0,isBunfigError:()=>bc,globalPerformanceMonitor:()=>en,globalCache:()=>Hi,getEnvOrDefault:()=>V0,generateConfigTypes:()=>iw,defaultGeneratedDir:()=>sh,defaultConfigDir:()=>fh,deepMergeWithArrayStrategy:()=>Wf,deepMerge:()=>pc,createLibraryConfig:()=>nw,config:()=>Q0,bunfigPlugin:()=>rw,applyEnvVarsToConfig:()=>Qi,TypeGenerationError:()=>Cf,SchemaValidationError:()=>rn,PluginError:()=>Uf,PerformanceMonitor:()=>Nf,FileSystemError:()=>Bf,ErrorFactory:()=>fi,EnvVarError:()=>_r,EnvProcessor:()=>Zr,ConfigValidator:()=>If,ConfigValidationError:()=>Sf,ConfigNotFoundError:()=>Nr,ConfigMergeError:()=>Rf,ConfigLoader:()=>Of,ConfigLoadError:()=>nn,ConfigFileLoader:()=>Lr,ConfigCache:()=>jf,CacheUtils:()=>th,BunfigError:()=>Et,BrowserConfigError:()=>gf,ArrayMergeStrategies:()=>rh});class jf{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 e=this.generateKey(t,n),f=r??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),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(!nc(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 e=nc(n)?rc(n):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},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,e)=>r+e.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 Nf{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-r;return this.recordMetric({operation:t,duration:s,timestamp:e,...n}),f}catch(f){let s=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...n}),f}}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((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((e)=>e.duration),r=n.reduce((e,f)=>e+f,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 Y0(t,i={}){let r=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return r?`${t}:${r}`:t}function W0(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function I0(t){return t.getStats().size*2}function _f(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&K(i[0])&&"id"in i[0]&&i[0].id===3&&K(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(K(i)&&K(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(K(t)&&"arr"in t&&Array.isArray(t.arr)&&K(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&K(i[0])&&K(t[0])){let r=[...i];for(let e of t)if(K(e)&&"name"in e){if(!r.find((s)=>K(s)&&("name"in s)&&s.name===e.name))r.push(e)}else if(K(e)&&"path"in e){if(!r.find((s)=>K(s)&&("path"in s)&&s.path===e.path))r.push(e)}else if(!r.some((f)=>Ur(f,e)))r.push(e);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}if(!K(i)||!K(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let e=i[r];if(e===null||e===void 0)continue;else if(K(e)&&K(n[r]))n[r]=_f(n[r],e);else if(Array.isArray(e)&&Array.isArray(n[r]))if(e.length>0&&n[r].length>0&&K(e[0])&&K(n[r][0])){let f=[...e];for(let s of n[r])if(K(s)&&"name"in s){if(!f.find((l)=>K(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(K(s)&&"path"in s){if(!f.find((l)=>K(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Ur(c,s)))f.push(s);n[r]=f}else if(e.every((f)=>typeof f==="string")&&n[r].every((f)=>typeof f==="string")){let f=[...e];for(let s of n[r])if(!f.includes(s))f.push(s);n[r]=f}else n[r]=e;else n[r]=e}return n}function Ur(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(!Ur(t[n],i[n]))return!1;return!0}if(K(t)&&K(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Ur(t[e],i[e]))return!1}return!0}return!1}function K(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function O0(t,i){if(!qc(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 _f(i,r)}catch{return null}}catch{return null}}async function Z0({name:t="",cwd:i,defaultConfig:n}){let r=i||Af.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Cr(r,`${s}${c}`),h=await O0(l,n);if(h!==null)return h}try{let s=Cr(r,"package.json");if(qc(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return _f(n,l)}catch{}}}catch{}return n}function L0(t,i={}){let n=Br.cwd();while(n.includes("storage"))n=sc(n,"..");let r=sc(n,t||"");if(i?.relative)return py(Br.cwd(),r);return r}async function M0(){try{let t=await Z0({name:"clarity",defaultConfig:Ar,cwd:Br.cwd(),endpoint:"",headers:{}});return{...Ar,...t}}catch{return Ar}}function x(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function H0(){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 kc{async format(t){let i=await H0(),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:Yi.pid,hostname:i(),environment:Yi.env.NODE_ENV||"development",platform:Yi.platform,version:Yi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yi.env.NODE_ENV||Yi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Fr{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={...Ef},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new kc,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??ft.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...dr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...dr};return{...dr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ef.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 e,f=0,s=3,c=1000;while(f<s)try{try{try{await t0(this.config.logDirectory,uc.F_OK|uc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await i0(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:ei.from(t);try{if(!Qe(this.currentLogFile))await tf(this.currentLogFile,"",{mode:420});if(e=hc(this.currentLogFile,"a",420),Qy(e,l,{flag:"a"}),cc(e),e!==void 0)ve(e),e=void 0;if((await Ni(this.currentLogFile)).size===0){if(await tf(this.currentLogFile,l,{flag:"w",mode:420}),(await Ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let $=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,$);let w=c*2**f;await new Promise((y)=>setTimeout(y,w)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{ve(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,$=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 _i(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 _i(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return _i(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(x())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((e)=>{console.error("Error rotating keys:",e)})},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 e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Xe(16).toString("hex")}generateKey(){return Xe(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=Xe(16),r=Py("aes-256-gcm",i,n),e=ei.concat([r.update(t,"utf8"),r.final()]),f=r.getAuthTag();return{encrypted:ei.concat([n,e,f]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=yc(),e=[];r.on("data",(f)=>e.push(f)),r.on("end",()=>i(ei.from(ei.concat(e)))),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;let t=await Ni(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await nr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${n}.${s}`;if(await Ni(n).catch(()=>null))try{if(await $c(n,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await rr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await tf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=n.replace(/\.log$/,`-${e}.log`);if(await Ni(n).catch(()=>null))await $c(n,f)}if(this.currentLogFile=r,i.maxFiles){let f=(await nr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await rr(_i(this.config.logDirectory,s))}}}async compressLogFile(t,i){let n=lc(t),r=vy(i),e=yc();await n0(n,e,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()})),Qe(this.currentLogFile))try{let t=hc(this.currentLogFile,"r+");cc(t),ve(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 nr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await rr(_i(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?z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:e,level:f,showTimestamp:s=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(i);if(f==="warning")y.push("WARN");else if(f==="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(e),y.join(" ")}let l=ft.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${n} ${e}`;else if(f==="info"||f==="success")h=`${n} ${r} ${e}`;else h=`${n} ${r} ${z.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,l-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let n=/%([sdijfo%])/g,r=0,e=t.replace(n,(f,s)=>{if(s==="%")return"%";if(r>=i.length)return f;let c=i[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(r<i.length)e+=` ${i.slice(r).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...n){let r=new Date,e=this.formatConsoleTimestamp(r),f=this.formatFileTimestamp(r),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,n);if(this.fancy&&!x()){let h=ih[t],u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",$;switch(t){case"debug":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:z.gray(s),level:t}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:z.green(s),level:t}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error($),c){let w=c.split(`
67
+ `);for(let y of w)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:z.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!x()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
68
+ `;if(c)l+=`${c}
69
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!x()){let n=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:z.blue("◐"),tag:n,message:`${z.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),e=Math.round(r-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
70
+ `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!x()){let u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:z.green("✓"),tag:u,message:`${f}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!x())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 Fr(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(!Qe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return lc(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"),e=r.slice(0,16),f=r.slice(-16),s=r.slice(16,-16),c=Xy("aes-256-gcm",n,e);return c.setAuthTag(f),ei.concat([c.update(s),c.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 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);if(this.fancy&&!x()){let f=t.split(`
71
+ `),s=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((u)=>{let $=" ".repeat(s-u.length-2);return`│ ${u}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(l),showTimestamp:!1}))}else if(!x())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let e=`${r} ${this.environment}.INFO: [BOX] ${t}
72
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(x())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${z.cyan("?")} ${t} (y/n) `);let n=(r)=>{let e=r.toString().trim().toLowerCase();ft.stdin.removeListener("data",n);try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!1)}catch{}ft.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!0)}catch{}ft.stdin.resume(),ft.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 s=/%([sdijfo%])/g,c=0;if(n=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let u=i[c++];switch(h){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 l}}),c<i.length)n+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!x()){let s=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=z.blue("◐");console.error(`${c} ${s} ${z.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
73
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||x()||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:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;ft.stdout.write(`${"\r".padEnd(ft.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||x()||!ft.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),e=t.barLength-r,f=z.green("━".repeat(r)),s=z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${n}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||n===100?z.green("✓"):z.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${l}${h}`,y=ft.stdout.columns||80,m=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${m}`,ft.stdout.write(t.lastRenderedLine),i)ft.stdout.write(`
74
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||x()||!ft.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 nr(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=_i(this.config.logDirectory,r);if(t.before)try{if((await Ni(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await rr(r),console.warn(`Deleted log file: ${r}`)}catch(e){console.error(`Failed to delete log file ${r}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function mr(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 e of t)if(Z(e)&&"name"in e){if(!r.find((s)=>Z(s)&&("name"in s)&&s.name===e.name))r.push(e)}else if(Z(e)&&"path"in e){if(!r.find((s)=>Z(s)&&("path"in s)&&s.path===e.path))r.push(e)}else if(!r.some((f)=>Jr(f,e)))r.push(e);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);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 e=i[r];if(e===null||e===void 0)continue;else if(Z(e)&&Z(n[r]))n[r]=mr(n[r],e);else if(Array.isArray(e)&&Array.isArray(n[r]))if(e.length>0&&n[r].length>0&&Z(e[0])&&Z(n[r][0])){let f=[...e];for(let s of n[r])if(Z(s)&&"name"in s){if(!f.find((l)=>Z(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(Z(s)&&"path"in s){if(!f.find((l)=>Z(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Jr(c,s)))f.push(s);n[r]=f}else if(e.every((f)=>typeof f==="string")&&n[r].every((f)=>typeof f==="string")){let f=[...e];for(let s of n[r])if(!f.includes(s))f.push(s);n[r]=f}else n[r]=e;else n[r]=e}return n}function Yf(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:mr(t,i);if(Array.isArray(t))return n==="replace"?i:mr(t,i);if(!Z(i)||!Z(t))return i;let r={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=r[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(n==="replace")r[e]=f;else r[e]=mr(s,f);else if(Z(f)&&Z(s))r[e]=Yf(s,f,n);else r[e]=f}return r}function Jr(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(!Jr(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 e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Jr(t[e],i[e]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function yr(t,i,n="replace"){if(!Kc(t))return null;try{let r=await import(t),e=r.default||r;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Yf(i,e,n)}catch{return null}}catch{return null}}function z0(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let $=[...c,h],w=(o)=>o.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${r}_${$.map(w).join("_")}`,m=`${r}_${$.map((o)=>o.toUpperCase()).join("_")}`;if(n)lt.info(`Checking environment variable ${y} for config ${t}.${$.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[h]=f(u,$);else{let o=tn.env[y]||tn.env[m];if(o!==void 0){if(n)lt.info(`Using environment variable ${o?y:m} for config ${t}.${$.join(".")}`);if(typeof u==="number")l[h]=Number(o);else if(typeof u==="boolean")l[h]=o.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(o);if(Array.isArray(A))l[h]=A;else l[h]=o.split(",").map((d)=>d.trim())}catch{l[h]=o.split(",").map((A)=>A.trim())}else l[h]=o}}}return l}return f(e)}async function G0({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?z0(t,e,f):e,h=n||tn.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let $=[t,`.${t}`].filter(Boolean),w=[`${t}.config`,`.${t}.config`].filter(Boolean),y=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],o=Array.from(new Set([h,$t(h,"config"),$t(h,".config"),r?$t(h,r):void 0].filter(Boolean)));for(let A of o){if(f)lt.info(`Searching for configuration in: ${A}`);let T=[$t(h,"config"),$t(h,".config")].concat(r?[$t(h,r)]:[]).includes(A)?[...$,...w,...y,...m]:[...w,...$,...m,...y];for(let N of T)for(let _ of u){let M=$t(A,`${N}${_}`),yi=await yr(M,l,c);if(yi!==null){if(f)lt.success(`Configuration loaded from: ${M}`);return yi}}}if(t){let A=$t(Pe(),".config",t),d=["config",`${t}.config`];if(i)d.push(`${i}.config`);if(f)lt.info(`Checking user config directory: ${A}`);for(let T of d)for(let N of u){let _=$t(A,`${T}${N}`),M=await yr(_,l,c);if(M!==null){if(f)lt.success(`Configuration loaded from user config directory: ${_}`);return M}}}if(t){let A=$t(Pe(),".config"),d=[`.${t}.config`];if(i)d.push(`.${i}.config`);if(f)lt.info(`Checking user config directory for dotfile configs: ${A}`);for(let T of d)for(let N of u){let _=$t(A,`${T}${N}`),M=await yr(_,l,c);if(M!==null){if(f)lt.success(`Configuration loaded from user config directory dotfile: ${_}`);return M}}}if(t){let A=Pe(),d=[`.${t}.config`,`.${t}`];if(i)d.push(`.${i}.config`),d.push(`.${i}`);if(f)lt.info(`Checking user home directory for dotfile configs: ${A}`);for(let T of d)for(let N of u){let _=$t(A,`${T}${N}`),M=await yr(_,l,c);if(M!==null){if(f)lt.success(`Configuration loaded from user home directory: ${_}`);return M}}}try{let A=$t(h,"package.json");if(Kc(A)){let d=await import(A),T=d[t];if(!T&&i){if(T=d[i],T&&f)lt.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)lt.success(`Configuration loaded from package.json: ${T===d[t]?t:i}`);return Yf(l,T,c)}catch(N){if(f)lt.warn("Failed to merge package.json config:",N)}}}catch(A){if(f)lt.warn("Failed to load package.json:",A)}if(f)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function K0(t,i={}){let n=Rr.cwd();while(n.includes("storage"))n=fc(n,"..");let r=fc(n,t||"");if(i?.relative)return Vy(Rr.cwd(),r);return r}async function q0(){try{let t=await G0({name:"clarity",alias:"logging",defaultConfig:Er,cwd:Rr.cwd()});return{...Er,...t||{}}}catch{return Er}}function P(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function x0(){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 Dc{async format(t){let i=await x0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Oi.pid,hostname:i(),environment:Oi.env.NODE_ENV||"development",platform:Oi.platform,version:Oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oi.env.NODE_ENV||Oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class jr{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={...Tf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Dc,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??B.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tr};return{...Tr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Tf.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 n=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await l0(this.config.logDirectory,mc.F_OK|mc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await c0(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(!er(this.currentLogFile))await ef(this.currentLogFile,"",{mode:420});if(e=ac(this.currentLogFile,"a",420),s0(e,l,{flag:"a"}),oc(e),e!==void 0)rf(e),e=void 0;if((await Wi(this.currentLogFile)).size===0){if(await ef(this.currentLogFile,l,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let $=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,$);let w=c*2**f;await new Promise((y)=>setTimeout(y,w)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{rf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,$=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Ii(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 Ii(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ii(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 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((e)=>{console.error("Error rotating keys:",e)})},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 e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return nf(16).toString("hex")}generateKey(){return nf(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=nf(16),r=r0("aes-256-gcm",i,n),e=Vt.isBuffer(t)?t:Vt.from(t,"utf8"),f=r.update(e),s=r.final(),c=f.length+s.length,l=r.getAuthTag(),h=Vt.allocUnsafe(16+c+16);return n.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=dc(),e=[];r.on("data",(f)=>e.push(f)),r.on("end",()=>i(Vt.from(Vt.concat(e)))),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 Wi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await fr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${n}.${s}`;if(await Wi(n).catch(()=>null))try{if(await Ac(n,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await sr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await ef(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=n.replace(/\.log$/,`-${e}.log`);if(await Wi(n).catch(()=>null))await Ac(n,f)}if(this.currentLogFile=r,i.maxFiles){let f=(await fr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await sr(Ii(this.config.logDirectory,s))}}}async compressLogFile(t,i){let n=wc(t),r=f0(i),e=dc();await $0(n,e,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=ac(this.currentLogFile,"r+");oc(t),rf(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 i=(await fr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await sr(Ii(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()?U.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof B.env.NO_COLOR<"u",i=B.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof B.stderr<"u"&&B.stderr.isTTY||typeof B.stdout<"u"&&B.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:e,level:f,showTimestamp:s=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(i);if(f==="warning")y.push("WARN");else if(f==="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(e),y.join(" ")}let l=B.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${n} ${e}`;else if(f==="info"||f==="success")h=`${n} ${r} ${e}`;else h=`${n} ${r} ${U.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,l-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let n=/%([sdijfo%])/g,r=0,e=t.replace(n,(f,s)=>{if(s==="%")return"%";if(r>=i.length)return f;let c=i[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(r<i.length)e+=` ${i.slice(r).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,e)=>{let f=U.underline(U.blue(r)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(n,r)=>U.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>U.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>U.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>U.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>U.strikethrough(r)),i}supportsHyperlinks(){if(P())return!1;let t=B.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=B.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(h0(i)||i.startsWith("./")||i.startsWith("../"))i=u0(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){let r=new Date,e=this.formatConsoleTimestamp(r),f=this.formatFileTimestamp(r),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,n);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":nh[t],w=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:U.gray(l),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:U.green(l),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.error(y),c){let m=c.split(`
75
+ `);for(let o of m)if(o.trim()&&!o.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:U.gray(` ${o}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
76
+ `;if(c)u+=`${c}
77
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let n={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!P()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!P()&&B.stdout.isTTY)B.stdout.write(`
78
+ `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":U.blue("◐"),tag:n,message:`${U.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),e=Math.round(r-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
79
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":U.green("✓"),tag:u,message:`${f}${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 jr(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 wc(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"),e=r.subarray(0,16),f=r.subarray(r.length-16),s=r.subarray(16,r.length-16),c=e0("aes-256-gcm",n,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,$=Vt.allocUnsafe(u);return l.copy($,0),h.copy($,l.length),$.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:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
80
+ `),l=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:n,message:U.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:U.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:n,message:U.cyan(u),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${f}`);let s=`${r} ${this.environment}.INFO: [BOX] ${f}
81
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${U.cyan("?")} ${t} (y/n) `);let n=(r)=>{let e=r.toString().trim().toLowerCase();B.stdin.removeListener("data",n);try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!1)}catch{}B.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!0)}catch{}B.stdin.resume(),B.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(n=t.replace(l,(u,$)=>{if($==="%")return"%";if(h>=i.length)return u;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return u}}),h<i.length)n+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:e}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${U.blue("◐")} `;console.error(`${h}${l} ${U.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
82
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!B.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),e=t.barLength-r,f=U.green("━".repeat(r)),s=U.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${n}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||n===100?U.green("✓"):U.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${U.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${l}${h}`,y=B.stdout.columns||80,m=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${m}`,B.stdout.write(t.lastRenderedLine),i)B.stdout.write(`
83
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!B.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 fr(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=Ii(this.config.logDirectory,r);if(t.before)try{if((await Wi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);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(e){console.error(`Failed to delete log file ${r}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Vc(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=n;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===n||!e(s))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function bc(t){return t instanceof Et}function k0(t){return t instanceof Nr}function D0(t){if(bc(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 Zr{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:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=n,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return en.track("applyEnvironmentVariables",h,{configName:t});return h()}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[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${n}_${c.join("_")}`,h=r.useBackwardCompatibility?`${n}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,n,r);else{let u=lr.env[l]||(h?lr.env[h]:void 0);if(u!==void 0){if(r.verbose){let $=lr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,r.customParsers,r.configName)}catch($){if($ instanceof _r)throw $;throw fi.envVar(l,u,typeof f,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,e){for(let[f,s]of Object.entries(r))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw fi.envVar(n,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,e]of Object.entries(lr.env))if(r.startsWith(n)&&e!==void 0)i[r]=e;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(e){r.push(`Cannot parse value "${i}" as ${n}: ${e}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:e="text"}=n,f=r||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,n,r){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${n}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,n,r);else r.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}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}:
84
+
85
+ `;for(let r of t)n+=`${r.key}
86
+ `,n+=` Type: ${r.type}
87
+ `,n+=` Description: ${r.description}
88
+ `,n+=` Example: ${r.example}
89
+
90
+ `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
91
+
92
+ `;n+=`| Variable | Type | Description | Example |
93
+ `,n+=`|----------|------|-------------|----------|
94
+ `;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
95
+ `;return n}}function V0(t,i){let n=Qc("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function pc(t,i,n={}){return Pc(t,i,n,new WeakMap)}function Pc(t,i,n,r){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=n;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Xc(t,i,e,r);if(!gt(i)||!gt(t))return i;return X0(t,i,n,r)}function Xc(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 b0(t,i);case"smart":return p0(t,i,r);default:return i}return i}function b0(t,i){let n=[...i];for(let r of t)if(!n.some((e)=>df(e,r)))n.push(r);return n}function p0(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(gt(i[0])&&gt(t[0]))return P0(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}function P0(t,i,n){let r=[...i];for(let e of t){if(!gt(e)){r.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(r.find((h)=>gt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)r.push(e)}return r}function X0(t,i,n,r){let e=i;if(gt(e)&&r.has(e))return r.get(e);let f={...t};if(gt(e))r.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(n.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(gt(c)&&gt(l))f[s]=Pc(l,c,n,r);else if(Array.isArray(c)||Array.isArray(l))f[s]=Xc(l,c,n.arrayMergeMode||"smart",r);else f[s]=c}return f}function Wf(t,i,n="replace"){return pc(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function df(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(!df(t[n],i[n]))return!1;return!0}if(gt(t)&&gt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!df(t[e],i[e]))return!1}return!0}return!1}function gt(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:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=n;if(e){let h=Hi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!cr(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new nn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new nn(t,Error("Configuration must export a valid object"),"unknown");let A={config:Wf(i,$,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Hi.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?fi.configLoad(t,h):fi.configLoad(t,Error(String(h)))}};if(s)return en.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let e=await this.loadFromPath(r,i,n);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(n.verbose)console.warn(`Failed to load config from ${r}:`,e)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),e=[];for(let f of r)for(let s of this.extensions)e.push(ff(i,`${f}${s}`));return e}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 Vc(async()=>{return cr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!cr(t))return r;if(i||n){let e=this.generateNamePatterns(i||"",n);for(let f of e)for(let s of this.extensions){let c=ff(t,`${f}${s}`);if(await this.checkFileAccess(c))r.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=ff(t,s);if(await this.checkFileAccess(c))r.push(c)}}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(!cr(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:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}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 e=await this.loadFromPath(r,{},i);if(e)n.set(r,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${r}:`,e)}})),n}}class If{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=n,h=async()=>{let u=[],$=[],w={stopOnFirstError:r,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await en.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,n){try{if(!y0(i))throw new rn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),e=r.default||r;if(Array.isArray(e))return this.validateWithRules(t,e,n);else return this.validateWithJSONSchema(t,e,n)}catch(r){throw new rn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],e=[];return this.validateObjectAgainstSchema(t,i,"",r,e,n),{isValid:r.length===0,errors:r,warnings:e}}validateObjectAgainstSchema(t,i,n,r,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(r.push({path:n,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.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"}),f.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 s=0;s<t.length;s++){let c=n?`${n}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,r,e,f),f.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(r.push({path:n?`${n}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=n?`${n}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,r,e,f),f.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(r.push(...c),n.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:e}}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 e=Array.isArray(t)?"array":typeof t;if(e!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,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 e=i.validator(t);if(e)r.push({path:n,message:i.message||e,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let e of n)if(r&&typeof r==="object"&&e in r)r=r[e];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,e,f,s]=r;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}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:eh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Of{fileLoader=new Lr;envProcessor=new Zr;validator=new If;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:e,validate:f,...s}=t;try{if(n?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,n)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),$=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),w=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw l;if($&&(!h||!w))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(n?.enabled&&c)this.cacheResult(s.name||"",c,n,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Wt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Wt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||ui.cwd(),w=[],y=await this.loadLocalConfiguration(r,e,$,s,c,h,u,l,n);if(y)return w.push(...this.getLocalSearchPaths(r,e,$,s)),this.finalizeResult(y,w,l,r,u);let m=await this.loadHomeConfiguration(r,e,c,h,u,l);if(m)return w.push(...this.getHomeSearchPaths(r,e)),this.finalizeResult(m,w,l,r,u);let o=await this.loadPackageJsonConfiguration(r,e,$,c,h,u,l);if(o)return w.push(yt($,"package.json")),this.finalizeResult(o,w,l,r,u);if(w.push(...this.getAllSearchPaths(r,e,$,s)),i)throw fi.configNotFound(r,w,e);return{...await this.applyEnvironmentVariables(r,c,l,u),warnings:[`No configuration file found for "${r}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,e,f,s,c,l){let h=c?Qi(t,e,s):e,u=this.getLocalDirectories(n,r);for(let $ of u){if(s)Wt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(y){if(s)Wt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,e,f){if(!t)return null;let s=f?Qi(t,n,e):n,c=[yt(ji(),".config",t),yt(ji(),".config"),ji()];for(let l of c){if(e)Wt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:r,verbose:e});if(u){if(e)Wt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,n,r,e,f,s){let c=s?Qi(t,r,f):r;try{let l=yt(n,"package.json");if(!mf(l))return null;let h=await import(l),u=h[t],$=t;if(!u&&i)u=h[i],$=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Wt.success(`Configuration loaded from package.json: ${$}`);return{config:Wf(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Wt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Qi(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let e=[];if(n){let f=n(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw fi.configValidation(r||"unknown",e,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Hi.get(n)||null}cacheResult(t,i,n,r){let e=this.generateCacheKey(t,r);Hi.set(e,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 e=[];return e.push(...this.getLocalSearchPaths(t,i,n,r)),e.push(...this.getHomeSearchPaths(t,i)),e.push(yt(n,"package.json")),e}getLocalSearchPaths(t,i,n,r){let e=this.getLocalDirectories(n,r),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let n=[yt(ji(),".config",t),yt(ji(),".config"),ji()],r=[];for(let e of n)r.push(...this.fileLoader.generateConfigPaths(t,e,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function Fc(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 v0(t){return Qt.loadConfig({...t,__strictErrorHandling:!0})}async function vc(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 e=r instanceof Error?r.name:"UnknownError",f=r instanceof Error?r.message:String(r);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Wt.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 Q0(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"&&Fc(n)))return(await Qt.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await Qt.loadConfig({...t,cwd:t.cwd||ui.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Fc(i)))return(await Qt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function tw(t,i,n="replace"){let r=new Lr;try{let e=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function Qi(t,i,n=!1){let r=new Zr,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((o)=>o.toUpperCase()).join("")}`,`${e}_${$.map((o)=>o.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,m;for(let o of w)if(y=ui.env[o],y!==void 0){m=o;break}if(y!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let o=Number(y);if(!Number.isNaN(o))l[h]=o}else if(Array.isArray(u))try{l[h]=JSON.parse(y)}catch{l[h]=y.split(",").map((o)=>o.trim())}else l[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,$)}return l}return f(i)}function iw(t){let i=yt(ui.cwd(),t.configDir),n=yt(ui.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!mf(ec(r)))qy(ec(r),{recursive:!0,mode:511});let e=mf(i)?xy(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Nw}
96
+ export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
97
+ `;ky(r,f,{mode:438})}function nw(t){let i=null,n=null,r=()=>{if(!n)n=vc(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)Wt.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return n},e="defaultConfig"in t?t.defaultConfig:{};return i=e,r(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return r(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function rw(t){let i=Ec(a0.cwd(),t?.configDir||"./config");function n(){if(!w0(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=o0(i).filter((l)=>e.has(sf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let u=sf(h).toLowerCase(),$=c.get(l);if(!$){c.set(l,h);continue}let w=sf($).toLowerCase();if(f.indexOf(u)<f.indexOf(w))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function r(){let e=n(),f=e.map((h)=>h.base),s=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
98
+ ${e.map((h)=>{let u=Ec(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${u}').default`}).join(`,
99
+ `)}
100
+ }`:"Record<string, any>";return`export type ConfigNames = ${s}
101
+ export type ConfigByName = ${c}
102
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
103
+ export type ConfigOf = Config
104
+ `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Qc,Hi,en,th,ew,fw,Jc,Ar,Ef,st,z,sw,jc,lw,Nc,cw,hw,uf,uw,_c,Yc,$f,$w,yw,ww,ow,dr,ih,aw,lt,mw,Aw,Wc,Er,Tf,X,U,dw,Ic,Ew,Oc,Tw,Sw,yf,Rw,Zc,Lc,Bw,wf,Cw,gw,Uw,Fw,Jw,Tr,nh,jw,Nw="0.15.6",Et,Nr,nn,Sf,Rf,_r,Bf,Cf,rn,gf,Uf,fi,rh,eh,Wt,Qt,fh,sh,_w=_0(async()=>{Qc=import.meta.require,Hi=new jf,en=new Nf,th={createKey:Y0,isEquivalent:W0,estimateMemoryUsage:I0},ew=Cr(Af.cwd(),"config"),fw=Cr(Af.cwd(),"src/generated"),Jc=Br.env.CLARITY_LOG_DIR||by(L0(),"logs"),Ar={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Jc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ef=await M0(),st={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"},z=st,sw=st.red,jc=st.green,lw=st.yellow,Nc=st.blue,cw=st.magenta,hw=st.cyan,uf=st.white,uw=st.gray,_c=st.bgRed,Yc=st.bgYellow,$f=st.bold,$w=st.dim,yw=st.italic,ww=st.underline,ow=st.reset,dr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ih={debug:"\uD83D\uDD0D",info:Nc("ℹ"),success:jc("✓"),warning:Yc(uf($f(" WARN "))),error:_c(uf($f(" ERROR ")))},aw=new Fr("stacks"),lt=new Fr("bunfig",{showTags:!0}),mw=$t(tn.cwd(),"config"),Aw=$t(tn.cwd(),"src/generated"),Wc=Rr.env.CLARITY_LOG_DIR||Dy(K0(),"logs"),Er={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Wc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Tf=await q0(),X={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"},U=X,dw=X.red,Ic=X.green,Ew=X.yellow,Oc=X.blue,Tw=X.magenta,Sw=X.cyan,yf=X.white,Rw=X.gray,Zc=X.bgRed,Lc=X.bgYellow,Bw=X.bgGray,wf=X.bold,Cw=X.dim,gw=X.italic,Uw=X.underline,Fw=X.strikethrough,Jw=X.reset,Tr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nh={debug:"\uD83D\uDD0D",info:Oc("ℹ"),success:Ic("✓"),warning:Lc(yf(wf(" WARN "))),error:Zc(yf(wf(" ERROR ")))},jw=new jr("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}`}},Nr=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,n,r){let e=r?` or alias "${r}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:r,searchPaths:n,searchPathCount:n.length})}},nn=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}},Sf=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})}},Rf=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,n,r,e){super(`Failed to merge configuration from "${i}" with "${n}": ${r.message}`,{sourcePath:i,targetPath:n,configName:e,originalError:r.name,originalMessage:r.message});this.cause=r}},_r=class extends Et{code="ENV_VAR_ERROR";constructor(i,n,r,e){super(`Failed to parse environment variable "${i}" with value "${n}" as ${r}`,{envKey:i,envValue:n,expectedType:r,configName:e})}},Bf=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}},Cf=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}},rn=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})}},gf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,n,r,e){super(`Failed to fetch configuration from "${i}": ${n} ${r}`,{endpoint:i,status:n,statusText:r,configName:e})}},Uf=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}},fi={configNotFound(t,i,n){return new Nr(t,i,n)},configLoad(t,i,n){return new nn(t,i,n)},configValidation(t,i,n){return new Sf(t,i,n)},configMerge(t,i,n,r){return new Rf(t,i,n,r)},envVar(t,i,n,r){return new _r(t,i,n,r)},fileSystem(t,i,n){return new Bf(t,i,n)},typeGeneration(t,i,n){return new Cf(t,i,n)},schemaValidation(t,i,n){return new rn(t,i,n)},browserConfig(t,i,n,r){return new gf(t,i,n,r)},plugin(t,i,n){return new Uf(t,i,n)}},rh={replace:"replace",concat:"concat",smart:"smart"},eh=/^https?:\/\//,Wt=new jr("bunfig",{showTags:!0}),Qt=new Of,fh=yt(ui.cwd(),"config"),sh=yt(ui.cwd(),"src/generated")});function Yw(t,i={}){let n=gr.cwd();while(n.includes("storage"))n=Tc(n,"..");let r=Tc(n,t||"");if(i?.relative)return A0(gr.cwd(),r);return r}var Ww=gr.env.CLARITY_LOG_DIR||m0(Yw(),"logs"),lh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ww,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Yr={...lh},H1=(async()=>{try{let{loadConfig:t}=await _w().then(()=>xc),i=await t({name:"clarity",alias:"logging",defaultConfig:lh,cwd:gr.cwd()});if(i)Object.assign(Yr,i)}catch{}return Yr})();function v(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Iw(){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 ch{async format(t){let i=await Iw(),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:Mi.pid,hostname:i(),environment:Mi.env.NODE_ENV||"development",platform:Mi.platform,version:Mi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mi.env.NODE_ENV||Mi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},j=it,z1=it.red,Ow=it.green,G1=it.yellow,Zw=it.blue,K1=it.magenta,q1=it.cyan,Mc=it.white,x1=it.gray,Lw=it.bgRed,Mw=it.bgYellow,k1=it.bgGray,Hc=it.bold,D1=it.dim,V1=it.italic,b1=it.underline,p1=it.strikethrough,P1=it.reset,of={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hw={debug:"\uD83D\uDD0D",info:Zw("ℹ"),success:Ow("✓"),warning:Mw(Mc(Hc(" WARN "))),error:Lw(Mc(Hc(" ERROR ")))};class Mr{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={...Yr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ch,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??C.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 e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,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{...of,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...of};return{...of,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Yr.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!v()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await R0(this.config.logDirectory,Cc.F_OK|Cc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await B0(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:bt.from(t);try{if(!hr(this.currentLogFile))await hf(this.currentLogFile,"",{mode:420});if(e=Bc(this.currentLogFile,"a",420),S0(e,l,{flag:"a"}),Rc(e),e!==void 0)cf(e),e=void 0;if((await Zi(this.currentLogFile)).size===0){if(await hf(this.currentLogFile,l,{flag:"w",mode:420}),(await Zi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let $=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,$);let w=c*2**f;await new Promise((y)=>setTimeout(y,w)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{cf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,$=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Li(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 Li(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Li(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(v())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((e)=>{console.error("Error rotating keys:",e)})},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 e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return lf(16).toString("hex")}generateKey(){return lf(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=lf(16),r=d0("aes-256-gcm",i,n),e=bt.isBuffer(t)?t:bt.from(t,"utf8"),f=r.update(e),s=r.final(),c=f.length+s.length,l=r.getAuthTag(),h=bt.allocUnsafe(16+c+16);return n.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Uc(),e=[];r.on("data",(f)=>e.push(f)),r.on("end",()=>i(bt.from(bt.concat(e)))),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(v())return;if(!this.shouldWriteToFile())return;let t=await Zi(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 e=await ur(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${n}.${s}`;if(await Zi(n).catch(()=>null))try{if(await gc(n,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await $r(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await hf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=n.replace(/\.log$/,`-${e}.log`);if(await Zi(n).catch(()=>null))await gc(n,f)}if(this.currentLogFile=r,i.maxFiles){let f=(await ur(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await $r(Li(this.config.logDirectory,s))}}}async compressLogFile(t,i){let n=Sc(t),r=T0(i),e=Uc();await U0(n,e,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()})),hr(this.currentLogFile))try{let t=Bc(this.currentLogFile,"r+");Rc(t),cf(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(!v()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await ur(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await $r(Li(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?j.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v())return!1;let t=typeof C.env.NO_COLOR<"u",i=C.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:e,level:f,showTimestamp:s=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(i);if(f==="warning")y.push("WARN");else if(f==="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(e),y.join(" ")}let l=C.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${n} ${e}`;else if(f==="info"||f==="success")h=`${n} ${r} ${e}`;else h=`${n} ${r} ${j.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,l-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let n=/%([sdijfo%])/g,r=0,e=t.replace(n,(f,s)=>{if(s==="%")return"%";if(r>=i.length)return f;let c=i[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(r<i.length)e+=` ${i.slice(r).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,e)=>{let f=j.underline(j.blue(r)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(n,r)=>j.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>j.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>j.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>j.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>j.strikethrough(r)),i}supportsHyperlinks(){if(v())return!1;let t=C.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=C.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(C0(i)||i.startsWith("./")||i.startsWith("../"))i=g0(i);else return null;return hr(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,e=this.formatConsoleTimestamp(r),f=this.formatFileTimestamp(r),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,n);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Hw[t],w=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:j.gray(l),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:j.green(l),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:l,level:t}),console.error(y),c){let m=c.split(`
105
+ `);for(let o of m)if(o.trim()&&!o.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:j.gray(` ${o}`),level:t,showTimestamp:!1}))}break}}else if(!v()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
106
+ `;if(c)u+=`${c}
107
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let n={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!v()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!v()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!v()&&C.stdout.isTTY)C.stdout.write(`
108
+ `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!v()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:n,message:`${j.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),e=Math.round(r-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
109
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":j.green("✓"),tag:u,message:`${f}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!v())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 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(v())throw Error("createReadStream is not supported in browser environments");if(!hr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Sc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=bt.isBuffer(t)?t:bt.from(t,"base64"),e=r.subarray(0,16),f=r.subarray(r.length-16),s=r.subarray(16,r.length-16),c=E0("aes-256-gcm",n,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,$=bt.allocUnsafe(u);return l.copy($,0),h.copy($,l.length),$.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 v()}isServerMode(){return!v()}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:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
110
+ `),l=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:n,message:j.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan(u),showTimestamp:!1}))}else if(!v())console.error(`${r} ${this.environment}.INFO: [BOX] ${f}`);let s=`${r} ${this.environment}.INFO: [BOX] ${f}
111
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(v())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${j.cyan("?")} ${t} (y/n) `);let n=(r)=>{let e=r.toString().trim().toLowerCase();C.stdin.removeListener("data",n);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(n=t.replace(l,(u,$)=>{if($==="%")return"%";if(h>=i.length)return u;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return u}}),h<i.length)n+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:e}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${h}${l} ${j.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
112
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.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),e=t.barLength-r,f=j.green("━".repeat(r)),s=j.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${n}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||n===100?j.green("✓"):j.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${l}${h}`,y=C.stdout.columns||80,m=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${m}`,C.stdout.write(t.lastRenderedLine),i)C.stdout.write(`
113
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||v()||!C.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(v()){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=Li(this.config.logDirectory,r);if(t.before)try{if((await Zi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await $r(r),console.warn(`Deleted log file: ${r}`)}catch(e){console.error(`Failed to delete log file ${r}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var X1=new Mr("stacks");class It 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 hh extends It{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],e="";if(r.length===1)e=` or alias "${r[0]}"`;else if(r.length>1)e=` or aliases ${r.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class Wr extends It{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 uh extends It{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class $h extends It{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 Zf extends It{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 It{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 wh extends It{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 Ir extends It{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 oh extends It{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 ah extends It{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 zi={configNotFound(t,i,n){return new hh(t,i,n)},configLoad(t,i,n){return new Wr(t,i,n)},configValidation(t,i,n){return new uh(t,i,n)},configMerge(t,i,n,r){return new $h(t,i,n,r)},envVar(t,i,n,r){return new Zf(t,i,n,r)},fileSystem(t,i,n){return new yh(t,i,n)},typeGeneration(t,i,n){return new wh(t,i,n)},schemaValidation(t,i,n){return new Ir(t,i,n)},browserConfig(t,i,n,r){return new oh(t,i,n,r)},plugin(t,i,n){return new ah(t,i,n)}};async function zw(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=n;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===n||!e(s))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Lf{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:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=n,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Jf.track("applyEnvironmentVariables",h,{configName:t});return h()}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[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${n}_${c.join("_")}`,h=r.useBackwardCompatibility?`${n}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,n,r);else{let u=wr.env[l]||(h?wr.env[h]:void 0);if(u!==void 0){if(r.verbose){let $=wr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,r.customParsers,r.configName)}catch($){if($ instanceof Zf)throw $;throw zi.envVar(l,u,typeof f,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,e){for(let[f,s]of Object.entries(r))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw zi.envVar(n,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,e]of Object.entries(wr.env))if(r.startsWith(n)&&e!==void 0)i[r]=e;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(e){r.push(`Cannot parse value "${i}" as ${n}: ${e}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:e="text"}=n,f=r||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,n,r){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${n}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,n,r);else r.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}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}:
114
+
115
+ `;for(let r of t)n+=`${r.key}
116
+ `,n+=` Type: ${r.type}
117
+ `,n+=` Description: ${r.description}
118
+ `,n+=` Example: ${r.example}
119
+
120
+ `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
121
+
122
+ `;n+=`| Variable | Type | Description | Example |
123
+ `,n+=`|----------|------|-------------|----------|
124
+ `;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
125
+ `;return n}}function Gw(t,i,n={}){return mh(t,i,n,new WeakMap)}function mh(t,i,n,r){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=n;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ah(t,i,e,r);if(!Ut(i)||!Ut(t))return i;return kw(t,i,n,r)}function Ah(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 Kw(t,i);case"smart":return qw(t,i,r);default:return i}return i}function Kw(t,i){let n=[...i];for(let r of t)if(!n.some((e)=>Ff(e,r)))n.push(r);return n}function qw(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ut(i[0])&&Ut(t[0]))return xw(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let e of t)if(!r.includes(e))r.push(e);return r}return i}function xw(t,i,n){let r=[...i];for(let e of t){if(!Ut(e)){r.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(r.find((h)=>Ut(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)r.push(e)}return r}function kw(t,i,n,r){let e=i;if(Ut(e)&&r.has(e))return r.get(e);let f={...t};if(Ut(e))r.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(n.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Ut(c)&&Ut(l))f[s]=mh(l,c,n,r);else if(Array.isArray(c)||Array.isArray(l))f[s]=Ah(l,c,n.arrayMergeMode||"smart",r);else f[s]=c}return f}function dh(t,i,n="replace"){return Gw(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ff(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(!Ff(t[n],i[n]))return!1;return!0}if(Ut(t)&&Ut(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let e of n){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Ff(t[e],i[e]))return!1}return!0}return!1}function Ut(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Eh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=n;if(e){let h=Sr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!or(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new Wr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Wr(t,Error("Configuration must export a valid object"),"unknown");let A={config:dh(i,$,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Sr.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?zi.configLoad(t,h):zi.configLoad(t,Error(String(h)))}};if(s)return Jf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let e=await this.loadFromPath(r,i,n);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(n.verbose)console.warn(`Failed to load config from ${r}:`,e)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),e=[];for(let f of r)for(let s of this.extensions)e.push(af(i,`${f}${s}`));return e}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 f of r){if(!f)continue;if(n.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)n.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return n.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return zw(async()=>{return or(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!or(t))return r;if(i||n){let e=this.generateNamePatterns(i||"",n);for(let f of e)for(let s of this.extensions){let c=af(t,`${f}${s}`);if(await this.checkFileAccess(c))r.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=af(t,s);if(await this.checkFileAccess(c))r.push(c)}}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(!or(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:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}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 e=await this.loadFromPath(r,{},i);if(e)n.set(r,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${r}:`,e)}})),n}}var Vw=/^https?:\/\//;class Th{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=n,h=async()=>{let u=[],$=[],w={stopOnFirstError:r,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await Jf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,n){try{if(!Dw(i))throw new Ir(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),e=r.default||r;if(Array.isArray(e))return this.validateWithRules(t,e,n);else return this.validateWithJSONSchema(t,e,n)}catch(r){throw new Ir(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],e=[];return this.validateObjectAgainstSchema(t,i,"",r,e,n),{isValid:r.length===0,errors:r,warnings:e}}validateObjectAgainstSchema(t,i,n,r,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(r.push({path:n,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.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"}),f.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 s=0;s<t.length;s++){let c=n?`${n}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,r,e,f),f.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(r.push({path:n?`${n}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=n?`${n}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,r,e,f),f.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(r.push(...c),n.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:e}}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 e=Array.isArray(t)?"array":typeof t;if(e!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,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 e=i.validator(t);if(e)r.push({path:n,message:i.message||e,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let e of n)if(r&&typeof r==="object"&&e in r)r=r[e];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,e,f,s]=r;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}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:Vw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var pt=new Mr("bunfig",{showTags:!0});function bw(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 Sh{fileLoader=new Eh;envProcessor=new Lf;validator=new Th;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:e,validate:f,...s}=t;try{if(n?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,n)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),$=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),w=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw l;if($&&(!h||!w))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(n?.enabled&&c)this.cacheResult(s.name||"",c,n,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)pt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw pt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||Or.cwd(),w=[],y=await this.loadLocalConfiguration(r,e,$,s,c,h,u,l,n);if(y)return w.push(...this.getLocalSearchPaths(r,e,$,s)),this.finalizeResult(y,w,l,r,u);let m=await this.loadHomeConfiguration(r,e,c,h,u,l);if(m)return w.push(...this.getHomeSearchPaths(r,e)),this.finalizeResult(m,w,l,r,u);let o=await this.loadPackageJsonConfiguration(r,e,$,c,h,u,l);if(o)return w.push(Ct($,"package.json")),this.finalizeResult(o,w,l,r,u);if(w.push(...this.getAllSearchPaths(r,e,$,s)),i)throw zi.configNotFound(r,w,e);return{...await this.applyEnvironmentVariables(r,c,l,u),warnings:[`No configuration file found for "${r}"${bw(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,e,f,s,c,l){let h=c?ar(t,e,s):e,u=this.getLocalDirectories(n,r);for(let $ of u){if(s)pt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(y){if(s)pt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,n,r,e,f){if(!t)return null;let s=f?ar(t,n,e):n,c=[Ct(Ji(),".config",t),Ct(Ji(),".config"),Ji()];for(let l of c){if(e)pt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:r,verbose:e});if(u){if(e)pt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,n,r,e,f,s){let c=s?ar(t,r,f):r;try{let l=Ct(n,"package.json");if(!Gy(l))return null;let h={};try{h=JSON.parse(Ky(l,"utf8"))}catch(w){if(f)pt.warn("Failed to parse package.json:",[w instanceof Error?w:Error(String(w))]);return null}let u=h[t],$=t;if(!u&&i){let w=Array.isArray(i)?i:[i];for(let y of w){if(!y)continue;if(h[y]){u=h[y],$=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)pt.success(`Configuration loaded from package.json: ${$}`);return{config:dh(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)pt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:ar(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let e=[];if(n){let f=n(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw zi.configValidation(r||"unknown",e,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Sr.get(n)||null}cacheResult(t,i,n,r){let e=this.generateCacheKey(t,r);Sr.set(e,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 e=[];return e.push(...this.getLocalSearchPaths(t,i,n,r)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Ct(n,"package.json")),e}getLocalSearchPaths(t,i,n,r){let e=this.getLocalDirectories(n,r),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let n=[Ct(Ji(),".config",t),Ct(Ji(),".config"),Ji()],r=[];for(let e of n)r.push(...this.fileLoader.generateConfigPaths(t,e,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var nd=new Sh;function ar(t,i,n=!1){let r=new Lf,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((o)=>o.toUpperCase()).join("")}`,`${e}_${$.map((o)=>o.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,m;for(let o of w)if(y=Or.env[o],y!==void 0){m=o;break}if(y!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let o=Number(y);if(!Number.isNaN(o))l[h]=o}else if(Array.isArray(u))try{l[h]=JSON.parse(y)}catch{l[h]=y.split(",").map((o)=>o.trim())}else l[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,$)}return l}return f(i)}var rd=Ct(Or.cwd(),"config"),ed=Ct(Or.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",pw={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Hf(Mf(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Hf(Mf(),".stacks","ssl","stacks.localhost.crt"),keyPath:Hf(Mf(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Rh=pw;import{execSync as sn}from"node:child_process";import{homedir as to}from"node:os";import{join as io}from"node:path";import{execSync as Hr}from"node:child_process";function Bh(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function zr(t){try{let i=Hr(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return Bh(i)}catch{return null}}function Pw(t){try{return Hr(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function Xw(t,i){try{let n=Hr(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((r)=>n.includes(`DNS:${r}`))}catch{return!1}}function vw(t,i,n=443){try{return Hr(`echo | openssl s_client -connect ${t}:${n} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function Qw(t){let i=[];for(let n of t.split(`
126
+ `)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)i.push(r[1].toUpperCase())}return i}var si="-d -r trustRoot -p ssl -p basic",$i="/Library/Keychains/System.keychain",zf="rpx.localhost";function ln(){return io(to(),"Library/Keychains/login.keychain-db")}function Gf(){return[$i,ln()]}function Ch(t,i=zf){let n=sn(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let e of n.split(`
127
+ `)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)r.push(f[1].toUpperCase())}return r}function Gr(t){if(process.platform!=="darwin")return;let i=zr(t.caPath);if(!i)return;let n=t.commonName??zf,r=t.keychains??Gf();for(let e of r)for(let f of Ch(e,n)){if(f===i)continue;try{if(e.startsWith("/Library"))fn(`security delete-certificate -Z ${f} "${e}"`);else sn(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});a("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function cn(t,i,n){if(process.platform!=="darwin")return hn(t,n);try{let e=sn(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return a("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,n?.verbose),e}catch{return!1}}function hn(t,i){let n=zr(t);if(!n)return!1;for(let r of Gf())try{let e=sn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let f of e.split(`
128
+ `))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return a("ssl",`Root CA fingerprint found in ${r}`,i?.verbose),!0}}catch{}return!1}function Kf(t,i){if(process.platform!=="darwin")return!1;let n=i.serverName;Gr({caPath:t,commonName:i.commonName,verbose:i.verbose});let r=ln();try{sn(`security add-trusted-cert ${si} -k "${r}" "${t}"`,{stdio:"ignore"})}catch{}try{fn(`security add-trusted-cert ${si} -k ${$i} "${t}"`)}catch{return!1}return cn(t,n,{verbose:i.verbose})||hn(t,{verbose:i.verbose})}var li=null,no="rpx-root-ca.crt",ro="rpx-root-ca.key";function kf(t){return{caCertPath:Q(t,no),caKeyPath:Q(t,ro)}}function Nd(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:kf(t)}}async function eo(t,i){try{let[n,r]=await Promise.all([D.readFile(t.caCertPath,"utf8"),D.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 gh(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 Nh(t){let n=xf(t).replace(/\*/g,"wildcard"),r=Q(qr(),".stacks","ssl"),e=r;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:r,{caCertPath:t.https.caCertPath||Q(e,`${n}.ca.crt`),certPath:t.https.certPath||Q(e,`${n}.crt`),keyPath:t.https.keyPath||Q(e,`${n}.key`)};return{caCertPath:Q(e,`${n}.ca.crt`),certPath:Q(e,`${n}.crt`),keyPath:Q(e,`${n}.key`)}}function Uh(t){let i=new Set;if(Kr(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";gh(r).forEach((e)=>i.add(e))});else if(Jh(t)){let n=t.to||"rpx.localhost";gh(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function _d(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Rh,...t};if(t.https=Vf(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 D.readFile(t.https?.keyPath,"utf8"),r=await D.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 Yd(t,i){if(Ot.platform==="darwin")return fo(t,i);if(Ot.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)r(!0);else n(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{r(!f)})})})}catch{return!1}return!1}async function fo(t,i){if(Ot.platform!=="darwin")return!1;let n=i?.serverName??"rpx.localhost",r=i?.verbose??!1;try{if(cn(t,n,{verbose:r}))return a("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return a("ssl","Trusting Root CA for browsers (login + system keychains)",r),Kf(t,{serverName:n,verbose:r})}catch{return!1}}async function _h(t){if(li&&!t.forceRegenerate){a("ssl","Using cached SSL configuration",t.verbose);return}so();let i=Kr(t)?t.proxies.map((u)=>u.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=Vf(t,t.verbose),r=n.basePath||Q(qr(),".stacks","ssl");await D.mkdir(r,{recursive:!0});let e=kf(r),f=await eo(e,t.verbose),s=!1;if(!f){if(t.verbose)L.info("Generating Root CA certificate (one-time)...");f=await Ve(n);try{await Promise.all([D.writeFile(e.caCertPath,f.certificate),D.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,a("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(u){throw a("ssl",`Error saving Root CA files: ${u}`,t.verbose),Error(`Failed to save Root CA files: ${u}`)}}else a("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)L.info(`Generating host certificate for: ${i.join(", ")}`);let c=await be({...n,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([D.writeFile(n.certPath,c.certificate),D.writeFile(n.keyPath,c.privateKey),D.writeFile(n.caCertPath,f.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch(u){throw a("ssl",`Error saving certificate files: ${u}`,t.verbose),Error(`Failed to save certificate files: ${u}`)}if(s?!1:await Yh(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)L.success("Root CA is already trusted in system trust store");if(li={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)L.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)L.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Ot.platform==="darwin")try{Gr({caPath:e.caCertPath,verbose:t.verbose});let u=ln();try{Gi(`security add-trusted-cert ${si} -k "${u}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(fn(`security add-trusted-cert ${si} -k ${$i} "${e.caCertPath}"`),t.verbose)L.success("Successfully added Root CA to system trust store");h=!0;let $=Q(r,"trust-rpx-cert.sh"),w=`#!/bin/bash
129
+ echo "Trusting RPX Root CA"
130
+ sudo security add-trusted-cert ${si} -k ${$i} "${e.caCertPath}"
131
+ echo "Root CA trusted! Please restart your browser."
132
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
133
+ `;await D.writeFile($,w,{mode:493})}catch(u){if(t.verbose)L.warn(`Could not add Root CA to trust store automatically: ${u}`);let $=Q(r,"trust-rpx-cert.sh"),w=`#!/bin/bash
134
+ echo "Trusting RPX Root CA"
135
+ sudo security add-trusted-cert ${si} -k ${$i} "${e.caCertPath}"
136
+ echo "Root CA trusted! Please restart your browser."
137
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
138
+ `;if(await D.writeFile($,w,{mode:493}),t.verbose)L.info(`Created a trust helper script at: ${$}`),L.info(`If you're still having certificate issues, run: sh ${$}`)}else if(Ot.platform==="linux")try{let{exec:u}=await import("node:child_process"),$="/usr/local/share/ca-certificates/rpx",w=`
139
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
140
+ cp "${e.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
141
+ update-ca-certificates
142
+ echo "RPX Root CA installed. Please restart your browser."
143
+ `,y=Q(qf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await D.writeFile(y,w,{mode:493}),await new Promise((m)=>{u(`sudo bash "${y}"`,(o)=>{if(o){if(t.verbose)L.warn(`Could not trust certificates: ${o}`);m(!1)}else{if(t.verbose)L.success("Successfully added certificates to system trust store");m(!0)}})}),await D.unlink(y).catch(()=>{}),h=!0}catch(u){if(t.verbose)L.warn(`Failed to trust certificates: ${u}`)}else if(Ot.platform==="win32")try{let u=`
144
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${e.caCertPath.replace(/\//g,"\\")}")
145
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
146
+ $store.Open("ReadWrite")
147
+ $store.Add($cert)
148
+ $store.Close()
149
+ Write-Host "Root CA trusted successfully!"
150
+ `,$=Q(qf.tmpdir(),"rpx-trust.ps1");if(await D.writeFile($,u),Gi(`powershell -ExecutionPolicy Bypass -File "${$}"`),t.verbose)L.success("Successfully added certificate to Windows trust store");h=!0}catch(u){if(t.verbose)L.warn(`Could not trust certificate: ${u}`)}else try{await pe(c,f.certificate,n),h=!0}catch(u){if(t.verbose)L.warn(`Could not add certificate to trust store: ${u}`)}if(li={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)L.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)L.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),L.warn("This will bypass the warning and you should only need to do it once")}function so(){li=null}async function Df(t){if(!t)return null;if(li)return li;let i=Vf(t);try{let[n,r,e]=await Promise.all([D.access(i.keyPath).then(()=>!0).catch(()=>!1),D.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?D.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 f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;a("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||Q(qr(),".stacks","ssl"),h=kf(l);if(!(c?await Yh(h.caCertPath,t):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[$,w,y]=await Promise.all([D.readFile(i.keyPath,"utf8"),D.readFile(i.certPath,"utf8"),e&&i.caCertPath?D.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(y&&!y.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(Kr(t))try{let{X509Certificate:m}=await import("node:crypto"),A=new m(w).subjectAltName||"",T=t.proxies.map((N)=>N.to).filter((N)=>!A.includes(`DNS:${N}`));if(T.length>0)return a("ssl",`Certificate missing SANs for: ${T.join(", ")}, will regenerate`,t.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return a("ssl","Successfully loaded existing certificates",t.verbose),li={key:$,cert:w,ca:y},li}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function Vf(t,i){let n=xf(t);a("ssl",`Primary domain: ${n}`,i);let r=Nh(t),e=Q(qr(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:n,hostCertCN:n,basePath:f,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(Uh(t)).map((c)=>({type:2,value:c}))};if(Fh(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:n,hostCertCN:n,basePath:e,...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(Uh(t)).map((f)=>({type:2,value:f}))}}async function Wd(t,i){let n=Nh({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((e)=>jh(e,i)))}async function Yh(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Ot.platform==="darwin"){if(i?.serverName)return cn(t,i.serverName,{verbose:i.verbose});return hn(t,{verbose:i.verbose})}else if(Ot.platform==="win32")try{let r=Gi(`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 e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(Gi(e).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(Ot.platform==="linux")try{let r=Gi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",e=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of e)try{if(Gi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${r}"`).toString().includes(r))return a("ssl",`Certificate fingerprint found in ${f}`,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 ${Ot.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}}import*as Ft from"node:path";function Wh(t,i){if(typeof t==="string")return{dir:t,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:i};return{dir:t.dir,spa:t.spa??!1,pathRewriteStyle:t.pathRewriteStyle??"directory",maxAge:t.maxAge??0,cleanUrls:i}}var lo={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"};function co(t){let i=Ft.extname(t).toLowerCase();return lo[i]??"application/octet-stream"}function ho(t){let i;try{i=decodeURIComponent(t)}catch{return null}if(i.includes("\x00")||i.includes("\\"))return null;let n=Ft.posix.normalize(`/${i}`);if(n.includes(".."))return null;return n.replace(/^\/+/,"")}function uo(t,i){let n=ho(t);if(n===null)return null;let r=Ft.posix.extname(n);if(i.cleanUrls&&r===".html"){let e=t.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ft.join(i.dir,n),redirectTo:e||"/"}}if(n===""||t.endsWith("/"))return{filePath:Ft.join(i.dir,n,"index.html")};if(r!=="")return{filePath:Ft.join(i.dir,n)};if(i.pathRewriteStyle==="flat")return{filePath:Ft.join(i.dir,`${n}.html`)};return{filePath:Ft.join(i.dir,n,"index.html")}}async function Ih(t,i){let n=uo(t,i);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=i.maxAge>0?`public, max-age=${i.maxAge}`:"no-cache",e=Bun.file(n.filePath);if(await e.exists())return new Response(e,{status:200,headers:{"Content-Type":co(n.filePath),"Cache-Control":r}});if(i.spa){let f=Ft.join(i.dir,"index.html"),s=Bun.file(f);if(await s.exists())return new Response(s,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var $o=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function yo(t){return(t.headers.get("host")||"").split(":")[0]}function Oh(t,i,n){let r=new URL(t.url),e=i.sourceHost??"",f=r.pathname,s=Zh(r.pathname,i.pathRewrites);if(s)e=s.targetHost,f=s.targetPath,a("request",`Path rewrite: ${r.pathname} → ${e}${f}`,n);return{targetHost:e,targetPath:f,search:r.search}}function Lh(t,i){return async(n,r)=>{let e=new URL(n.url),f=yo(n),s=t(f);if(!s)return a("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});if(s.static)return Ih(e.pathname,s.static);if(n.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!r||!s.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:$,targetPath:w,search:y}=Oh(n,s,i),m=`ws://${$}${w}${y}`,o={};for(let[T,N]of n.headers)if(!$o.has(T.toLowerCase())&&T.toLowerCase()!=="host")o[T]=N;o.host=$,o["x-forwarded-for"]="127.0.0.1",o["x-forwarded-proto"]="https",o["x-forwarded-host"]=f;let A={targetUrl:m,forwardHeaders:o};if(r.upgrade(n,{data:A})){a("ws",`upgraded ${f}${w} → ${m}`,i);return}return new Response("WebSocket upgrade failed",{status:400})}if(!s.sourceHost)return new Response(`No upstream configured for ${f}`,{status:502});let{targetHost:c,targetPath:l,search:h}=Oh(n,s,i),u=`http://${c}${l}${h}`;try{let $=new Headers(n.headers);if($.set("host",c),s.changeOrigin)$.set("origin",`http://${s.sourceHost}`);$.set("x-forwarded-for","127.0.0.1"),$.set("x-forwarded-proto","https"),$.set("x-forwarded-host",f);let w=await fetch(u,{method:n.method,headers:$,body:n.body,redirect:"manual"});if(s.cleanUrls&&e.pathname.endsWith(".html")){let m=e.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let y=new Headers(w.headers);return new Response(w.body,{status:w.status,statusText:w.statusText,headers:y})}catch($){return a("request",`Proxy error for ${f}: ${$}`,i),new Response(`Proxy Error: ${$}`,{status:502})}}}function Mh(t){let i=new WeakMap;return{open(n){let{targetUrl:r,forwardHeaders:e}=n.data,f;try{f=new WebSocket(r,{headers:e})}catch(c){a("ws",`failed to open upstream ${r}: ${c}`,t),n.close(1011,"upstream connect failed");return}f.binaryType="arraybuffer";let s={upstream:f,upstreamOpen:!1,pending:[]};i.set(n,s),f.addEventListener("open",()=>{s.upstreamOpen=!0;for(let c of s.pending)f.send(c);s.pending=[]}),f.addEventListener("message",(c)=>{n.send(c.data)}),f.addEventListener("close",(c)=>{try{n.close(c.code||1000,c.reason||"")}catch{}}),f.addEventListener("error",()=>{a("ws",`upstream error for ${r}`,t);try{n.close(1011,"upstream error")}catch{}})},message(n,r){let e=i.get(n);if(!e)return;let f=typeof r==="string"?r:new Uint8Array(r);if(e.upstreamOpen)e.upstream.send(f);else e.pending.push(f)},close(n,r,e){let f=i.get(n);if(!f)return;i.delete(n);try{f.upstream.close(r||1000,e||"")}catch{}}}}function Hh(t){return t.startsWith("*.")}function wo(t,i){if(!Hh(i))return!1;let n=i.slice(1);return t.length>n.length&&t.endsWith(n)}function zh(t,i){let n=t.get(i);if(n!==void 0)return n;let r,e=-1;for(let[f,s]of t){if(!Hh(f))continue;if(wo(i,f)){let c=f.length-1;if(c>e)e=c,r=s}}return r}import*as un from"node:fs/promises";import*as bf from"node:path";function oo(t){if(!t.endsWith(".crt"))return null;let i=t.slice(0,-4);if(i.length===0)return null;if(i.startsWith("_wildcard."))return`*.${i.slice(10)}`;return i}async function ao(t,i,n,r){try{let[e,f]=await Promise.all([un.readFile(i,"utf8"),un.readFile(n,"utf8")]);return{serverName:t,cert:e,key:f}}catch(e){return a("sni",`skipping ${t}: ${e.message}`,r),null}}async function Gh(t,i){let n=new Map;if(t.certsDir){let e=[];try{e=await un.readdir(t.certsDir)}catch(f){a("sni",`certsDir read failed (${t.certsDir}): ${f.message}`,i)}for(let f of e){let s=oo(f);if(!s)continue;let c=f.slice(0,-4);n.set(s,{certPath:bf.join(t.certsDir,f),keyPath:bf.join(t.certsDir,`${c}.key`)})}}if(t.domains)for(let[e,f]of Object.entries(t.domains))n.set(e,f);let r=[];for(let[e,f]of n){let s=await ao(e,f.certPath,f.keyPath,i);if(s)r.push(s)}return r}import*as xr from"node:fs";import*as wt from"node:fs/promises";import{homedir as mo}from"node:os";import*as pf from"node:path";import*as kr from"node:process";var Ao=/^[a-zA-Z0-9._-]+$/;function qi(){return pf.join(mo(),".stacks","rpx","registry.d")}function Pf(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Ao.test(t)}function Xf(t,i){if(!Pf(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return pf.join(t,`${i}.json`)}function Zt(t){if(!Number.isInteger(t)||t<=0)return!1;try{return kr.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Kh(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,r=typeof i.from==="string"&&i.from.length>0,e=typeof i.static==="string"||!!i.static&&typeof i.static==="object"&&typeof i.static.dir==="string";return typeof i.id==="string"&&Pf(i.id)&&(r||e)&&typeof i.to==="string"&&i.to.length>0&&n&&typeof i.createdAt==="string"}async function Eo(t){await wt.mkdir(t,{recursive:!0})}async function Dd(t,i=qi(),n){if(!Kh(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await Eo(i);let r=Xf(i,t.id),e=`${r}.tmp.${kr.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await wt.writeFile(e,f,{encoding:"utf8",mode:420}),await wt.rename(e,r),a("registry",`wrote entry ${t.id} → ${r}`,n)}catch(s){throw await wt.unlink(e).catch(()=>{}),s}}async function To(t,i=qi(),n){let r=Xf(i,t);try{await wt.unlink(r),a("registry",`removed entry ${t}`,n)}catch(e){if(e.code!=="ENOENT")throw e}}async function So(t,i=qi(),n){let r=Xf(i,t);try{let e=await wt.readFile(r,"utf8"),f=JSON.parse(e);if(!Kh(f))return a("registry",`entry ${t} failed validation, removing`,n),await wt.unlink(r).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return a("registry",`entry ${t} has invalid JSON, removing`,n),await wt.unlink(r).catch(()=>{}),null;throw e}}async function Ki(t=qi(),i){let n;try{n=await wt.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let r=[];for(let e of n){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!Pf(f))continue;let s=await So(f,t,i);if(s)r.push(s)}return r}async function vf(t=qi(),i){let n=await Ki(t,i),r=0;for(let e of n){if(e.pid===void 0)continue;if(!Zt(e.pid))a("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await To(e.id,t,i).catch(()=>{}),r++}return r}function qh(t,i={}){let n=i.dir??qi(),r=i.debounceMs??100,e=i.pollMs??Math.max(r*2,250),f=i.verbose;xr.mkdirSync(n,{recursive:!0});let s=null,c=!1,l=null,h=!1,u=(A)=>{return JSON.stringify(A.map((d)=>({id:d.id,from:d.from,to:d.to,pid:d.pid,pathRewrites:d.pathRewrites,cleanUrls:d.cleanUrls,changeOrigin:d.changeOrigin,static:d.static})).sort((d,T)=>d.id.localeCompare(T.id)))},$=()=>{if(s=null,c)return;Ki(n,f).then((A)=>{return l=u(A),t(A)}).catch((A)=>{a("registry",`watcher onChange failed: ${A}`,f)})},w=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout($,r)},m=setInterval(()=>{if(c||h)return;h=!0,Ki(n,f).then((A)=>{if(u(A)!==l)w()}).catch((A)=>{a("registry",`watcher poll failed: ${A}`,f)}).finally(()=>{h=!1})},e),o=xr.watch(n,{persistent:!0},(A,d)=>{if(d&&/\.tmp\.\d+\.\d+$/.test(d))return;w()});return o.on("error",(A)=>{a("registry",`watcher error: ${A}`,f)}),w(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),o.close()}}}var Ro=5000;function ot(){return Lt.join(ts(),".stacks","rpx")}function Dr(t=ot()){return Lt.join(t,"daemon.pid")}async function xi(t=ot()){try{let i=await Mt.readFile(Dr(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 Bo(t=ot()){let i=await xi(t);return i!==null&&Zt(i)}async function Co(t=ot()){await Mt.mkdir(t,{recursive:!0});let i=Dr(t);while(!0){try{let r=await Mt.open(i,"wx");try{await r.write(`${F.pid}
151
+ `)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await xi(t);if(n!==null&&Zt(n))throw Error(`rpx daemon already running (pid=${n})`);await Mt.unlink(i).catch(()=>{})}}async function $n(t=ot()){await Mt.unlink(Dr(t)).catch(()=>{})}function go(t){let i=t.cleanUrls??!1;if(t.static)return{static:Wh(t.static,i),cleanUrls:i};let n=t.from??"localhost:1";return{sourceHost:new URL(n.startsWith("http")?n:`http://${n}`).host,cleanUrls:i,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function Uo(t){return t.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??t[0]??"rpx.localhost"}async function Fo(t,i){let n=await Ki(i,t.verbose),r=[...new Set(n.map((u)=>u.to))],e=Uo(r),f=[...new Set([e,...r,"rpx.localhost"])],s=Lt.join(ts(),".stacks","ssl"),c=Lt.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:Lt.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:Lt.join(s,"rpx.localhost.key"),caCertPath:Lt.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((u)=>({from:"localhost:1",to:u}))}:{to:e,from:"localhost:1"}},h=await Df(l);if(!h)a("daemon","no usable cert on disk, generating one",t.verbose),await _h(l),h=await Df(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function Jo(t,i,n,r){let e=F.env.SUDO_PASSWORD,f=F.env.HOME??ts(),s=[F.execPath,...F.argv.slice(1)],c=[`HOME=${f}`,`PATH=${F.env.PATH??""}`];if(r)c.push("RPX_VERBOSE=1");let l=e?["-S","-p","","env",...c,...s]:["-n","env",...c,...s];a("daemon",`elevating daemon via sudo for privileged ports ${i}/${n}`,r);let h=xh("sudo",l,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,$=null;if(h.once("error",(m)=>{u=m}),h.once("exit",(m)=>{$=m??0}),e&&h.stdin)h.stdin.write(`${e}
152
+ `),h.stdin.end();h.unref();let w=Dr(t),y=Date.now()+15000;while(Date.now()<y){if(u)throw u;let m=await xi(t);if(m!==null&&Zt(m)){if(r)L.success(`rpx daemon elevated to root (pid=${m}, https on :${i})`);return{httpsPort:i,httpPort:n,pidPath:w,done:Promise.resolve(),stop:async()=>{try{F.kill(m,"SIGTERM")}catch{}}}}if($!==null&&$!==0)throw Error(`rpx daemon could not elevate to bind :${i} (sudo exited ${$}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((o)=>setTimeout(o,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${t})`)}async function sE(t={}){let i=t.verbose??!1,n=t.rpxDir??ot(),r=t.registryDir??Lt.join(n,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??Ro,l=e>0&&e<1024||f>0&&f<1024,h=typeof F.getuid==="function"&&F.getuid()===0;if(F.platform!=="win32"&&l&&!h)return Jo(n,e,f,i);let u=await Co(n),$=new Map,w=(R)=>zh($,R);function y(R){let Tt=new Map;for(let an of R)Tt.set(an.to,go(an));$=Tt,a("daemon",`routing table now covers ${Tt.size} host(s): ${Array.from(Tt.keys()).join(", ")||"<empty>"}`,i)}await vf(r,i).catch((R)=>{a("daemon",`initial gc failed: ${R}`,i)});let m=await Ki(r,i);y(m),await wn({rpxDir:n,verbose:i}).catch((R)=>{a("daemon",`DNS reconcile on start failed: ${R}`,i)}),await Qf(m,{rpxDir:n,verbose:i,ownerPid:F.pid}).catch((R)=>{a("daemon",`DNS setup on start failed: ${R}`,i)});let o=[];if(t.productionCerts){if(o=await Gh(t.productionCerts,i),i&&o.length>0)L.info(`SNI: serving ${o.length} real cert(s): ${o.map((R)=>R.serverName).join(", ")}`)}let A=Lh(w,i),d=Mh(i),T;if(o.length>0)T=o.map((R)=>({serverName:R.serverName,cert:R.cert,key:R.key}));else{let R=await Fo(t,r);T={key:R.key,cert:R.cert,ca:R.ca,requestCert:!1,rejectUnauthorized:!1}}let N=Bun.serve({port:e,hostname:s,tls:T,fetch(R,Tt){return A(R,Tt)},websocket:d,error(R){return a("daemon",`https server error: ${R}`,i),new Response(`Server Error: ${R.message}`,{status:500})}}),_=null;if(f>0)_=Bun.serve({port:f,hostname:s,fetch(R){let Tt=new URL(R.url),an=(R.headers.get("host")??Tt.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${an}${Tt.pathname}${Tt.search}`}})}});if(i)L.success(`rpx daemon listening on https://${s}:${e}${_?` (http→https on :${f})`:""}`),L.info(`pid file: ${u}`),L.info(`registry: ${r}`);let M=qh((R)=>{y(R),Qf(R,{rpxDir:n,verbose:i,ownerPid:F.pid}).catch((Tt)=>{a("daemon",`DNS sync on registry change failed: ${Tt}`,i)})},{dir:r,verbose:i}),yi=setInterval(()=>{vf(r,i).then((R)=>{if(R>0)a("daemon",`gc reaped ${R} stale entries`,i)}).catch((R)=>{a("daemon",`periodic gc failed: ${R}`,i)})},c);if(typeof yi.unref==="function")yi.unref();let hs=!1,us,Xr=new Promise((R)=>{us=R});async function $s(){if(hs)return Xr;if(hs=!0,clearInterval(yi),M.close(),N.stop(!1),_?.stop(!1),await yn({rpxDir:n,verbose:i}).catch((R)=>{a("daemon",`DNS teardown failed: ${R}`,i)}),await $n(n),i)L.info("rpx daemon stopped");return us(),Xr}let ys=(R)=>{a("daemon",`received ${R}, shutting down`,i),$s().catch(()=>{})};return F.once("SIGINT",ys),F.once("SIGTERM",ys),{stop:$s,done:Xr,httpsPort:typeof N.port==="number"?N.port:e,httpPort:_&&typeof _.port==="number"?_.port:f,pidPath:u}}function jo(){let t=F.execPath,i=Lt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&F.argv[1])return[t,F.argv[1],"daemon:start"];return[t,"daemon:start"]}async function lE(t={}){let i=t.rpxDir??ot(),n=t.verbose??!1;await wn({rpxDir:i,verbose:n}).catch((u)=>{a("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,n)});let r=await xi(i);if(r!==null&&Zt(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 $n(i);await Mt.mkdir(i,{recursive:!0});let e=t.spawnCommand??jo();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${e.join(" ")}`,n);let f=xh(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??F.cwd(),env:t.spawnEnv?{...F.env,...t.spawnEnv}:F.env});f.unref();let s=null;f.once("error",(u)=>{s=u});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let u=await xi(i);if(u!==null&&Zt(u))return a("daemon",`daemon registered with pid=${u}`,n),{pid:u,spawned:!0};await new Promise(($)=>setTimeout($,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function cE(t={}){let i=t.rpxDir??ot(),n=t.verbose??!1,r=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await xi(i);if(s===null||!Zt(s)){if(s!==null)await $n(i);return await wn({rpxDir:i,verbose:n}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{F.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await $n(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+r;while(Date.now()<c){if(!Zt(s))return a("daemon",`daemon pid=${s} stopped cleanly`,n),{stopped:!0,pid:s,forced:!1};await new Promise((l)=>setTimeout(l,e))}if(!f)throw Error(`rpx daemon (pid=${s}) did not exit within ${r}ms`);a("daemon",`daemon pid=${s} did not exit, escalating to SIGKILL`,n);try{F.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await $n(i),await yn({rpxDir:i,verbose:n}).catch((l)=>{a("daemon",`DNS teardown after SIGKILL: ${l}`,n)}),{stopped:!0,pid:s,forced:!0}}async function hE(t={}){let i=t.rpxDir??ot();if(await Bo(i))return;await wn({rpxDir:i,verbose:t.verbose})}import*as ci from"node:fs/promises";import{homedir as No}from"node:os";import*as is from"node:path";var Vr=1,_o="dns-state.json",kh=["com","test","dev","app","page","local","localhost","example","invalid"];function Dh(){return is.join(No(),".stacks","rpx")}function ns(t=Dh()){return is.join(t,_o)}async function br(t=Dh()){try{let i=await ci.readFile(ns(t),"utf8"),n=JSON.parse(i);if(n.version!==Vr||!Array.isArray(n.resolvers))return null;return{version:Vr,resolvers:n.resolvers.filter((r)=>typeof r==="string"),domains:Array.isArray(n.domains)?n.domains.filter((r)=>typeof r==="string"):[],ownerPid:typeof n.ownerPid==="number"?n.ownerPid:null,updatedAt:typeof n.updatedAt==="string"?n.updatedAt:""}}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Vh(t,i){await ci.mkdir(t,{recursive:!0}),await ci.writeFile(ns(t),`${JSON.stringify(i,null,2)}
153
+ `,"utf8")}async function rs(t){await ci.rm(ns(t),{force:!0})}function bh(t){let i=t.trim().toLowerCase().replace(/\.$/,"");if(!i||i.includes("127.0.0.1"))return null;if(i==="localhost"||i.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(i))return null;return i}function Yo(t){let i=bh(t);if(!i)return null;let n=i.split(".");if(n.length<2)return null;return n.slice(-2).join(".")}function es(t){let i=new Set;for(let n of t){let r=Yo(n);if(r)i.add(r)}return Array.from(i).sort()}function fs(t){let i=new Set;for(let n of t){let r=bh(n);if(r)i.add(r)}return Array.from(i).sort()}var ss=15353,Io="# managed-by: rpx",Xh="/etc/resolver",at=null,pr=new Set;function Oo(t){return{id:t.readUInt16BE(0),flags:t.readUInt16BE(2),qdcount:t.readUInt16BE(4),ancount:t.readUInt16BE(6),nscount:t.readUInt16BE(8),arcount:t.readUInt16BE(10)}}function vh(t,i){let n=[],r=i;while(!0){let e=t[r];if(e===0){r++;break}if((e&192)===192){let f=t.readUInt16BE(r)&16383,{name:s}=vh(t,f);n.push(s),r+=2;break}r++,n.push(t.subarray(r,r+e).toString("ascii")),r+=e}return{name:n.join("."),newOffset:r}}function Zo(t,i){let{name:n,newOffset:r}=vh(t,i),e=t.readUInt16BE(r),f=t.readUInt16BE(r+2);return{question:{name:n,type:e,class:f},newOffset:r+4}}function Pr(t){let i=t.split("."),n=[];for(let r of i)n.push(Buffer.from([r.length])),n.push(Buffer.from(r,"ascii"));return n.push(Buffer.from([0])),Buffer.concat(n)}function Lo(t,i,n){let r=[],e=Buffer.alloc(12);e.writeUInt16BE(t,0),e.writeUInt16BE(33152,2),e.writeUInt16BE(1,4),e.writeUInt16BE(1,6),e.writeUInt16BE(0,8),e.writeUInt16BE(0,10),r.push(e),r.push(Pr(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),r.push(f),r.push(Pr(i.name));let s=Buffer.alloc(10);if(s.writeUInt16BE(i.type,0),s.writeUInt16BE(1,2),s.writeUInt32BE(300,4),i.type===1){s.writeUInt16BE(4,8),r.push(s);let c=n.split(".").map((l)=>Number.parseInt(l,10));r.push(Buffer.from(c))}else if(i.type===28)s.writeUInt16BE(16,8),r.push(s),r.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return e.writeUInt16BE(33155,2),e.writeUInt16BE(0,6),Buffer.concat([e,Pr(i.name),f]);return Buffer.concat(r)}function Mo(t,i){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(t,0),r.writeUInt16BE(33155,2),r.writeUInt16BE(1,4),r.writeUInt16BE(0,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(Pr(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),n.push(e),Buffer.concat(n)}async function Ho(t,i){if(ti.platform!=="darwin")return!1;let n=fs(t);if(n.length===0)return!1;if(at){for(let r of n)pr.add(r);return a("dns","DNS server already running — merged domains",i),!0}return pr=new Set(n),new Promise((r)=>{at=Wo.createSocket("udp4"),at.on("error",(e)=>{a("dns",`DNS server error: ${e.message}`,i),at?.close(),at=null,r(!1)}),at.on("message",(e,f)=>{try{let s=Oo(e),{question:c}=Zo(e,12);a("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let $ of pr)if(l===$||l.endsWith(`.${$}`)){h=!0;break}let u;if(h&&(c.type===1||c.type===28))u=Lo(s.id,c,"127.0.0.1"),a("dns",`Responding with localhost for ${c.name}`,i);else u=Mo(s.id,c),a("dns",`NXDOMAIN for ${c.name}`,i);at?.send(u,f.port,f.address)}catch(s){a("dns",`Error processing DNS query: ${s}`,i)}}),at.on("listening",()=>{let e=at?.address();a("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),r(!0)});try{at.bind(ss,"127.0.0.1")}catch(e){a("dns",`Failed to bind DNS server: ${e}`,i),r(!1)}})}function Qh(t){if(at)a("dns","Stopping DNS server",t),at.close(),at=null,pr=new Set}function dE(){return at!==null}function zo(){return`${Io}
154
+ nameserver 127.0.0.1
155
+ port ${ss}
156
+ `}function on(t){return Ph.join(Xh,t)}function Go(t){return t.includes("127.0.0.1")&&t.includes(String(ss))}async function Ko(t){try{return await ph.readFile(on(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ls(t){if(ti.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:n}=await import("./chunk-a0ddh9cv.js");if(!n()){a("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),a("dns","DNS cache flushed",t)}catch(r){a("dns",`Could not flush DNS cache: ${r}`,t)}}async function qo(t,i){let{execSudoSync:n}=await import("./chunk-a0ddh9cv.js"),r=zo().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Xh} && printf "%b" "${r}" > ${on(t)}'`;n(e),a("dns",`Created ${on(t)}`,i)}async function xo(t,i){let{execSudoSync:n}=await import("./chunk-a0ddh9cv.js");n(`rm -f ${on(t)}`),a("dns",`Removed ${on(t)}`,i)}async function EE(t,i){return iu({domains:i??[],verbose:t})}async function ko(t,i){if(ti.platform!=="darwin")return!0;let{getSudoPassword:n}=await import("./chunk-a0ddh9cv.js");if(!n())return a("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let r of t)await qo(r,i);return await ls(i),!0}catch(r){return a("dns",`Failed to create resolver file: ${r}`,i),!1}}async function cs(t,i){if(ti.platform!=="darwin")return;let{getSudoPassword:n}=await import("./chunk-a0ddh9cv.js");if(!n())return;try{for(let r of t)await xo(r,i);await ls(i)}catch(r){a("dns",`Failed to remove resolver files: ${r}`,i)}}async function tu(t){if(ti.platform!=="darwin")return[];let i=[];for(let n of kh){let r=await Ko(n);if(r&&Go(r))await cs([n],t),i.push(n)}return i}async function iu(t){let i=t.rpxDir??ot(),n=fs(t.domains);if(n.length===0)return!1;let r=es(n);if(!await Ho(n,t.verbose))return!1;if(!await ko(r,t.verbose))return!1;let s={version:Vr,resolvers:r,domains:n,ownerPid:t.ownerPid??ti.pid,updatedAt:new Date().toISOString()};return await Vh(i,s),!0}async function Qf(t,i={}){let n=t.map((l)=>l.to).filter(Boolean),r=i.rpxDir??ot(),e=es(n),c=((await br(r))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await cs(c,i.verbose);if(e.length===0){Qh(i.verbose),await rs(r);return}await iu({domains:n,rpxDir:r,verbose:i.verbose,ownerPid:i.ownerPid??ti.pid})}async function yn(t={}){let i=t.rpxDir??ot();Qh(t.verbose);let r=(await br(i))?.resolvers??[];await cs(r,t.verbose),await tu(t.verbose),await rs(i)}async function TE(t){await yn({verbose:t})}async function wn(t={}){let i=t.rpxDir??ot(),n=await br(i),r=n?.ownerPid!=null&&Zt(n.ownerPid);if(n&&!r){a("dns",`reconcile: owner pid ${n.ownerPid} is gone — tearing down DNS`,t.verbose),await yn(t);return}let e=await tu(t.verbose);if(e.length>0)a("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await ls(t.verbose)}
157
+ export{L as a,Rh as b,Bh as c,zr as d,Pw as e,Xw as f,vw as g,Qw as h,si as i,$i as j,zf as k,ln as l,Gf as m,Ch as n,Gr as o,cn as p,hn as q,Kf as r,kf as s,Nd as t,_d as u,Yd as v,_h as w,so as x,Df as y,Vf as z,Wd as A,Yh as B,Wh as C,co as D,ho as E,uo as F,Ih as G,Lh as H,Mh as I,Hh as J,wo as K,zh as L,oo as M,Gh as N,qi as O,Pf as P,Zt as Q,Dd as R,To as S,So as T,Ki as U,vf as V,qh as W,Vr as X,kh as Y,bh as Z,Yo as _,es as $,fs as aa,ss as ba,Io as ca,Ho as da,Qh as ea,dE as fa,on as ga,Go as ha,EE as ia,tu as ja,iu as ka,Qf as la,yn as ma,TE as na,wn as oa,ot as pa,Dr as qa,xi as ra,Bo as sa,Co as ta,$n as ua,sE as va,jo as wa,lE as xa,cE as ya,hE as za};