@stacksjs/rpx 0.11.9 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +166 -162
- package/dist/chunk-00z9z9an.js +156 -0
- package/dist/chunk-747af2w4.js +1 -0
- package/dist/chunk-end75nnv.js +1 -0
- package/dist/{chunk-jpf41gb9.js → chunk-zs1tyy8z.js} +2 -2
- package/dist/daemon.d.ts +4 -0
- package/dist/dns-state.d.ts +27 -0
- package/dist/dns.d.ts +43 -0
- package/dist/hosts.d.ts +2 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +6 -156
- package/package.json +1 -1
- package/src/daemon.ts +41 -2
- package/src/dns-state.ts +116 -0
- package/src/dns.ts +252 -142
- package/src/hosts.ts +26 -5
- package/src/index.ts +29 -0
- package/src/start.ts +7 -9
- package/src/utils.ts +7 -1
- package/dist/chunk-6z1nzq0x.js +0 -1
- package/dist/chunk-qcdcnadb.js +0 -1
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import{Aa as Eh,Ca as Rh,Da as Th,pa as W,ra as rr,sa as w,wa as Ah,xa as zf,za as zn}from"./chunk-zs1tyy8z.js";import cw from"node:dgram";import*as Yh from"node:fs/promises";import*as Ih from"node:path";import*as Qt from"node:process";import{spawn as vy}from"node:child_process";import*as Lt from"node:fs/promises";import{homedir as Jh}from"node:os";import*as It from"node:path";import*as D from"node:process";var M={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 Mi}from"node:child_process";import k from"node:fs/promises";import*as Mf from"node:os";import{homedir as Gn}from"node:os";import{join as Q}from"node:path";import*as Yt from"node:process";import{createRequire as zh}from"node:module";import Vn from"node:os";import pn from"node:path";import{existsSync as es,statSync as fs}from"fs";import{existsSync as Gh,mkdirSync as Jw,readdirSync as Nw,readFileSync as qh,writeFileSync as jw}from"fs";import{homedir as ui}from"os";import{dirname as Yw,resolve as Tt}from"path";import Vr from"process";import{existsSync as ss,statSync as ls}from"fs";import{existsSync as we,mkdirSync as Kh,readdirSync as xh,writeFileSync as kh}from"fs";import{homedir as ai}from"os";import{dirname as cs,resolve as ht}from"path";import ci from"process";import{join as Dh,relative as bh,resolve as hs}from"path";import Wr from"process";import{existsSync as Ps,mkdirSync as Kw,readdirSync as xw,writeFileSync as kw}from"fs";import{homedir as Pn}from"os";import{dirname as Vw,resolve as ct}from"path";import Di from"process";import{join as Vh,relative as ph,resolve as os}from"path";import Yr from"process";import{existsSync as vs,mkdirSync as Qw,readdirSync as t0,writeFileSync as i0}from"fs";import{dirname as n0,resolve as Ir}from"path";import me from"process";import{Buffer as ti}from"buffer";import{createCipheriv as Ph,createDecipheriv as vh,randomBytes as vn}from"crypto";import{closeSync as Xn,createReadStream as us,createWriteStream as Xh,existsSync as Qn,fsyncSync as as,openSync as $s,writeFileSync as Qh}from"fs";import{access as to,constants as ys,mkdir as io,readdir as $r,rename as ws,stat as $i,unlink as yr,writeFile as te}from"fs/promises";import{join as yi}from"path";import rt from"process";import{pipeline as ro}from"stream/promises";import{createGzip as ms}from"zlib";import wi from"process";import Gt from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as no,createDecipheriv as eo,randomBytes as ie}from"crypto";import{closeSync as re,createReadStream as ds,createWriteStream as fo,existsSync as wr,fsyncSync as As,openSync as Es,writeFileSync as so}from"fs";import{access as lo,constants as Ts,mkdir as co,readdir as mr,rename as gs,stat as mi,unlink as dr,writeFile as ne}from"fs/promises";import{isAbsolute as ho,join as di,resolve as oo}from"path";import N from"process";import{pipeline as uo}from"stream/promises";import{createGzip as Ss}from"zlib";import Ai from"process";import qt from"process";import Ar from"process";import{existsSync as Er}from"fs";import{resolve as ee}from"path";import{existsSync as ao}from"fs";import{existsSync as $o,readdirSync as yo}from"fs";import{extname as fe,resolve as Cs}from"path";import wo from"process";import{join as mo,relative as Ao,resolve as Rs}from"path";import Or from"process";import{Buffer as Mt}from"buffer";import{createCipheriv as Eo,createDecipheriv as To,randomBytes as se}from"crypto";import{closeSync as le,createReadStream as Bs,createWriteStream as go,existsSync as Tr,fsyncSync as Us,openSync as Fs,writeFileSync as So}from"fs";import{access as Co,constants as Js,mkdir as Ro,readdir as gr,rename as Ns,stat as Ei,unlink as Sr,writeFile as ce}from"fs/promises";import{isAbsolute as Bo,join as Ti,resolve as Uo}from"path";import j from"process";import{pipeline as Fo}from"stream/promises";import{createGzip as js}from"zlib";import gi from"process";import Kt from"process";import Cr from"process";import{existsSync as Rr}from"fs";import{resolve as he}from"path";import{existsSync as Jo}from"fs";import{exec as Pu}from"node:child_process";import xs from"node:fs";import vu from"node:os";import Ut from"node:path";import Yl from"node:process";import{promisify as Xu}from"node:util";import Bi from"node:crypto";import xt from"node:fs";import Ne from"node:path";import{execSync as ps}from"node:child_process";import br from"node:os";var Cw=zh(import.meta.url);class Xs{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 r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??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 r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!es(t))return!0;return fs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=es(r)?fs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Qs{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),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 r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Hr=new Xs,je=new Qs,No=Object.defineProperty,jo=(t)=>t;function _o(t,i){this[t]=jo.bind(null,i)}var Wo=(t,i)=>{for(var r in i)No(t,r,{get:i[r],enumerable:!0,configurable:!0,set:_o.bind(i,r)})},Yo=(t,i)=>()=>(t&&(i=t(t=0)),i),tl={};Wo(tl,{withErrorRecovery:()=>nl,tryLoadConfig:()=>ru,loadConfigWithResult:()=>tu,loadConfig:()=>cl,isRetryableError:()=>Vo,isConfigNotFoundError:()=>bo,isBunfigError:()=>el,globalPerformanceMonitor:()=>Pi,globalCache:()=>Ci,getEnvOrDefault:()=>po,generateConfigTypes:()=>nu,defaultGeneratedDir:()=>ml,defaultConfigDir:()=>wl,deepMergeWithArrayStrategy:()=>Oe,deepMerge:()=>fl,createLibraryConfig:()=>eu,config:()=>iu,bunfigPlugin:()=>fu,applyEnvVarsToConfig:()=>xi,TypeGenerationError:()=>Ce,SchemaValidationError:()=>Vi,PluginError:()=>Be,PerformanceMonitor:()=>We,FileSystemError:()=>Se,ErrorFactory:()=>ri,EnvVarError:()=>qr,EnvProcessor:()=>pr,ConfigValidator:()=>He,ConfigValidationError:()=>Te,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>ge,ConfigLoader:()=>Le,ConfigLoadError:()=>bi,ConfigFileLoader:()=>Pr,ConfigCache:()=>_e,CacheUtils:()=>ol,BunfigError:()=>mt,BrowserConfigError:()=>Re,ArrayMergeStrategies:()=>$l});class _e{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 r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??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 r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!ss(t))return!0;return ls(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=ss(r)?ls(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class We{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),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 r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Io(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function Oo(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Ho(t){return t.getStats().size*2}function Ye(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 n=[...i];for(let e of t)if(z(e)&&"name"in e){if(!n.find((f)=>z(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(z(e)&&"path"in e){if(!n.find((f)=>z(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Lr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!z(i)||!z(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(z(e)&&z(r[n]))r[n]=Ye(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&z(e[0])&&z(r[n][0])){let f=[...e];for(let s of r[n])if(z(s)&&"name"in s){if(!f.find((c)=>z(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(z(s)&&"path"in s){if(!f.find((c)=>z(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Lr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Lr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Lr(t[r],i[r]))return!1;return!0}if(z(t)&&z(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Lr(t[e],i[e]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Lo(t,i){if(!vs(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ye(i,n)}catch{return null}}catch{return null}}async function Zo({name:t="",cwd:i,defaultConfig:r}){let n=i||me.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=Ir(n,`${s}${c}`),h=await Lo(l,r);if(h!==null)return h}try{let s=Ir(n,"package.json");if(vs(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ye(r,c)}catch{}}}catch{}return r}function Mo(t,i={}){let r=Yr.cwd();while(r.includes("storage"))r=os(r,"..");let n=os(r,t||"");if(i?.relative)return ph(Yr.cwd(),n);return n}async function zo(){try{let t=await Zo({name:"clarity",defaultConfig:Jr,cwd:Yr.cwd(),endpoint:"",headers:{}});return{...Jr,...t}}catch{return Jr}}function q(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Go(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Gt<"u"){let t=Gt.type;if(t==="renderer"||t==="worker")return!1;return!!(Gt.versions&&(Gt.versions.node||Gt.versions.bun))}return!1}class il{async format(t){let i=await Go(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:wi.pid,hostname:i(),environment:wi.env.NODE_ENV||"development",platform:wi.platform,version:wi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wi.env.NODE_ENV||wi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Zr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Ae},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new il,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??rt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||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{...Nr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Nr};return{...Nr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ae.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await to(this.config.logDirectory,ys.F_OK|ys.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await io(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:ti.from(t);try{if(!Qn(this.currentLogFile))await te(this.currentLogFile,"",{mode:420});if(n=$s(this.currentLogFile,"a",420),Qh(n,c,{flag:"a"}),as(n),n!==void 0)Xn(n),n=void 0;if((await $i(this.currentLogFile)).size===0){if(await te(this.currentLogFile,c,{flag:"w",mode:420}),(await $i(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 o=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,o);let u=s*2**e;await new Promise(($)=>setTimeout($,u)),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(n!==void 0)try{Xn(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,o=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(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,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=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(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return vn(16).toString("hex")}generateKey(){return vn(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(),r=vn(16),n=Ph("aes-256-gcm",i,r),e=ti.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ti.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ms(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ti.from(ti.concat(e)))),n.on("error",r),n.write(t),n.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 $i(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await $r(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await $i(r).catch(()=>null))try{if(await ws(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await yr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await te(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=r.replace(/\.log$/,`-${e}.log`);if(await $i(r).catch(()=>null))await ws(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await $r(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await yr(yi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=us(t),n=Xh(i),e=ms();await ro(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}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 r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}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()})),Qn(this.currentLogFile))try{let t=$s(this.currentLogFile,"r+");as(t),Xn(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 $r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await yr(yi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,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?L.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=rt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${L.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${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 r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];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(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!q()){let h=ul[t],o=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:L.gray(s),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:L.green(s),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u),c){let $=c.split(`
|
|
2
|
+
`);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:L.gray(` ${a}`),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 r=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:L.blue("◐"),tag:r,message:`${L.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
5
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let h=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:L.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new Zr(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(r),r}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!Qn(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 r=this.keys.get(this.currentKeyId);try{let n=ti.isBuffer(t)?t:ti.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=vh("aes-256-gcm",r,e);return c.setAuthTag(f),ti.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!q()){let f=t.split(`
|
|
6
|
+
`),s=Math.max(...f.map((o)=>o.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((o)=>{let u=" ".repeat(s-o.length-2);return`│ ${o}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:L.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(c)})),h.forEach((o)=>console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(o),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(l),showTimestamp:!1}))}else if(!q())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${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(`${L.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();rt.stdin.removeListener("data",r);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",r)})}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 r=t;if(i&&i.length>0){let e=/%([sdijfo%])/g,f=0;if(r=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)r+=` ${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?L.gray(this.formatTag(this.name)):"",f=L.blue("◐");console.error(`${f} ${e} ${L.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}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 r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||q()||!rt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=L.green("━".repeat(n)),s=L.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=i||r===100?L.green("✓"):L.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=rt.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,rt.stdout.write(t.lastRenderedLine),i)rt.stdout.write(`
|
|
9
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||q()||!rt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await $r(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=yi(this.config.logDirectory,n);if(t.before)try{if((await $i(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await yr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Fr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&_(i[0])&&"id"in i[0]&&i[0].id===3&&_(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(_(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(_(t)&&"arr"in t&&Array.isArray(t.arr)&&_(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&_(i[0])&&_(t[0])){let n=[...i];for(let e of t)if(_(e)&&"name"in e){if(!n.find((f)=>_(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(_(e)&&"path"in e){if(!n.find((f)=>_(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Mr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!_(i)||!_(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(_(e)&&_(r[n]))r[n]=Fr(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&_(e[0])&&_(r[n][0])){let f=[...e];for(let s of r[n])if(_(s)&&"name"in s){if(!f.find((c)=>_(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(_(s)&&"path"in s){if(!f.find((c)=>_(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Mr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Ie(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:Fr(t,i);if(Array.isArray(t))return r==="replace"?i:Fr(t,i);if(!_(i)||!_(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=Fr(s,f);else if(_(f)&&_(s))n[e]=Ie(s,f,r);else n[e]=f}return n}function Mr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mr(t[r],i[r]))return!1;return!0}if(_(t)&&_(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Mr(t[e],i[e]))return!1}return!0}return!1}function _(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Br(t,i,r="replace"){if(!Ps(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Ie(i,e,r)}catch{return null}}catch{return null}}function qo(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${u.map($).join("_")}`,m=`${n}_${u.map((y)=>y.toUpperCase()).join("_")}`;if(r)et.info(`Checking environment variable ${a} for config ${t}.${u.join(".")}`);if(typeof o==="object"&&o!==null&&!Array.isArray(o))l[h]=f(o,u);else{let y=Di.env[a]||Di.env[m];if(y!==void 0){if(r)et.info(`Using environment variable ${y?a:m} for config ${t}.${u.join(".")}`);if(typeof o==="number")l[h]=Number(y);else if(typeof o==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(o))try{let d=JSON.parse(y);if(Array.isArray(d))l[h]=d;else l[h]=y.split(",").map((A)=>A.trim())}catch{l[h]=y.split(",").map((d)=>d.trim())}else l[h]=y}}}return l}return f(e)}async function Ko({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?qo(t,e,f):e,h=r||Di.cwd(),o=[".ts",".js",".mjs",".cjs",".json"];if(f)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let u=[t,`.${t}`].filter(Boolean),$=[`${t}.config`,`.${t}.config`].filter(Boolean),a=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([h,ct(h,"config"),ct(h,".config"),n?ct(h,n):void 0].filter(Boolean)));for(let d of y){if(f)et.info(`Searching for configuration in: ${d}`);let A=[ct(h,"config"),ct(h,".config")].concat(n?[ct(h,n)]:[]).includes(d)?[...u,...$,...a,...m]:[...$,...u,...m,...a];for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from: ${O}`);return H}}}if(t){let d=ct(Pn(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)et.info(`Checking user config directory: ${d}`);for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory: ${O}`);return H}}}if(t){let d=ct(Pn(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)et.info(`Checking user config directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory dotfile: ${O}`);return H}}}if(t){let d=Pn(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)et.info(`Checking user home directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user home directory: ${O}`);return H}}}try{let d=ct(h,"package.json");if(Ps(d)){let A=await import(d),g=A[t];if(!g&&i){if(g=A[i],g&&f)et.success(`Using alias "${i}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(f)et.success(`Configuration loaded from package.json: ${g===A[t]?t:i}`);return Ie(l,g,c)}catch(I){if(f)et.warn("Failed to merge package.json config:",I)}}}catch(d){if(f)et.warn("Failed to load package.json:",d)}if(f)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function xo(t,i={}){let r=Wr.cwd();while(r.includes("storage"))r=hs(r,"..");let n=hs(r,t||"");if(i?.relative)return bh(Wr.cwd(),n);return n}async function ko(){try{let t=await Ko({name:"clarity",alias:"logging",defaultConfig:jr,cwd:Wr.cwd()});return{...jr,...t||{}}}catch{return jr}}function b(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Do(){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 rl{async format(t){let i=await Do(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}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 zr{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={...Ee},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new rl,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??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||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},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{..._r,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{..._r};return{..._r,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ee.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!b()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await lo(this.config.logDirectory,Ts.F_OK|Ts.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await co(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(!wr(this.currentLogFile))await ne(this.currentLogFile,"",{mode:420});if(n=Es(this.currentLogFile,"a",420),so(n,c,{flag:"a"}),As(n),n!==void 0)re(n),n=void 0;if((await mi(this.currentLogFile)).size===0){if(await ne(this.currentLogFile,c,{flag:"w",mode:420}),(await mi(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 o=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,o);let u=s*2**e;await new Promise(($)=>setTimeout($,u)),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(n!==void 0)try{re(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,o=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return di(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(b())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,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=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(n.length>f)for(let[s]of n.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(),r=ie(16),n=no("aes-256-gcm",i,r),e=Zt.isBuffer(t)?t:Zt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Zt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Ss(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Zt.from(Zt.concat(e)))),n.on("error",r),n.write(t),n.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(b())return;if(!this.shouldWriteToFile())return;let t=await mi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await mr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await mi(r).catch(()=>null))try{if(await gs(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await dr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ne(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=r.replace(/\.log$/,`-${e}.log`);if(await mi(r).catch(()=>null))await gs(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await mr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await dr(di(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=ds(t),n=fo(i),e=Ss();await uo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}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()})),wr(this.currentLogFile))try{let t=Es(this.currentLogFile,"r+");As(t),re(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(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await mr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await dr(di(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,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()?R.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||b())return!1;let t=typeof N.env.NO_COLOR<"u",i=N.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof N.stderr<"u"&&N.stderr.isTTY||typeof N.stdout<"u"&&N.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=N.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${R.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${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 r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];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(n<i.length)e+=` ${i.slice(n).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,(r,n,e)=>{let f=R.underline(R.blue(n)),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,(r,n)=>R.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>R.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>R.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>R.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>R.strikethrough(n)),i}supportsHyperlinks(){if(b())return!1;let t=N.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 r=N.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(ho(i)||i.startsWith("./")||i.startsWith("../"))i=oo(i);else return null;return wr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":al[t],$=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:R.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:R.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
|
|
10
|
+
`);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:R.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
11
|
+
`;if(c)o+=`${c}
|
|
12
|
+
`;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!b()&&N.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()&&!b()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!b()&&N.stdout.isTTY)N.stdout.write(`
|
|
13
|
+
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!b()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":R.blue("◐"),tag:r,message:`${R.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
14
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":R.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!b())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}`,r=new zr(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(r),r}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!wr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ds(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 r=this.keys.get(this.currentKeyId);try{let n=Zt.isBuffer(t)?t:Zt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=eo("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=Zt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(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,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
15
|
+
`),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:R.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(o),showTimestamp:!1}))}else if(!b())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
|
|
16
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(b())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${R.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}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 r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let o=i[c++];switch(h){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${R.blue("◐")} `;console.error(`${c}${s} ${R.cyan(n)}`)}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()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=R.green("━".repeat(n)),s=R.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?R.green("✓"):R.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${R.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=N.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,N.stdout.write(t.lastRenderedLine),i)N.stdout.write(`
|
|
18
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||b()||!N.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(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await mr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=di(this.config.logDirectory,n);if(t.before)try{if((await mi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await dr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function nl(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function el(t){return t instanceof mt}function bo(t){return t instanceof Gr}function Vo(t){if(el(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 pr{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,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Pi.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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=Ar.env[l]||(h?Ar.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=Ar.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof qr)throw u;throw ri.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))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(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Ar.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.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 r=`Environment Variables for ${i}:
|
|
19
|
+
|
|
20
|
+
`;for(let n of t)r+=`${n.key}
|
|
21
|
+
`,r+=` Type: ${n.type}
|
|
22
|
+
`,r+=` Description: ${n.description}
|
|
23
|
+
`,r+=` Example: ${n.example}
|
|
24
|
+
|
|
25
|
+
`;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
|
|
26
|
+
|
|
27
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
28
|
+
`,r+=`|----------|------|-------------|----------|
|
|
29
|
+
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
30
|
+
`;return r}}function po(t,i){let r=hl("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function fl(t,i,r={}){return sl(t,i,r,new WeakMap)}function sl(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;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 ll(t,i,e,n);if(!gt(i)||!gt(t))return i;return Qo(t,i,r,n)}function ll(t,i,r,n){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(r){case"replace":return i;case"concat":return Po(t,i);case"smart":return vo(t,i,n);default:return i}return i}function Po(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>de(e,n)))r.push(n);return r}function vo(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(gt(i[0])&>(t[0]))return Xo(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Xo(t,i,r){let n=[...i];for(let e of t){if(!gt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>gt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Qo(t,i,r,n){let e=i;if(gt(e)&&n.has(e))return n.get(e);let f={...t};if(gt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(gt(c)&>(l))f[s]=sl(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ll(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Oe(t,i,r="replace"){return fl(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function de(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!de(t[r],i[r]))return!1;return!0}if(gt(t)&>(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!de(t[e],i[e]))return!1}return!0}return!1}function gt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Pr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Ci.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Er(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new bi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new bi(t,Error("Configuration must export a valid object"),"unknown");let m={config:Oe(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Ci.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 Pi.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(ee(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return nl(async()=>{return Er(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Er(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=ee(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=ee(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}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(!Er(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))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(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class He{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await Pi.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!ao(i))throw new Vi(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Vi(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,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(n.push({path:r,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(n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,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=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.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(n.push({path:r?`${r}.${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=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.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:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;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:yl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Le{fileLoader=new Pr;envProcessor=new pr;validator=new He;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}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 o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))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(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Ft.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Ft.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||ci.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(ht(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw ri.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?xi(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)Ft.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)Ft.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?xi(t,r,e):r,c=[ht(ai(),".config",t),ht(ai(),".config"),ai()];for(let l of c){if(e)Ft.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)Ft.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?xi(t,n,f):n;try{let l=ht(r,"package.json");if(!we(l))return null;let h=await import(l),o=h[t],u=t;if(!o&&i)o=h[i],u=i;if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)Ft.success(`Configuration loaded from package.json: ${u}`);return{config:Oe(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Ft.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:xi(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(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(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Ci.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Ci.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.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,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(ht(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[ht(ai(),".config",t),ht(ai(),".config"),ai()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function _s(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")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function tu(t){return kt.loadConfig({...t,__strictErrorHandling:!0})}async function cl(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await kt.loadConfig(t);else n=await kt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Ft.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await kt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function iu(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await kt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&_s(r)))return(await kt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await kt.loadConfig({...t,cwd:t.cwd||ci.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&_s(i)))return(await kt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function ru(t,i,r="replace"){let n=new Pr;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function xi(t,i,r=!1){let n=new pr,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=ci.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}function nu(t){let i=ht(ci.cwd(),t.configDir),r=ht(ci.cwd(),t.generatedDir),n=ht(r,"config-types.ts");if(!we(cs(n)))Kh(cs(n),{recursive:!0,mode:511});let e=we(i)?xh(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Wu}
|
|
31
|
+
export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
|
|
32
|
+
`;kh(n,f,{mode:438})}function eu(t){let i=null,r=null,n=()=>{if(!r)r=cl(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)Ft.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),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 fu(t){let i=Cs(wo.cwd(),t?.configDir||"./config");function r(){if(!$o(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=yo(i).filter((l)=>e.has(fe(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 o=fe(h).toLowerCase(),u=c.get(l);if(!u){c.set(l,h);continue}let $=fe(u).toLowerCase();if(f.indexOf(o)<f.indexOf($))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 n(){let e=r(),f=e.map((l)=>l.base),s=f.length?f.map((l)=>`'${l}'`).join(" | "):"string",c=e.length?`{
|
|
33
|
+
${e.map((l)=>{let h=Cs(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:n(),loader:"ts"}})}}}var hl,Ci,Pi,ol,su,lu,Ws,Jr,Ae,nt,L,cu,Ys,hu,Is,ou,uu,oe,au,Os,Hs,ue,$u,yu,wu,mu,Nr,ul,du,et,Au,Eu,Ls,jr,Ee,V,R,Tu,Zs,gu,Ms,Su,Cu,ae,Ru,zs,Gs,Bu,$e,Uu,Fu,Ju,Nu,ju,_r,al,_u,Wu="0.15.6",mt,Gr,bi,Te,ge,qr,Se,Ce,Vi,Re,Be,ri,$l,yl,Ft,kt,wl,ml,Yu=Yo(async()=>{hl=import.meta.require,Ci=new _e,Pi=new We,ol={createKey:Io,isEquivalent:Oo,estimateMemoryUsage:Ho},su=Ir(me.cwd(),"config"),lu=Ir(me.cwd(),"src/generated"),Ws=Yr.env.CLARITY_LOG_DIR||Vh(Mo(),"logs"),Jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ws,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ae=await zo(),nt={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"},L=nt,cu=nt.red,Ys=nt.green,hu=nt.yellow,Is=nt.blue,ou=nt.magenta,uu=nt.cyan,oe=nt.white,au=nt.gray,Os=nt.bgRed,Hs=nt.bgYellow,ue=nt.bold,$u=nt.dim,yu=nt.italic,wu=nt.underline,mu=nt.reset,Nr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ul={debug:"\uD83D\uDD0D",info:Is("ℹ"),success:Ys("✓"),warning:Hs(oe(ue(" WARN "))),error:Os(oe(ue(" ERROR ")))},du=new Zr("stacks"),et=new Zr("bunfig",{showTags:!0}),Au=ct(Di.cwd(),"config"),Eu=ct(Di.cwd(),"src/generated"),Ls=Wr.env.CLARITY_LOG_DIR||Dh(xo(),"logs"),jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ls,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ee=await ko(),V={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},R=V,Tu=V.red,Zs=V.green,gu=V.yellow,Ms=V.blue,Su=V.magenta,Cu=V.cyan,ae=V.white,Ru=V.gray,zs=V.bgRed,Gs=V.bgYellow,Bu=V.bgGray,$e=V.bold,Uu=V.dim,Fu=V.italic,Ju=V.underline,Nu=V.strikethrough,ju=V.reset,_r={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},al={debug:"\uD83D\uDD0D",info:Ms("ℹ"),success:Zs("✓"),warning:Gs(ae($e(" WARN "))),error:zs(ae($e(" ERROR ")))},_u=new zr("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,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Gr=class extends mt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},bi=class extends mt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Te=class extends mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},ge=class extends mt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qr=class extends mt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},Se=class extends mt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Ce=class extends mt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Vi=class extends mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},Re=class extends mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},Be=class extends mt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ri={configNotFound(t,i,r){return new Gr(t,i,r)},configLoad(t,i,r){return new bi(t,i,r)},configValidation(t,i,r){return new Te(t,i,r)},configMerge(t,i,r,n){return new ge(t,i,r,n)},envVar(t,i,r,n){return new qr(t,i,r,n)},fileSystem(t,i,r){return new Se(t,i,r)},typeGeneration(t,i,r){return new Ce(t,i,r)},schemaValidation(t,i,r){return new Vi(t,i,r)},browserConfig(t,i,r,n){return new Re(t,i,r,n)},plugin(t,i,r){return new Be(t,i,r)}},$l={replace:"replace",concat:"concat",smart:"smart"},yl=/^https?:\/\//,Ft=new zr("bunfig",{showTags:!0}),kt=new Le,wl=ht(ci.cwd(),"config"),ml=ht(ci.cwd(),"src/generated")});function Iu(t,i={}){let r=Or.cwd();while(r.includes("storage"))r=Rs(r,"..");let n=Rs(r,t||"");if(i?.relative)return Ao(Or.cwd(),n);return n}var Ou=Or.env.CLARITY_LOG_DIR||mo(Iu(),"logs"),dl={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ou,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Kr={...dl},V0=(async()=>{try{let{loadConfig:t}=await Yu().then(()=>tl),i=await t({name:"clarity",alias:"logging",defaultConfig:dl,cwd:Or.cwd()});if(i)Object.assign(Kr,i)}catch{}return Kr})();function p(){if(Kt.env.NODE_ENV==="test"||Kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Hu(){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 Al{async format(t){let i=await Hu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:gi.pid,hostname:i(),environment:gi.env.NODE_ENV||"development",platform:gi.platform,version:gi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:gi.env.NODE_ENV||gi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}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"},U=tt,p0=tt.red,Lu=tt.green,P0=tt.yellow,Zu=tt.blue,v0=tt.magenta,X0=tt.cyan,qs=tt.white,Q0=tt.gray,Mu=tt.bgRed,zu=tt.bgYellow,tm=tt.bgGray,Ks=tt.bold,im=tt.dim,rm=tt.italic,nm=tt.underline,em=tt.strikethrough,fm=tt.reset,ye={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Gu={debug:"\uD83D\uDD0D",info:Zu("ℹ"),success:Lu("✓"),warning:zu(qs(Ks(" WARN "))),error:Mu(qs(Ks(" ERROR ")))};class vr{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={...Kr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Al,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??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||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},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ye,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ye};return{...ye,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Kr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Co(this.config.logDirectory,Js.F_OK|Js.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ro(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:Mt.from(t);try{if(!Tr(this.currentLogFile))await ce(this.currentLogFile,"",{mode:420});if(n=Fs(this.currentLogFile,"a",420),So(n,c,{flag:"a"}),Us(n),n!==void 0)le(n),n=void 0;if((await Ei(this.currentLogFile)).size===0){if(await ce(this.currentLogFile,c,{flag:"w",mode:420}),(await Ei(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 o=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,o);let u=s*2**e;await new Promise(($)=>setTimeout($,u)),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(n!==void 0)try{le(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,o=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 Ti(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 Ti(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ti(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,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=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(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return se(16).toString("hex")}generateKey(){return se(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(),r=se(16),n=Eo("aes-256-gcm",i,r),e=Mt.isBuffer(t)?t:Mt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Mt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=js(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Mt.from(Mt.concat(e)))),n.on("error",r),n.write(t),n.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 Ei(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await gr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ei(r).catch(()=>null))try{if(await Ns(r,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=`${r}.1`;await ce(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=r.replace(/\.log$/,`-${e}.log`);if(await Ei(r).catch(()=>null))await Ns(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await gr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Sr(Ti(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Bs(t),n=go(i),e=js();await Fo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}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()})),Tr(this.currentLogFile))try{let t=Fs(this.currentLogFile,"r+");Us(t),le(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await gr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Sr(Ti(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,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 j.env.NO_COLOR<"u",i=j.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=j.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${U.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${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 r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];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(n<i.length)e+=` ${i.slice(n).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,(r,n,e)=>{let f=U.underline(U.blue(n)),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,(r,n)=>U.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>U.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>U.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>U.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>U.strikethrough(n)),i}supportsHyperlinks(){if(p())return!1;let t=j.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 r=j.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Bo(i)||i.startsWith("./")||i.startsWith("../"))i=Uo(i);else return null;return Tr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Gu[t],$=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:U.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:U.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
|
|
40
|
+
`);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:U.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
41
|
+
`;if(c)o+=`${c}
|
|
42
|
+
`;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&j.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()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!p()&&j.stdout.isTTY)j.stdout.write(`
|
|
43
|
+
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":U.blue("◐"),tag:r,message:`${U.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
44
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=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:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new vr(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(r),r}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!Tr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Bs(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 r=this.keys.get(this.currentKeyId);try{let n=Mt.isBuffer(t)?t:Mt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=To("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=Mt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
45
|
+
`),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:U.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(o),showTimestamp:!1}))}else if(!p())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${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(`${U.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}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 r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let o=i[c++];switch(h){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${U.blue("◐")} `;console.error(`${c}${s} ${U.cyan(n)}`)}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()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=U.green("━".repeat(n)),s=U.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?U.green("✓"):U.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${U.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=j.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,j.stdout.write(t.lastRenderedLine),i)j.stdout.write(`
|
|
48
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!j.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 gr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Ti(this.config.logDirectory,n);if(t.before)try{if((await Ei(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Sr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var sm=new vr("stacks");class jt 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,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class El extends jt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class xr extends jt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class Tl extends jt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class gl extends jt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ze extends jt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class Sl extends jt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Cl extends jt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class kr extends jt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Rl extends jt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class Bl extends jt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Ri={configNotFound(t,i,r){return new El(t,i,r)},configLoad(t,i,r){return new xr(t,i,r)},configValidation(t,i,r){return new Tl(t,i,r)},configMerge(t,i,r,n){return new gl(t,i,r,n)},envVar(t,i,r,n){return new Ze(t,i,r,n)},fileSystem(t,i,r){return new Sl(t,i,r)},typeGeneration(t,i,r){return new Cl(t,i,r)},schemaValidation(t,i,r){return new kr(t,i,r)},browserConfig(t,i,r,n){return new Rl(t,i,r,n)},plugin(t,i,r){return new Bl(t,i,r)}};async function qu(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Me{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,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return je.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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=Cr.env[l]||(h?Cr.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=Cr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof Ze)throw u;throw Ri.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))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(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Cr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.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 r=`Environment Variables for ${i}:
|
|
49
|
+
|
|
50
|
+
`;for(let n of t)r+=`${n.key}
|
|
51
|
+
`,r+=` Type: ${n.type}
|
|
52
|
+
`,r+=` Description: ${n.description}
|
|
53
|
+
`,r+=` Example: ${n.example}
|
|
54
|
+
|
|
55
|
+
`;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
|
|
56
|
+
|
|
57
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
58
|
+
`,r+=`|----------|------|-------------|----------|
|
|
59
|
+
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
60
|
+
`;return r}}function Ku(t,i,r={}){return Ul(t,i,r,new WeakMap)}function Ul(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;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 Fl(t,i,e,n);if(!St(i)||!St(t))return i;return bu(t,i,r,n)}function Fl(t,i,r,n){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(r){case"replace":return i;case"concat":return xu(t,i);case"smart":return ku(t,i,n);default:return i}return i}function xu(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Ue(e,n)))r.push(n);return r}function ku(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(St(i[0])&&St(t[0]))return Du(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Du(t,i,r){let n=[...i];for(let e of t){if(!St(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>St(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function bu(t,i,r,n){let e=i;if(St(e)&&n.has(e))return n.get(e);let f={...t};if(St(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(St(c)&&St(l))f[s]=Ul(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Fl(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Jl(t,i,r="replace"){return Ku(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ue(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Ue(t[r],i[r]))return!1;return!0}if(St(t)&&St(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Ue(t[e],i[e]))return!1}return!0}return!1}function St(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Nl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Hr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Rr(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new xr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new xr(t,Error("Configuration must export a valid object"),"unknown");let m={config:Jl(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Hr.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 je.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(he(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return qu(async()=>{return Rr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Rr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=he(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=he(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}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(!Rr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))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(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var Vu=/^https?:\/\//;class jl{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await je.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Jo(i))throw new kr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new kr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,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(n.push({path:r,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(n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,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=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.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(n.push({path:r?`${r}.${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=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.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:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;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:Vu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var zt=new vr("bunfig",{showTags:!0});function pu(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((r)=>`"${r}"`).join(", ")}`}class _l{fileLoader=new Nl;envProcessor=new Me;validator=new jl;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}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 o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))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(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)zt.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 zt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||Vr.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(Tt(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw Ri.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${pu(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Ur(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)zt.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)zt.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Ur(t,r,e):r,c=[Tt(ui(),".config",t),Tt(ui(),".config"),ui()];for(let l of c){if(e)zt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)zt.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Ur(t,n,f):n;try{let l=Tt(r,"package.json");if(!Gh(l))return null;let h={};try{h=JSON.parse(qh(l,"utf8"))}catch($){if(f)zt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let o=h[t],u=t;if(!o&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){o=h[a],u=a;break}}}if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)zt.success(`Configuration loaded from package.json: ${u}`);return{config:Jl(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)zt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ur(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(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(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Hr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Hr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Tt(t,"config"),Tt(t,".config"),i?Tt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Tt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Tt(ui(),".config",t),Tt(ui(),".config"),ui()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var lm=new _l;function Ur(t,i,r=!1){let n=new Me,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=Vr.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}var cm=Tt(Vr.cwd(),"config"),hm=Tt(Vr.cwd(),"src/generated"),Wl={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:pn.join(Vn.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:pn.join(Vn.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:pn.join(Vn.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},x=Wl,Jt={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 T={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Si={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 Fe(t,i){let r=[];function n(e){let f;try{f=xs.readdirSync(e)}catch{return}for(let s of f){let c=Ut.join(e,s);try{if(xs.statSync(c).isDirectory())n(c);else if(s===i)r.push(e)}catch{continue}}}return n(t),r}function E(t,i,r){if(r||x.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Qu=Xu(Pu);function Il(){return Yl.env.SUDO_PASSWORD}var ks="[redacted]",ta=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),ia=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function ra(t){let i=t.toLowerCase();return ta.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Dr(t){if(Array.isArray(t))return t.map((r)=>Dr(r));if(typeof t==="string")return ia.test(t)?ks:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(ra(r)){i[r]=ks;continue}i[r]=Dr(n)}return i}function Xr(t){return JSON.stringify(Dr(t))}function na(t){let i=Il();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function ii(t,i={}){let r=na(t);try{let{stdout:n,stderr:e}=await Qu(r,{cwd:i.cwd||Yl.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
|
|
61
|
+
Error: ${n.message}`);throw e.stack=n.stack,e}}function Ol(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 ze(t){let i=Ut.join(vu.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:x.basePath&&x.basePath.trim()!==""?x.basePath:i,n=t.certPath?Ut.isAbsolute(t.certPath)?t.certPath:Ut.join(r,t.certPath):Ut.join(r,x.certPath),e=t.keyPath?Ut.isAbsolute(t.keyPath)?t.keyPath:Ut.join(r,t.keyPath):Ut.join(r,x.keyPath),f=t.caCertPath?Ut.isAbsolute(t.caCertPath)?t.caCertPath:Ut.join(r,t.caCertPath):Ut.join(r,x.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function Hl(t){let i=[],r=new Set;if(t.domain)r.add(t.domain);if(t.domains?.length)t.domains.forEach((n)=>r.add(n));for(let n of r)i.push({type:2,value:n});if(t.altNameIPs?.length)for(let n of t.altNameIPs)i.push({type:7,ip:n});if(t.altNameURIs?.length)for(let n of t.altNameURIs)i.push({type:6,value:n});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return E(T.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function Ge(t){let i=t.notBeforeDays??Jt.DEFAULT_NOT_BEFORE_DAYS,r=t.validityDays??(t.validityYears?t.validityYears*365:Jt.DEFAULT_VALIDITY_DAYS);E(T.CERT,"Calculating certificate validity dates",t.verbose);let n=new Date(Date.now()-86400*i*1000),e=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),E(T.CERT,`Validity period: ${n.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:n,notAfter:e}}var Nt={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},ot={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 ki(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function At(t,i){let r=ki(i.length);return Buffer.concat([Buffer.from([t]),r,i])}function pi(t){let i=t.split(".").map(Number),r=[];r.push(40*i[0]+i[1]);for(let n=2;n<i.length;n++){let e=i[n],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;r.push(...f)}return At(Nt.OID,Buffer.from(r))}function Je(t){let i;if(typeof t==="bigint"){let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return At(Nt.INTEGER,i)}function Ll(t,i=0){return At(Nt.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function Zl(t){return At(Nt.OCTET_STRING,t)}function dt(...t){return At(Nt.SEQUENCE,Buffer.concat(t))}function ea(...t){return At(Nt.SET,Buffer.concat(t))}function fa(t){return At(Nt.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function sa(t){return At(Nt.UTF8_STRING,Buffer.from(t,"utf8"))}function la(){return Buffer.from([Nt.NULL,0])}function Ds(t,i,r=!0){let n=160|t|(r?0:0),e=ki(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function bs(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return At(Nt.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(i%100).toString().padStart(2,"0"),n=(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=`${r}${n}${e}${f}${s}${c}Z`;return At(Nt.UTC_TIME,Buffer.from(l,"ascii"))}}function ca(t,i){return dt(bs(t),bs(i))}function Vs(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=ot.COMMON_NAME;break;case"C":n=ot.COUNTRY;break;case"L":n=ot.LOCALITY;break;case"ST":n=ot.STATE;break;case"O":n=ot.ORGANIZATION;break;case"OU":n=ot.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?fa(r.value):sa(r.value),f=dt(pi(n),e);i.push(ea(f))}return dt(...i)}function Ml(t){return dt(pi(t),la())}function ha(t){return t.export({type:"spki",format:"der"})}function oa(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 r=i.split(":"),n=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(r[e]||"0",16);n.writeUInt16BE(f,e*2)}return n}else{let i=t.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(i)}}function ua(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=ki(r.value.length);i.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=oa(r.ip),e=ki(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=ki(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return dt(...i)}function aa(t,i){if(t){if(i!==void 0)return dt(At(1,Buffer.from([255])),Je(i));return dt(At(1,Buffer.from([255])))}return dt()}function $a(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 r=0,n=i;while(n>0&&(n&1)===0)r++,n>>=1;if(i===0)r=7;return Ll(Buffer.from([i]),r)}function ya(t){let i=[];if(t.serverAuth)i.push(pi(ot.SERVER_AUTH));if(t.clientAuth)i.push(pi(ot.CLIENT_AUTH));return dt(...i)}function Ki(t,i,r){let n=[pi(t)];if(i)n.push(At(1,Buffer.from([255])));return n.push(Zl(r)),dt(...n)}function wa(t){let i=[];if(i.push(Ds(0,Je(2))),i.push(Je(t.serialNumber)),i.push(Ml(ot.SHA256_WITH_RSA)),i.push(Vs(t.issuer)),i.push(ca(t.notBefore,t.notAfter)),i.push(Vs(t.subject)),i.push(ha(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(Ki(ot.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,aa(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(Ki(ot.KEY_USAGE,t.extensions.keyUsage.critical??!0,$a(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(Ki(ot.EXTENDED_KEY_USAGE,!1,ya(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(Ki(ot.SUBJECT_ALT_NAME,!1,ua(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(Ki(ot.SUBJECT_KEY_IDENTIFIER,!1,Zl(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(Ds(3,dt(...r)))}return dt(...i)}function ma(t,i){let r=Bi.createSign("SHA256");r.update(t);let n=r.sign(i);return dt(t,Ml(ot.SHA256_WITH_RSA),Ll(n))}function da(t,i){let r=t.toString("base64"),n=[];for(let e=0;e<r.length;e+=64)n.push(r.slice(e,e+64));return`-----BEGIN ${i}-----
|
|
62
|
+
${n.join(`
|
|
63
|
+
`)}
|
|
64
|
+
-----END ${i}-----
|
|
65
|
+
`}function qe(){return Bi.randomBytes(20)}function zl(t=2048){let{privateKey:i,publicKey:r}=Bi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function Aa(t){let i=t.export({type:"spki",format:"der"});return Bi.createHash("sha1").update(i).digest()}function Gl(t){let i={serialNumber:t.serialNumber||qe(),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:Aa(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 r=wa(i),n=ma(r,t.signingKey);return{certificate:da(n,"CERTIFICATE"),certificateDer:n}}function ql(t){return t.export({type:"pkcs8",format:"pem"})}function Ea(t){return Bi.createPrivateKey(t)}function Ta(t){let i=new Bi.X509Certificate(t),r=i.publicKey,n=[],e=i.subject.split(`
|
|
66
|
+
`);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)n.push({shortName:s.trim(),value:l.trim()})}return{publicKey:r,subject:n}}async function Ke(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Jt.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=zl(i),e=[{shortName:"C",value:t.countryName||x.countryName},{shortName:"ST",value:t.stateName||x.stateName},{shortName:"L",value:t.localityName||x.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}=Ge({validityYears:t.validityYears||Jt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=Gl({serialNumber:qe(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:ql(r),notBefore:f,notAfter:s}}async function xe(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${Xr(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Ta(t.rootCA.certificate),r=Ea(t.rootCA.privateKey);E("ca",`Generating ${Jt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=Jt.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=zl(n),s=t.commonName||Ol(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||x.countryName},{shortName:"ST",value:t.stateName||x.stateName},{shortName:"L",value:t.localityName||x.localityName},{shortName:"O",value:t.organizationName||x.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=Ge({validityDays:t.validityDays||Jt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),o=Hl(t),u=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},$=t.extKeyUsage||{serverAuth:!0},{certificate:a}=Gl({serialNumber:qe(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:$,subjectAltName:o});return{certificate:a,privateKey:ql(e),notBefore:l,notAfter:h}}function Kl(t,i){E(T.STORAGE,`Storing certificate and private key with options: ${Xr(i)}`,i?.verbose);let{certPath:r,keyPath:n}=ze({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(T.STORAGE,`Certificate path: ${r}`,i?.verbose),E(T.STORAGE,`Private key path: ${n}`,i?.verbose);let e=Ne.dirname(r);if(!xt.existsSync(e))E(T.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),xt.mkdirSync(e,{recursive:!0});E(T.STORAGE,"Writing certificate file",i?.verbose),xt.writeFileSync(r,t.certificate);let f=Ne.dirname(n);if(!xt.existsSync(f))E(T.STORAGE,`Creating private key directory: ${f}`,i?.verbose),xt.mkdirSync(f,{recursive:!0});return E(T.STORAGE,"Writing private key file",i?.verbose),xt.writeFileSync(n,t.privateKey),E(T.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function xl(t,i){E(T.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=ze({basePath:i?.basePath,caCertPath:i?.caCertPath});E(T.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=Ne.dirname(r);if(!xt.existsSync(n))E(T.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),xt.mkdirSync(n,{recursive:!0});return E(T.STORAGE,"Writing CA certificate file",i?.verbose),xt.writeFileSync(r,t),E(T.STORAGE,"CA certificate stored successfully",i?.verbose),r}async function ga(t,i){if(br.platform()!=="darwin")return!1;try{let r=ps(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return E(T.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(ps("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(r))return E(T.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(T.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return E(T.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Sa={platform:"darwin",async addCertificate(t,i){if(await ga(t,i?.verbose)){E(T.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Si.success("Certificate is already trusted in system keychain");return}E(T.TRUST,"Adding certificate to macOS keychain",i?.verbose),await ii(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||x.commonName;E(T.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await ii(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),E(T.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw E(T.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Ca={platform:"win32",async addCertificate(t,i){E(T.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await ii(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||x.commonName;E(T.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await ii(`certutil -delstore -enterprise Root "${n}"`),E(T.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw E(T.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Ra={platform:"linux",async addCertificate(t,i){E(T.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=br.homedir(),n=Jt.LINUX_CERT_DB_FILENAME,e=Jt.LINUX_TRUST_ARGS;E(T.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=Fe(r,n);if(f.length===0){Si.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(T.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(T.TRUST,`Attempting to delete existing cert for ${x.commonName}`,i?.verbose),await ii(`certutil -d sql:${s} -D -n ${x.commonName}`)}catch(c){E(T.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(T.TRUST,`Adding new certificate to ${s}`,i?.verbose),await ii(`certutil -d sql:${s} -A -t ${e} -n ${x.commonName} -i ${t}`),Si.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||x.commonName;E(T.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=br.homedir(),f=Jt.LINUX_CERT_DB_FILENAME;E(T.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=Fe(e,f);if(s.length===0){Si.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(T.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await ii(`certutil -d sql:${c} -D -n "${n}"`),Si.info(`Cert removed from ${c}`)}catch(l){E(T.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},Ba={darwin:Sa,win32:Ca,linux:Ra};async function ke(t,i,r){E(T.TRUST,`Adding certificate to system trust store with options: ${Xr(r)}`,r?.verbose),E(T.TRUST,"Storing certificate and private key",r?.verbose);let n=Kl(t,r);E(T.TRUST,"Storing CA certificate",r?.verbose);let e=xl(i,r),f=br.platform();E(T.TRUST,`Detected platform: ${f}`,r?.verbose);let s=Ba[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(T.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await s.addCertificate(e,r),E(T.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as If}from"node:os";import{join as Of,resolve as ZA}from"node:path";import{existsSync as kl,statSync as Dl}from"fs";import{existsSync as Ua,mkdirSync as Xm,readdirSync as Qm,readFileSync as Fa,writeFileSync as td}from"fs";import{homedir as Ui}from"os";import{dirname as nd,resolve as Ct}from"path";import Yn from"process";import{existsSync as bl,statSync as Vl}from"fs";import{existsSync as af,mkdirSync as Ja,readdirSync as Na,writeFileSync as ja}from"fs";import{homedir as Fi}from"os";import{dirname as pl,resolve as at}from"path";import hi from"process";import{join as _a,relative as Wa,resolve as Pl}from"path";import Tn from"process";import{existsSync as Yc,mkdirSync as $d,readdirSync as yd,writeFileSync as wd}from"fs";import{homedir as De}from"os";import{dirname as Ad,resolve as ut}from"path";import Xi from"process";import{join as Ya,relative as Ia,resolve as vl}from"path";import gn from"process";import{existsSync as Ic,mkdirSync as Cd,readdirSync as Rd,writeFileSync as Bd}from"fs";import{dirname as Fd,resolve as Sn}from"path";import $f from"process";import{Buffer as ni}from"buffer";import{createCipheriv as Oa,createDecipheriv as Ha,randomBytes as be}from"crypto";import{closeSync as Ve,createReadStream as Xl,createWriteStream as La,existsSync as pe,fsyncSync as Ql,openSync as tc,writeFileSync as Za}from"fs";import{access as Ma,constants as ic,mkdir as za,readdir as Qr,rename as rc,stat as Ji,unlink as tn,writeFile as Pe}from"fs/promises";import{join as Ni}from"path";import ft from"process";import{pipeline as Ga}from"stream/promises";import{createGzip as nc}from"zlib";import ji from"process";import pt from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as qa,createDecipheriv as Ka,randomBytes as ve}from"crypto";import{closeSync as Xe,createReadStream as ec,createWriteStream as xa,existsSync as rn,fsyncSync as fc,openSync as sc,writeFileSync as ka}from"fs";import{access as Da,constants as lc,mkdir as ba,readdir as nn,rename as cc,stat as _i,unlink as en,writeFile as Qe}from"fs/promises";import{isAbsolute as Va,join as Wi,resolve as pa}from"path";import S from"process";import{pipeline as Pa}from"stream/promises";import{createGzip as hc}from"zlib";import Yi from"process";import Pt from"process";import fn from"process";import{existsSync as sn}from"fs";import{resolve as tf}from"path";import{existsSync as va}from"fs";import{existsSync as Xa,readdirSync as Qa}from"fs";import{extname as rf,resolve as oc}from"path";import t$ from"process";import{join as i$,relative as r$,resolve as uc}from"path";import Cn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as n$,createDecipheriv as e$,randomBytes as nf}from"crypto";import{closeSync as ef,createReadStream as ac,createWriteStream as f$,existsSync as ln,fsyncSync as $c,openSync as yc,writeFileSync as s$}from"fs";import{access as l$,constants as wc,mkdir as c$,readdir as cn,rename as mc,stat as Ii,unlink as hn,writeFile as ff}from"fs/promises";import{isAbsolute as h$,join as Oi,resolve as o$}from"path";import C from"process";import{pipeline as u$}from"stream/promises";import{createGzip as dc}from"zlib";import Hi from"process";import vt from"process";import un from"process";import{existsSync as an}from"fs";import{resolve as uf}from"path";import{existsSync as _y}from"fs";class _c{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 r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??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 r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!kl(t))return!0;return Dl(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=kl(r)?Dl(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Wc{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),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 r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var En=new _c,Rf=new Wc;var a$=Object.defineProperty,$$=(t)=>t;function y$(t,i){this[t]=$$.bind(null,i)}var w$=(t,i)=>{for(var r in i)a$(t,r,{get:i[r],enumerable:!0,configurable:!0,set:y$.bind(i,r)})},m$=(t,i)=>()=>(t&&(i=t(t=0)),i),Oc={};w$(Oc,{withErrorRecovery:()=>Zc,tryLoadConfig:()=>M$,loadConfigWithResult:()=>L$,loadConfig:()=>Kc,isRetryableError:()=>_$,isConfigNotFoundError:()=>j$,isBunfigError:()=>Mc,globalPerformanceMonitor:()=>ir,globalCache:()=>Li,getEnvOrDefault:()=>W$,generateConfigTypes:()=>z$,defaultGeneratedDir:()=>vc,defaultConfigDir:()=>Pc,deepMergeWithArrayStrategy:()=>Nf,deepMerge:()=>zc,createLibraryConfig:()=>G$,config:()=>Z$,bunfigPlugin:()=>q$,applyEnvVarsToConfig:()=>vi,TypeGenerationError:()=>Tf,SchemaValidationError:()=>tr,PluginError:()=>Sf,PerformanceMonitor:()=>Uf,FileSystemError:()=>Ef,ErrorFactory:()=>ei,EnvVarError:()=>Nn,EnvProcessor:()=>In,ConfigValidator:()=>jf,ConfigValidationError:()=>df,ConfigNotFoundError:()=>Jn,ConfigMergeError:()=>Af,ConfigLoader:()=>_f,ConfigLoadError:()=>Qi,ConfigFileLoader:()=>On,ConfigCache:()=>Bf,CacheUtils:()=>kc,BunfigError:()=>Et,BrowserConfigError:()=>gf,ArrayMergeStrategies:()=>Vc});class Bf{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 r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}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(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??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 r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!bl(t))return!0;return Vl(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=bl(r)?Vl(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Uf{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),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 r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function d$(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function A$(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function E$(t){return t.getStats().size*2}function Ff(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 n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((s)=>G(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((s)=>G(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Rn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=Ff(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let s of r[n])if(G(s)&&"name"in s){if(!f.find((l)=>G(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((l)=>G(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Rn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Rn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Rn(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Rn(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function T$(t,i){if(!Ic(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ff(i,n)}catch{return null}}catch{return null}}async function g$({name:t="",cwd:i,defaultConfig:r}){let n=i||$f.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=Sn(n,`${s}${c}`),h=await T$(l,r);if(h!==null)return h}try{let s=Sn(n,"package.json");if(Ic(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Ff(r,l)}catch{}}}catch{}return r}function S$(t,i={}){let r=gn.cwd();while(r.includes("storage"))r=vl(r,"..");let n=vl(r,t||"");if(i?.relative)return Ia(gn.cwd(),n);return n}async function C$(){try{let t=await g$({name:"clarity",defaultConfig:wn,cwd:gn.cwd(),endpoint:"",headers:{}});return{...wn,...t}}catch{return wn}}function K(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function R$(){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 Hc{async format(t){let i=await R$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bn{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={...wf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Hc,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 r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||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{...mn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...mn};return{...mn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:wf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Ma(this.config.logDirectory,ic.F_OK|ic.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await za(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:ni.from(t);try{if(!pe(this.currentLogFile))await Pe(this.currentLogFile,"",{mode:420});if(e=tc(this.currentLogFile,"a",420),Za(e,l,{flag:"a"}),Ql(e),e!==void 0)Ve(e),e=void 0;if((await Ji(this.currentLogFile)).size===0){if(await Pe(this.currentLogFile,l,{flag:"w",mode:420}),(await Ji(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let o=h;if(o.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(o.code)){if(f<s-1){let u=typeof o.message==="string"?o.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(o?.code&&["ENOSPC","EDQUOT"].includes(o.code))throw Error(`Disk quota exceeded or no space left on device: ${o.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",o),o}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 o=l,u=typeof o.message==="string"?o.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((o)=>setTimeout(o,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Ni(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(K())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,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 be(16).toString("hex")}generateKey(){return be(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=be(16),n=Oa("aes-256-gcm",i,r),e=ni.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ni.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=nc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ni.from(ni.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(K())return;let t=await Ji(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Qr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ji(r).catch(()=>null))try{if(await rc(r,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=`${r}.1`;await Pe(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=r.replace(/\.log$/,`-${e}.log`);if(await Ji(r).catch(()=>null))await rc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await Qr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await tn(Ni(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=Xl(t),n=La(i),e=nc();await Ga(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}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 r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}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()})),pe(this.currentLogFile))try{let t=tc(this.currentLogFile,"r+");Ql(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(!K()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Qr(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await tn(Ni(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,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?Z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=ft.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${Z.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${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 r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];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(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!K()){let h=Dc[t],o=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:Z.gray(s),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:Z.green(s),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u),c){let $=c.split(`
|
|
67
|
+
`);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:Z.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!K()){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&&!K()){let r=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Z.blue("◐"),tag:r,message:`${Z.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
|
|
70
|
+
`,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!K()){let o=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:Z.green("✓"),tag:o,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!K())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Bn(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(r),r}createReadStream(){if(K())throw Error("createReadStream is not supported in browser environments");if(!pe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xl(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 r=this.keys.get(this.currentKeyId);try{let n=ni.isBuffer(t)?t:ni.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=Ha("aes-256-gcm",r,e);return c.setAuthTag(f),ni.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return K()}isServerMode(){return!K()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!K()){let f=t.split(`
|
|
71
|
+
`),s=Math.max(...f.map((o)=>o.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((o)=>{let u=" ".repeat(s-o.length-2);return`│ ${o}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(c)})),h.forEach((o)=>console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(o),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(l),showTimestamp:!1}))}else if(!K())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
|
|
72
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(K())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${Z.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();ft.stdin.removeListener("data",r);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",r)})}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 r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let o=i[c++];switch(h){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!K()){let s=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",c=Z.blue("◐");console.error(`${c} ${s} ${Z.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
73
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||K()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())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||K())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||K())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||K()||!ft.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=Z.green("━".repeat(n)),s=Z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=i||r===100?Z.green("✓"):Z.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${Z.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=ft.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,ft.stdout.write(t.lastRenderedLine),i)ft.stdout.write(`
|
|
74
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||K()||!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(K()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Qr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Ni(this.config.logDirectory,n);if(t.before)try{if((await Ji(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await tn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function yn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&Y(i[0])&&"id"in i[0]&&i[0].id===3&&Y(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(Y(i)&&Y(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(Y(t)&&"arr"in t&&Array.isArray(t.arr)&&Y(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&Y(i[0])&&Y(t[0])){let n=[...i];for(let e of t)if(Y(e)&&"name"in e){if(!n.find((s)=>Y(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(Y(e)&&"path"in e){if(!n.find((s)=>Y(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Un(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!Y(i)||!Y(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(Y(e)&&Y(r[n]))r[n]=yn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&Y(e[0])&&Y(r[n][0])){let f=[...e];for(let s of r[n])if(Y(s)&&"name"in s){if(!f.find((l)=>Y(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(Y(s)&&"path"in s){if(!f.find((l)=>Y(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Un(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Jf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:yn(t,i);if(Array.isArray(t))return r==="replace"?i:yn(t,i);if(!Y(i)||!Y(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=yn(s,f);else if(Y(f)&&Y(s))n[e]=Jf(s,f,r);else n[e]=f}return n}function Un(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Un(t[r],i[r]))return!1;return!0}if(Y(t)&&Y(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Un(t[e],i[e]))return!1}return!0}return!1}function Y(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function on(t,i,r="replace"){if(!Yc(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Jf(i,e,r)}catch{return null}}catch{return null}}function B$(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${u.map($).join("_")}`,m=`${n}_${u.map((y)=>y.toUpperCase()).join("_")}`;if(r)lt.info(`Checking environment variable ${a} for config ${t}.${u.join(".")}`);if(typeof o==="object"&&o!==null&&!Array.isArray(o))l[h]=f(o,u);else{let y=Xi.env[a]||Xi.env[m];if(y!==void 0){if(r)lt.info(`Using environment variable ${y?a:m} for config ${t}.${u.join(".")}`);if(typeof o==="number")l[h]=Number(y);else if(typeof o==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(o))try{let d=JSON.parse(y);if(Array.isArray(d))l[h]=d;else l[h]=y.split(",").map((A)=>A.trim())}catch{l[h]=y.split(",").map((d)=>d.trim())}else l[h]=y}}}return l}return f(e)}async function U$({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?B$(t,e,f):e,h=r||Xi.cwd(),o=[".ts",".js",".mjs",".cjs",".json"];if(f)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let u=[t,`.${t}`].filter(Boolean),$=[`${t}.config`,`.${t}.config`].filter(Boolean),a=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([h,ut(h,"config"),ut(h,".config"),n?ut(h,n):void 0].filter(Boolean)));for(let d of y){if(f)lt.info(`Searching for configuration in: ${d}`);let g=[ut(h,"config"),ut(h,".config")].concat(n?[ut(h,n)]:[]).includes(d)?[...u,...$,...a,...m]:[...$,...u,...m,...a];for(let I of g)for(let O of o){let H=ut(d,`${I}${O}`),qi=await on(H,l,c);if(qi!==null){if(f)lt.success(`Configuration loaded from: ${H}`);return qi}}}if(t){let d=ut(De(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)lt.info(`Checking user config directory: ${d}`);for(let g of A)for(let I of o){let O=ut(d,`${g}${I}`),H=await on(O,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory: ${O}`);return H}}}if(t){let d=ut(De(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)lt.info(`Checking user config directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ut(d,`${g}${I}`),H=await on(O,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory dotfile: ${O}`);return H}}}if(t){let d=De(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)lt.info(`Checking user home directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ut(d,`${g}${I}`),H=await on(O,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user home directory: ${O}`);return H}}}try{let d=ut(h,"package.json");if(Yc(d)){let A=await import(d),g=A[t];if(!g&&i){if(g=A[i],g&&f)lt.success(`Using alias "${i}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(f)lt.success(`Configuration loaded from package.json: ${g===A[t]?t:i}`);return Jf(l,g,c)}catch(I){if(f)lt.warn("Failed to merge package.json config:",I)}}}catch(d){if(f)lt.warn("Failed to load package.json:",d)}if(f)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function F$(t,i={}){let r=Tn.cwd();while(r.includes("storage"))r=Pl(r,"..");let n=Pl(r,t||"");if(i?.relative)return Wa(Tn.cwd(),n);return n}async function J$(){try{let t=await U$({name:"clarity",alias:"logging",defaultConfig:dn,cwd:Tn.cwd()});return{...dn,...t||{}}}catch{return dn}}function P(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function N$(){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 Lc{async format(t){let i=await N$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}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 Fn{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={...mf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Lc,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??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||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},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...An,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...An};return{...An,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:mf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Da(this.config.logDirectory,lc.F_OK|lc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await ba(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:Dt.from(t);try{if(!rn(this.currentLogFile))await Qe(this.currentLogFile,"",{mode:420});if(e=sc(this.currentLogFile,"a",420),ka(e,l,{flag:"a"}),fc(e),e!==void 0)Xe(e),e=void 0;if((await _i(this.currentLogFile)).size===0){if(await Qe(this.currentLogFile,l,{flag:"w",mode:420}),(await _i(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let o=h;if(o.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(o.code)){if(f<s-1){let u=typeof o.message==="string"?o.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(o?.code&&["ENOSPC","EDQUOT"].includes(o.code))throw Error(`Disk quota exceeded or no space left on device: ${o.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",o),o}finally{if(e!==void 0)try{Xe(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let o=l,u=typeof o.message==="string"?o.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((o)=>setTimeout(o,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Wi(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 Wi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Wi(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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,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 ve(16).toString("hex")}generateKey(){return ve(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(),r=ve(16),n=qa("aes-256-gcm",i,r),e=Dt.isBuffer(t)?t:Dt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Dt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=hc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Dt.from(Dt.concat(e)))),n.on("error",r),n.write(t),n.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 _i(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 r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await nn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await _i(r).catch(()=>null))try{if(await cc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await en(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Qe(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=r.replace(/\.log$/,`-${e}.log`);if(await _i(r).catch(()=>null))await cc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await nn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await en(Wi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=ec(t),n=xa(i),e=hc();await Pa(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}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()})),rn(this.currentLogFile))try{let t=sc(this.currentLogFile,"r+");fc(t),Xe(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 nn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await en(Wi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,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()?B.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof S.env.NO_COLOR<"u",i=S.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=S.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${B.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${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 r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];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(n<i.length)e+=` ${i.slice(n).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,(r,n,e)=>{let f=B.underline(B.blue(n)),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,(r,n)=>B.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>B.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>B.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>B.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>B.strikethrough(n)),i}supportsHyperlinks(){if(P())return!1;let t=S.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 r=S.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Va(i)||i.startsWith("./")||i.startsWith("../"))i=pa(i);else return null;return rn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":bc[t],$=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:B.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:B.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
|
|
75
|
+
`);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:B.gray(` ${y}`),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 o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
76
|
+
`;if(c)o+=`${c}
|
|
77
|
+
`;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&S.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()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!P()&&S.stdout.isTTY)S.stdout.write(`
|
|
78
|
+
`);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":B.blue("◐"),tag:r,message:`${B.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
|
|
79
|
+
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":B.green("✓"),tag:o,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}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}`,r=new Fn(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(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!rn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ec(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 r=this.keys.get(this.currentKeyId);try{let n=Dt.isBuffer(t)?t:Dt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Ka("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=Dt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
80
|
+
`),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:B.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(o),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${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(`${B.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();S.stdin.removeListener("data",r);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",r)})}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 r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(o,u)=>{if(u==="%")return"%";if(h>=i.length)return o;let $=i[h++];switch(u){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return o}}),h<i.length)r+=` ${i.slice(h).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${B.blue("◐")} `;console.error(`${h}${l} ${B.cyan(n)}`)}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()||!S.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=B.green("━".repeat(n)),s=B.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?B.green("✓"):B.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=S.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,S.stdout.write(t.lastRenderedLine),i)S.stdout.write(`
|
|
83
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!S.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 nn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Wi(this.config.logDirectory,n);if(t.before)try{if((await _i(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await en(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Zc(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Mc(t){return t instanceof Et}function j$(t){return t instanceof Jn}function _$(t){if(Mc(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>t.message.toLowerCase().includes(r.toLowerCase()))}class In{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,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ir.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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=fn.env[l]||(h?fn.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=fn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof Nn)throw u;throw ei.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ei.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(fn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.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 r=`Environment Variables for ${i}:
|
|
84
|
+
|
|
85
|
+
`;for(let n of t)r+=`${n.key}
|
|
86
|
+
`,r+=` Type: ${n.type}
|
|
87
|
+
`,r+=` Description: ${n.description}
|
|
88
|
+
`,r+=` Example: ${n.example}
|
|
89
|
+
|
|
90
|
+
`;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
|
|
91
|
+
|
|
92
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
93
|
+
`,r+=`|----------|------|-------------|----------|
|
|
94
|
+
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
95
|
+
`;return r}}function W$(t,i){let r=xc("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function zc(t,i,r={}){return Gc(t,i,r,new WeakMap)}function Gc(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;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 qc(t,i,e,n);if(!Rt(i)||!Rt(t))return i;return H$(t,i,r,n)}function qc(t,i,r,n){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(r){case"replace":return i;case"concat":return Y$(t,i);case"smart":return I$(t,i,n);default:return i}return i}function Y$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>yf(e,n)))r.push(n);return r}function I$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Rt(i[0])&&Rt(t[0]))return O$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function O$(t,i,r){let n=[...i];for(let e of t){if(!Rt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Rt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function H$(t,i,r,n){let e=i;if(Rt(e)&&n.has(e))return n.get(e);let f={...t};if(Rt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Rt(c)&&Rt(l))f[s]=Gc(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=qc(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Nf(t,i,r="replace"){return zc(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function yf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!yf(t[r],i[r]))return!1;return!0}if(Rt(t)&&Rt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!yf(t[e],i[e]))return!1}return!0}return!1}function Rt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class On{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Li.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!sn(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new Qi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Qi(t,Error("Configuration must export a valid object"),"unknown");let d={config:Nf(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Li.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?ei.configLoad(t,h):ei.configLoad(t,Error(String(h)))}};if(s)return ir.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(tf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Zc(async()=>{return sn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!sn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=tf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=tf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}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((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!sn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))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(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class jf{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await ir.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!va(i))throw new tr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new tr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,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(n.push({path:r,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(n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,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=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.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(n.push({path:r?`${r}.${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=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.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:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;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:pc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class _f{fileLoader=new On;envProcessor=new In;validator=new jf;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}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 o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))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(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw _t.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||hi.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(at(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw ei.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?vi(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)_t.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)_t.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?vi(t,r,e):r,c=[at(Fi(),".config",t),at(Fi(),".config"),Fi()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)_t.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?vi(t,n,f):n;try{let l=at(r,"package.json");if(!af(l))return null;let h=await import(l),o=h[t],u=t;if(!o&&i)o=h[i],u=i;if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)_t.success(`Configuration loaded from package.json: ${u}`);return{config:Nf(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:vi(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(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 ei.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Li.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Li.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(Fi(),".config",t),at(Fi(),".config"),Fi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function Ac(t){let r=!(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 r||n}async function L$(t){return Xt.loadConfig({...t,__strictErrorHandling:!0})}async function Kc(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await Xt.loadConfig(t);else n=await Xt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)_t.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Xt.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function Z$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await Xt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ac(r)))return(await Xt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await Xt.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"&&Ac(i)))return(await Xt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function M$(t,i,r="replace"){let n=new On;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function vi(t,i,r=!1){let n=new In,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=hi.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}function z$(t){let i=at(hi.cwd(),t.configDir),r=at(hi.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!af(pl(n)))Ja(pl(n),{recursive:!0,mode:511});let e=af(i)?Na(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${wy}
|
|
96
|
+
export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
|
|
97
|
+
`;ja(n,f,{mode:438})}function G$(t){let i=null,r=null,n=()=>{if(!r)r=Kc(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)_t.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),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 q$(t){let i=oc(t$.cwd(),t?.configDir||"./config");function r(){if(!Xa(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Qa(i).filter((l)=>e.has(rf(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 o=rf(h).toLowerCase(),u=c.get(l);if(!u){c.set(l,h);continue}let $=rf(u).toLowerCase();if(f.indexOf(o)<f.indexOf($))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 n(){let e=r(),f=e.map((h)=>h.base),s=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
|
|
98
|
+
${e.map((h)=>{let o=oc(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${o}').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:n(),loader:"ts"}})}}}var xc,Li,ir,kc,K$,x$,Ec,wn,wf,st,Z,k$,Tc,D$,gc,b$,V$,sf,p$,Sc,Cc,lf,P$,v$,X$,Q$,mn,Dc,ty,lt,iy,ry,Rc,dn,mf,v,B,ny,Bc,ey,Uc,fy,sy,cf,ly,Fc,Jc,cy,hf,hy,oy,uy,ay,$y,An,bc,yy,wy="0.15.6",Et,Jn,Qi,df,Af,Nn,Ef,Tf,tr,gf,Sf,ei,Vc,pc,_t,Xt,Pc,vc,my=m$(async()=>{xc=import.meta.require,Li=new Bf,ir=new Uf,kc={createKey:d$,isEquivalent:A$,estimateMemoryUsage:E$},K$=Sn($f.cwd(),"config"),x$=Sn($f.cwd(),"src/generated"),Ec=gn.env.CLARITY_LOG_DIR||Ya(S$(),"logs"),wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ec,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},wf=await C$(),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,k$=st.red,Tc=st.green,D$=st.yellow,gc=st.blue,b$=st.magenta,V$=st.cyan,sf=st.white,p$=st.gray,Sc=st.bgRed,Cc=st.bgYellow,lf=st.bold,P$=st.dim,v$=st.italic,X$=st.underline,Q$=st.reset,mn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Dc={debug:"\uD83D\uDD0D",info:gc("ℹ"),success:Tc("✓"),warning:Cc(sf(lf(" WARN "))),error:Sc(sf(lf(" ERROR ")))},ty=new Bn("stacks"),lt=new Bn("bunfig",{showTags:!0}),iy=ut(Xi.cwd(),"config"),ry=ut(Xi.cwd(),"src/generated"),Rc=Tn.env.CLARITY_LOG_DIR||_a(F$(),"logs"),dn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mf=await J$(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},B=v,ny=v.red,Bc=v.green,ey=v.yellow,Uc=v.blue,fy=v.magenta,sy=v.cyan,cf=v.white,ly=v.gray,Fc=v.bgRed,Jc=v.bgYellow,cy=v.bgGray,hf=v.bold,hy=v.dim,oy=v.italic,uy=v.underline,ay=v.strikethrough,$y=v.reset,An={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bc={debug:"\uD83D\uDD0D",info:Uc("ℹ"),success:Bc("✓"),warning:Jc(cf(hf(" WARN "))),error:Fc(cf(hf(" ERROR ")))},yy=new Fn("stacks"),Et=class extends Error{timestamp;context;constructor(i,r={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Jn=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},Qi=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},df=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},Af=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},Nn=class extends Et{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},Ef=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Tf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},tr=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},gf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},Sf=class extends Et{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ei={configNotFound(t,i,r){return new Jn(t,i,r)},configLoad(t,i,r){return new Qi(t,i,r)},configValidation(t,i,r){return new df(t,i,r)},configMerge(t,i,r,n){return new Af(t,i,r,n)},envVar(t,i,r,n){return new Nn(t,i,r,n)},fileSystem(t,i,r){return new Ef(t,i,r)},typeGeneration(t,i,r){return new Tf(t,i,r)},schemaValidation(t,i,r){return new tr(t,i,r)},browserConfig(t,i,r,n){return new gf(t,i,r,n)},plugin(t,i,r){return new Sf(t,i,r)}},Vc={replace:"replace",concat:"concat",smart:"smart"},pc=/^https?:\/\//,_t=new Fn("bunfig",{showTags:!0}),Xt=new _f,Pc=at(hi.cwd(),"config"),vc=at(hi.cwd(),"src/generated")});function dy(t,i={}){let r=Cn.cwd();while(r.includes("storage"))r=uc(r,"..");let n=uc(r,t||"");if(i?.relative)return r$(Cn.cwd(),n);return n}var Ay=Cn.env.CLARITY_LOG_DIR||i$(dy(),"logs"),Xc={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ay,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn={...Xc},yA=(async()=>{try{let{loadConfig:t}=await my().then(()=>Oc),i=await t({name:"clarity",alias:"logging",defaultConfig:Xc,cwd:Cn.cwd()});if(i)Object.assign(jn,i)}catch{}return jn})();function X(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ey(){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 Qc{async format(t){let i=await Ey(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Hi.pid,hostname:i(),environment:Hi.env.NODE_ENV||"development",platform:Hi.platform,version:Hi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Hi.env.NODE_ENV||Hi.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"},F=it,wA=it.red,Ty=it.green,mA=it.yellow,gy=it.blue,dA=it.magenta,AA=it.cyan,Nc=it.white,EA=it.gray,Sy=it.bgRed,Cy=it.bgYellow,TA=it.bgGray,jc=it.bold,gA=it.dim,SA=it.italic,CA=it.underline,RA=it.strikethrough,BA=it.reset,of={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ry={debug:"\uD83D\uDD0D",info:gy("ℹ"),success:Ty("✓"),warning:Cy(Nc(jc(" WARN "))),error:Sy(Nc(jc(" ERROR ")))};class Hn{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={...jn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Qc,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 r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||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},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}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:jn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await l$(this.config.logDirectory,wc.F_OK|wc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await c$(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(!ln(this.currentLogFile))await ff(this.currentLogFile,"",{mode:420});if(e=yc(this.currentLogFile,"a",420),s$(e,l,{flag:"a"}),$c(e),e!==void 0)ef(e),e=void 0;if((await Ii(this.currentLogFile)).size===0){if(await ff(this.currentLogFile,l,{flag:"w",mode:420}),(await Ii(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let o=h;if(o.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(o.code)){if(f<s-1){let u=typeof o.message==="string"?o.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(o?.code&&["ENOSPC","EDQUOT"].includes(o.code))throw Error(`Disk quota exceeded or no space left on device: ${o.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",o),o}finally{if(e!==void 0)try{ef(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let o=l,u=typeof o.message==="string"?o.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((o)=>setTimeout(o,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Oi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Oi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Oi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,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(),r=nf(16),n=n$("aes-256-gcm",i,r),e=bt.isBuffer(t)?t:bt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=bt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=dc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(bt.from(bt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Ii(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 r=this.currentLogFile,n=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 o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ii(r).catch(()=>null))try{if(await mc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await hn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ff(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=r.replace(/\.log$/,`-${e}.log`);if(await Ii(r).catch(()=>null))await mc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await cn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await hn(Oi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=ac(t),n=f$(i),e=dc();await u$(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ln(this.currentLogFile))try{let t=yc(this.currentLogFile,"r+");$c(t),ef(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await hn(Oi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,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()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())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:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=C.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${F.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${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 r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];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(n<i.length)e+=` ${i.slice(n).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,(r,n,e)=>{let f=F.underline(F.blue(n)),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,(r,n)=>F.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>F.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>F.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>F.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>F.strikethrough(n)),i}supportsHyperlinks(){if(X())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 r=C.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(h$(i)||i.startsWith("./")||i.startsWith("../"))i=o$(i);else return null;return ln(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Ry[t],$=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:F.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:F.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
|
|
105
|
+
`);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:F.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
106
|
+
`;if(c)o+=`${c}
|
|
107
|
+
`;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!X()&&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()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!X()&&C.stdout.isTTY)C.stdout.write(`
|
|
108
|
+
`);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":F.blue("◐"),tag:r,message:`${F.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
|
|
109
|
+
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.green("✓"),tag:o,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!X())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}`,r=new Hn(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(r),r}createReadStream(){if(X())throw Error("createReadStream is not supported in browser environments");if(!ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ac(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 r=this.keys.get(this.currentKeyId);try{let n=bt.isBuffer(t)?t:bt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=e$("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=bt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
110
|
+
`),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:F.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(o),showTimestamp:!1}))}else if(!X())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
|
|
111
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();C.stdin.removeListener("data",r);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",r)})}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 r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(o,u)=>{if(u==="%")return"%";if(h>=i.length)return o;let $=i[h++];switch(u){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return o}}),h<i.length)r+=` ${i.slice(h).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${F.blue("◐")} `;console.error(`${h}${l} ${F.cyan(n)}`)}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 r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=F.green("━".repeat(n)),s=F.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=C.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,C.stdout.write(t.lastRenderedLine),i)C.stdout.write(`
|
|
113
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!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(X()){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),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Oi(this.config.logDirectory,n);if(t.before)try{if((await Ii(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await hn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var UA=new Hn("stacks");class Wt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class th extends Wt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class _n extends Wt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class ih extends Wt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class rh extends Wt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wf extends Wt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class nh extends Wt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class eh extends Wt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wn extends Wt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class fh extends Wt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class sh extends Wt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Zi={configNotFound(t,i,r){return new th(t,i,r)},configLoad(t,i,r){return new _n(t,i,r)},configValidation(t,i,r){return new ih(t,i,r)},configMerge(t,i,r,n){return new rh(t,i,r,n)},envVar(t,i,r,n){return new Wf(t,i,r,n)},fileSystem(t,i,r){return new nh(t,i,r)},typeGeneration(t,i,r){return new eh(t,i,r)},schemaValidation(t,i,r){return new Wn(t,i,r)},browserConfig(t,i,r,n){return new fh(t,i,r,n)},plugin(t,i,r){return new sh(t,i,r)}};async function By(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Yf{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,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Rf.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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=un.env[l]||(h?un.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=un.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof Wf)throw u;throw Zi.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))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(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(un.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||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,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.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 r=`Environment Variables for ${i}:
|
|
114
|
+
|
|
115
|
+
`;for(let n of t)r+=`${n.key}
|
|
116
|
+
`,r+=` Type: ${n.type}
|
|
117
|
+
`,r+=` Description: ${n.description}
|
|
118
|
+
`,r+=` Example: ${n.example}
|
|
119
|
+
|
|
120
|
+
`;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
|
|
121
|
+
|
|
122
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
123
|
+
`,r+=`|----------|------|-------------|----------|
|
|
124
|
+
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
125
|
+
`;return r}}function Uy(t,i,r={}){return lh(t,i,r,new WeakMap)}function lh(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;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 ch(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return jy(t,i,r,n)}function ch(t,i,r,n){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(r){case"replace":return i;case"concat":return Fy(t,i);case"smart":return Jy(t,i,n);default:return i}return i}function Fy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Cf(e,n)))r.push(n);return r}function Jy(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return Ny(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Ny(t,i,r){let n=[...i];for(let e of t){if(!Bt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Bt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function jy(t,i,r,n){let e=i;if(Bt(e)&&n.has(e))return n.get(e);let f={...t};if(Bt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=lh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ch(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function hh(t,i,r="replace"){return Uy(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Cf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Cf(t[r],i[r]))return!1;return!0}if(Bt(t)&&Bt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Cf(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class oh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=En.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!an(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new _n(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new _n(t,Error("Configuration must export a valid object"),"unknown");let d={config:hh(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)En.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?Zi.configLoad(t,h):Zi.configLoad(t,Error(String(h)))}};if(s)return Rf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(uf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return By(async()=>{return an(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!an(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=uf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=uf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}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((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!an(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))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(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var Wy=/^https?:\/\//;class uh{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await Rf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!_y(i))throw new Wn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Wn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,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(n.push({path:r,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(n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,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=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.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(n.push({path:r?`${r}.${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=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.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:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,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)n.push({path:r,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)n.push({path:r,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))n.push({path:r,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))n.push({path:r,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)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;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:Wy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Vt=new Hn("bunfig",{showTags:!0});function Yy(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((r)=>`"${r}"`).join(", ")}`}class ah{fileLoader=new oh;envProcessor=new Yf;validator=new uh;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}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 o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))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(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Vt.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 Vt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||Yn.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(Ct(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw Zi.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${Yy(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?$n(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)Vt.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)Vt.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?$n(t,r,e):r,c=[Ct(Ui(),".config",t),Ct(Ui(),".config"),Ui()];for(let l of c){if(e)Vt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)Vt.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?$n(t,n,f):n;try{let l=Ct(r,"package.json");if(!Ua(l))return null;let h={};try{h=JSON.parse(Fa(l,"utf8"))}catch($){if(f)Vt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let o=h[t],u=t;if(!o&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){o=h[a],u=a;break}}}if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)Vt.success(`Configuration loaded from package.json: ${u}`);return{config:hh(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Vt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$n(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(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(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return En.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);En.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.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,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Ct(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Ct(Ui(),".config",t),Ct(Ui(),".config"),Ui()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var _A=new ah;function $n(t,i,r=!1){let n=new Yf,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=Yn.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}var WA=Ct(Yn.cwd(),"config"),YA=Ct(Yn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Iy={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Of(If(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Of(If(),".stacks","ssl","stacks.localhost.crt"),keyPath:Of(If(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var $h=Iy;import{execSync as nr}from"node:child_process";import{homedir as My}from"node:os";import{join as zy}from"node:path";import{execSync as Ln}from"node:child_process";function yh(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Zn(t){try{let i=Ln(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return yh(i)}catch{return null}}function Oy(t){try{return Ln(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function Hy(t,i){try{let r=Ln(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((n)=>r.includes(`DNS:${n}`))}catch{return!1}}function Ly(t,i,r=443){try{return Ln(`echo | openssl s_client -connect ${t}:${r} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function Zy(t){let i=[];for(let r of t.split(`
|
|
126
|
+
`)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var fi="-d -r trustRoot -p ssl -p basic",oi="/Library/Keychains/System.keychain",Hf="rpx.localhost";function er(){return zy(My(),"Library/Keychains/login.keychain-db")}function Lf(){return[oi,er()]}function wh(t,i=Hf){let r=nr(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let e of r.split(`
|
|
127
|
+
`)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function Mn(t){if(process.platform!=="darwin")return;let i=Zn(t.caPath);if(!i)return;let r=t.commonName??Hf,n=t.keychains??Lf();for(let e of n)for(let f of wh(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))rr(`security delete-certificate -Z ${f} "${e}"`);else nr(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});w("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function fr(t,i,r){if(process.platform!=="darwin")return sr(t,r);try{let e=nr(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return w("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,r?.verbose),e}catch{return!1}}function sr(t,i){let r=Zn(t);if(!r)return!1;for(let n of Lf())try{let e=nr(`security find-certificate -a -Z "${n}" 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()===r)return w("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function Zf(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;Mn({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=er();try{nr(`security add-trusted-cert ${fi} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{rr(`security add-trusted-cert ${fi} -k ${oi} "${t}"`)}catch{return!1}return fr(t,r,{verbose:i.verbose})||sr(t,{verbose:i.verbose})}var si=null,Gy="rpx-root-ca.crt",qy="rpx-root-ca.key";function Gf(t){return{caCertPath:Q(t,Gy),caKeyPath:Q(t,qy)}}function f1(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:Gf(t)}}async function Ky(t,i){try{let[r,n]=await Promise.all([k.readFile(t.caCertPath,"utf8"),k.readFile(t.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return w("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:r,privateKey:n}}catch(r){return w("ssl",`No existing Root CA at ${t.caCertPath} (${r.code||r}), will create one`,i),null}}function mh(t){let i=new Set;i.add(t);let r=t.split(".");if(r.length>=2)i.add(`*.${r.slice(1).join(".")}`);return Array.from(i)}function gh(t){let r=zf(t).replace(/\*/g,"wildcard"),n=Q(Gn(),".stacks","ssl"),e=n;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:n,{caCertPath:t.https.caCertPath||Q(e,`${r}.ca.crt`),certPath:t.https.certPath||Q(e,`${r}.crt`),keyPath:t.https.keyPath||Q(e,`${r}.key`)};return{caCertPath:Q(e,`${r}.ca.crt`),certPath:Q(e,`${r}.crt`),keyPath:Q(e,`${r}.key`)}}function dh(t){let i=new Set;if(zn(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";mh(n).forEach((e)=>i.add(e))});else if(Eh(t)){let r=t.to||"rpx.localhost";mh(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function s1(t){w("ssl","Loading SSL configuration",t.verbose);let i={...$h,...t};if(t.https=Kf(i),!t.https?.keyPath&&!t.https?.certPath)return w("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let r=!t.https?.keyPath?"keyPath":"certPath";throw w("ssl",`Invalid SSL configuration - missing ${r}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{w("ssl","Reading SSL certificate files",t.verbose);let r=await k.readFile(t.https?.keyPath,"utf8"),n=await k.readFile(t.https?.certPath,"utf8");return w("ssl","SSL configuration loaded successfully",t.verbose),{key:r,cert:n}}catch(r){return w("ssl",`Failed to read certificates: ${r}`,t.verbose),null}}catch(r){throw w("ssl",`SSL configuration error: ${r}`,t.verbose),r}}async function l1(t,i){if(Yt.platform==="darwin")return xy(t,i);if(Yt.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)n(!0);else r(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function xy(t,i){if(Yt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(fr(t,r,{verbose:n}))return w("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return w("ssl","Trusting Root CA for browsers (login + system keychains)",n),Zf(t,{serverName:r,verbose:n})}catch{return!1}}async function Sh(t){if(si&&!t.forceRegenerate){w("ssl","Using cached SSL configuration",t.verbose);return}ky();let i=zn(t)?t.proxies.map((o)=>o.to):[t.to];w("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=Kf(t,t.verbose),n=r.basePath||Q(Gn(),".stacks","ssl");await k.mkdir(n,{recursive:!0});let e=Gf(n),f=await Ky(e,t.verbose),s=!1;if(!f){if(t.verbose)M.info("Generating Root CA certificate (one-time)...");f=await Ke(r);try{await Promise.all([k.writeFile(e.caCertPath,f.certificate),k.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,w("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(o){throw w("ssl",`Error saving Root CA files: ${o}`,t.verbose),Error(`Failed to save Root CA files: ${o}`)}}else w("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)M.info(`Generating host certificate for: ${i.join(", ")}`);let c=await xe({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([k.writeFile(r.certPath,c.certificate),k.writeFile(r.keyPath,c.privateKey),k.writeFile(r.caCertPath,f.certificate)]),w("ssl","Certificate files saved successfully",t.verbose)}catch(o){throw w("ssl",`Error saving certificate files: ${o}`,t.verbose),Error(`Failed to save certificate files: ${o}`)}if(s?!1:await Ch(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(w("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)M.success("Root CA is already trusted in system trust store");if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)M.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)M.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Yt.platform==="darwin")try{Mn({caPath:e.caCertPath,verbose:t.verbose});let o=er();try{Mi(`security add-trusted-cert ${fi} -k "${o}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(rr(`security add-trusted-cert ${fi} -k ${oi} "${e.caCertPath}"`),t.verbose)M.success("Successfully added Root CA to system trust store");h=!0;let u=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
|
|
129
|
+
echo "Trusting RPX Root CA"
|
|
130
|
+
sudo security add-trusted-cert ${fi} -k ${oi} "${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 k.writeFile(u,$,{mode:493})}catch(o){if(t.verbose)M.warn(`Could not add Root CA to trust store automatically: ${o}`);let u=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
|
|
134
|
+
echo "Trusting RPX Root CA"
|
|
135
|
+
sudo security add-trusted-cert ${fi} -k ${oi} "${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 k.writeFile(u,$,{mode:493}),t.verbose)M.info(`Created a trust helper script at: ${u}`),M.info(`If you're still having certificate issues, run: sh ${u}`)}else if(Yt.platform==="linux")try{let{exec:o}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",$=`
|
|
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
|
+
`,a=Q(Mf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await k.writeFile(a,$,{mode:493}),await new Promise((m)=>{o(`sudo bash "${a}"`,(y)=>{if(y){if(t.verbose)M.warn(`Could not trust certificates: ${y}`);m(!1)}else{if(t.verbose)M.success("Successfully added certificates to system trust store");m(!0)}})}),await k.unlink(a).catch(()=>{}),h=!0}catch(o){if(t.verbose)M.warn(`Failed to trust certificates: ${o}`)}else if(Yt.platform==="win32")try{let o=`
|
|
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
|
+
`,u=Q(Mf.tmpdir(),"rpx-trust.ps1");if(await k.writeFile(u,o),Mi(`powershell -ExecutionPolicy Bypass -File "${u}"`),t.verbose)M.success("Successfully added certificate to Windows trust store");h=!0}catch(o){if(t.verbose)M.warn(`Could not trust certificate: ${o}`)}else try{await ke(c,f.certificate,r),h=!0}catch(o){if(t.verbose)M.warn(`Could not add certificate to trust store: ${o}`)}if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)M.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)M.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),M.warn("This will bypass the warning and you should only need to do it once")}function ky(){si=null}async function qf(t){if(!t)return null;if(si)return si;let i=Kf(t);try{let[r,n,e]=await Promise.all([k.access(i.keyPath).then(()=>!0).catch(()=>!1),k.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?k.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return w("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;w("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||Q(Gn(),".stacks","ssl"),h=Gf(l);if(!(c?await Ch(h.caCertPath,t):!0))return w("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[u,$,a]=await Promise.all([k.readFile(i.keyPath,"utf8"),k.readFile(i.certPath,"utf8"),e&&i.caCertPath?k.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(a&&!a.includes("-----BEGIN CERTIFICATE-----"))return w("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(zn(t))try{let{X509Certificate:m}=await import("node:crypto"),d=new m($).subjectAltName||"",g=t.proxies.map((I)=>I.to).filter((I)=>!d.includes(`DNS:${I}`));if(g.length>0)return w("ssl",`Certificate missing SANs for: ${g.join(", ")}, will regenerate`,t.verbose),null}catch(m){w("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return w("ssl","Successfully loaded existing certificates",t.verbose),si={key:u,cert:$,ca:a},si}catch(r){return w("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function Kf(t,i){let r=zf(t);w("ssl",`Primary domain: ${r}`,i);let n=gh(t),e=Q(Gn(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,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(dh(t)).map((c)=>({type:2,value:c}))};if(Ah(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(dh(t)).map((f)=>({type:2,value:f}))}}async function c1(t,i){let r=gh({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];w("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>Th(e,i)))}async function Ch(t,i){try{if(w("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Yt.platform==="darwin"){if(i?.serverName)return fr(t,i.serverName,{verbose:i.verbose});return sr(t,{verbose:i.verbose})}else if(Yt.platform==="win32")try{let n=Mi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!n)return w("ssl","Could not extract certificate subject",i?.verbose),!1;let e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(Mi(e).toString().includes(n))return w("ssl","Certificate found in trusted root store",i?.verbose),!0;return w("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return w("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Yt.platform==="linux")try{let n=Mi(`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(Mi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${n}"`).toString().includes(n))return w("ssl",`Certificate fingerprint found in ${f}`,i?.verbose),!0}catch{}return w("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return w("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return w("ssl",`Platform ${Yt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return w("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}function Bh(t,i){return async(r)=>{let n=new URL(r.url),f=(r.headers.get("host")||"").split(":")[0],s=t(f);if(!s)return w("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});let c=s.sourceHost,l=n.pathname,h=Rh(n.pathname,s.pathRewrites);if(h)c=h.targetHost,l=h.targetPath,w("request",`Path rewrite: ${n.pathname} → ${c}${l}`,i);let o=`http://${c}${l}${n.search}`;try{let u=new Headers(r.headers);if(u.set("host",c),s.changeOrigin)u.set("origin",`http://${s.sourceHost}`);u.set("x-forwarded-for","127.0.0.1"),u.set("x-forwarded-proto","https"),u.set("x-forwarded-host",f);let $=await fetch(o,{method:r.method,headers:u,body:r.body,redirect:"manual"});if(s.cleanUrls&&n.pathname.endsWith(".html")){let m=n.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let a=new Headers($.headers);return new Response($.body,{status:$.status,statusText:$.statusText,headers:a})}catch(u){return w("request",`Proxy error for ${f}: ${u}`,i),new Response(`Proxy Error: ${u}`,{status:502})}}}import*as qn from"node:fs";import*as $t from"node:fs/promises";import{homedir as Dy}from"node:os";import*as xf from"node:path";import*as Kn from"node:process";var by=/^[a-zA-Z0-9._-]+$/;function Gi(){return xf.join(Dy(),".stacks","rpx","registry.d")}function kf(t){return typeof t==="string"&&t.length>0&&t.length<=128&&by.test(t)}function Df(t,i){if(!kf(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return xf.join(t,`${i}.json`)}function Ht(t){if(!Number.isInteger(t)||t<=0)return!1;try{return Kn.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Uh(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&kf(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&r&&typeof i.createdAt==="string"}async function Vy(t){await $t.mkdir(t,{recursive:!0})}async function d1(t,i=Gi(),r){if(!Uh(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await Vy(i);let n=Df(i,t.id),e=`${n}.tmp.${Kn.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await $t.writeFile(e,f,{encoding:"utf8",mode:420}),await $t.rename(e,n),w("registry",`wrote entry ${t.id} → ${n}`,r)}catch(s){throw await $t.unlink(e).catch(()=>{}),s}}async function py(t,i=Gi(),r){let n=Df(i,t);try{await $t.unlink(n),w("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function Py(t,i=Gi(),r){let n=Df(i,t);try{let e=await $t.readFile(n,"utf8"),f=JSON.parse(e);if(!Uh(f))return w("registry",`entry ${t} failed validation, removing`,r),await $t.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return w("registry",`entry ${t} has invalid JSON, removing`,r),await $t.unlink(n).catch(()=>{}),null;throw e}}async function zi(t=Gi(),i){let r;try{r=await $t.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!kf(f))continue;let s=await Py(f,t,i);if(s)n.push(s)}return n}async function bf(t=Gi(),i){let r=await zi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!Ht(e.pid))w("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await py(e.id,t,i).catch(()=>{}),n++}return n}function Fh(t,i={}){let r=i.dir??Gi(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;qn.mkdirSync(r,{recursive:!0});let s=null,c=!1,l=null,h=!1,o=(d)=>{return JSON.stringify(d.map((A)=>({id:A.id,from:A.from,to:A.to,pid:A.pid,pathRewrites:A.pathRewrites,cleanUrls:A.cleanUrls,changeOrigin:A.changeOrigin})).sort((A,g)=>A.id.localeCompare(g.id)))},u=()=>{if(s=null,c)return;zi(r,f).then((d)=>{return l=o(d),t(d)}).catch((d)=>{w("registry",`watcher onChange failed: ${d}`,f)})},$=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(u,n)},m=setInterval(()=>{if(c||h)return;h=!0,zi(r,f).then((d)=>{if(o(d)!==l)$()}).catch((d)=>{w("registry",`watcher poll failed: ${d}`,f)}).finally(()=>{h=!1})},e),y=qn.watch(r,{persistent:!0},(d,A)=>{if(A&&/\.tmp\.\d+\.\d+$/.test(A))return;$()});return y.on("error",(d)=>{w("registry",`watcher error: ${d}`,f)}),$(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),y.close()}}}var Xy=5000;function yt(){return It.join(Jh(),".stacks","rpx")}function pf(t=yt()){return It.join(t,"daemon.pid")}async function cr(t=yt()){try{let i=await Lt.readFile(pf(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Qy(t=yt()){let i=await cr(t);return i!==null&&Ht(i)}async function tw(t=yt()){await Lt.mkdir(t,{recursive:!0});let i=pf(t);while(!0){try{let n=await Lt.open(i,"wx");try{await n.write(`${D.pid}
|
|
151
|
+
`)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await cr(t);if(r!==null&&Ht(r))throw Error(`rpx daemon already running (pid=${r})`);await Lt.unlink(i).catch(()=>{})}}async function lr(t=yt()){await Lt.unlink(pf(t)).catch(()=>{})}function iw(t){return{sourceHost:new URL(t.from.startsWith("http")?t.from:`http://${t.from}`).host,cleanUrls:t.cleanUrls??!1,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function rw(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function nw(t,i){let r=await zi(i,t.verbose),n=[...new Set(r.map((o)=>o.to))],e=rw(n),f=[...new Set([e,...n,"rpx.localhost"])],s=It.join(Jh(),".stacks","ssl"),c=It.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:It.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:It.join(s,"rpx.localhost.key"),caCertPath:It.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((o)=>({from:"localhost:1",to:o}))}:{to:e,from:"localhost:1"}},h=await qf(l);if(!h)w("daemon","no usable cert on disk, generating one",t.verbose),await Sh(l),h=await qf(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function J1(t={}){let i=t.verbose??!1,r=t.rpxDir??yt(),n=t.registryDir??It.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??Xy,l=await tw(r),h=new Map,o=(J)=>h.get(J);function u(J){let Ot=new Map;for(let ar of J)Ot.set(ar.to,iw(ar));h=Ot,w("daemon",`routing table now covers ${Ot.size} host(s): ${Array.from(Ot.keys()).join(", ")||"<empty>"}`,i)}await bf(n,i).catch((J)=>{w("daemon",`initial gc failed: ${J}`,i)});let $=await zi(n,i);u($),await or({rpxDir:r,verbose:i}).catch((J)=>{w("daemon",`DNS reconcile on start failed: ${J}`,i)}),await Vf($,{rpxDir:r,verbose:i,ownerPid:D.pid}).catch((J)=>{w("daemon",`DNS setup on start failed: ${J}`,i)});let a=await nw(t,n),m=Bun.serve({port:e,hostname:s,tls:{key:a.key,cert:a.cert,ca:a.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Bh(o,i),error(J){return w("daemon",`https server error: ${J}`,i),new Response(`Server Error: ${J.message}`,{status:500})}}),y=null;if(f>0)y=Bun.serve({port:f,hostname:s,fetch(J){let Ot=new URL(J.url),ar=(J.headers.get("host")??Ot.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${ar}${Ot.pathname}${Ot.search}`}})}});if(i)M.success(`rpx daemon listening on https://${s}:${e}${y?` (http→https on :${f})`:""}`),M.info(`pid file: ${l}`),M.info(`registry: ${n}`);let d=Fh((J)=>{u(J),Vf(J,{rpxDir:r,verbose:i,ownerPid:D.pid}).catch((Ot)=>{w("daemon",`DNS sync on registry change failed: ${Ot}`,i)})},{dir:n,verbose:i}),A=setInterval(()=>{bf(n,i).then((J)=>{if(J>0)w("daemon",`gc reaped ${J} stale entries`,i)}).catch((J)=>{w("daemon",`periodic gc failed: ${J}`,i)})},c);if(typeof A.unref==="function")A.unref();let g=!1,I,O=new Promise((J)=>{I=J});async function H(){if(g)return O;if(g=!0,clearInterval(A),d.close(),m.stop(!1),y?.stop(!1),await hr({rpxDir:r,verbose:i}).catch((J)=>{w("daemon",`DNS teardown failed: ${J}`,i)}),await lr(r),i)M.info("rpx daemon stopped");return I(),O}let qi=(J)=>{w("daemon",`received ${J}, shutting down`,i),H().catch(()=>{})};return D.once("SIGINT",qi),D.once("SIGTERM",qi),{stop:H,done:O,httpsPort:typeof m.port==="number"?m.port:e,httpPort:y&&typeof y.port==="number"?y.port:f,pidPath:l}}function ew(){let t=D.execPath,i=It.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&D.argv[1])return[t,D.argv[1],"daemon:start"];return[t,"daemon:start"]}async function N1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1;await or({rpxDir:i,verbose:r}).catch((o)=>{w("daemon",`DNS reconcile before ensureDaemonRunning: ${o}`,r)});let n=await cr(i);if(n!==null&&Ht(n))return w("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)w("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await lr(i);await Lt.mkdir(i,{recursive:!0});let e=t.spawnCommand??ew();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");w("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=vy(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??D.cwd(),env:t.spawnEnv?{...D.env,...t.spawnEnv}:D.env});f.unref();let s=null;f.once("error",(o)=>{s=o});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let o=await cr(i);if(o!==null&&Ht(o))return w("daemon",`daemon registered with pid=${o}`,r),{pid:o,spawned:!0};await new Promise((u)=>setTimeout(u,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function j1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await cr(i);if(s===null||!Ht(s)){if(s!==null)await lr(i);return await or({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{D.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await lr(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+n;while(Date.now()<c){if(!Ht(s))return w("daemon",`daemon pid=${s} stopped cleanly`,r),{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 ${n}ms`);w("daemon",`daemon pid=${s} did not exit, escalating to SIGKILL`,r);try{D.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await lr(i),await hr({rpxDir:i,verbose:r}).catch((l)=>{w("daemon",`DNS teardown after SIGKILL: ${l}`,r)}),{stopped:!0,pid:s,forced:!0}}async function _1(t={}){let i=t.rpxDir??yt();if(await Qy(i))return;await or({rpxDir:i,verbose:t.verbose})}import*as li from"node:fs/promises";import{homedir as fw}from"node:os";import*as Pf from"node:path";var xn=1,sw="dns-state.json",Nh=["com","test","dev","app","page","local","localhost","example","invalid"];function jh(){return Pf.join(fw(),".stacks","rpx")}function vf(t=jh()){return Pf.join(t,sw)}async function kn(t=jh()){try{let i=await li.readFile(vf(t),"utf8"),r=JSON.parse(i);if(r.version!==xn||!Array.isArray(r.resolvers))return null;return{version:xn,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _h(t,i){await li.mkdir(t,{recursive:!0}),await li.writeFile(vf(t),`${JSON.stringify(i,null,2)}
|
|
152
|
+
`,"utf8")}async function Xf(t){await li.rm(vf(t),{force:!0})}function Wh(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 lw(t){let i=Wh(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function Qf(t){let i=new Set;for(let r of t){let n=lw(r);if(n)i.add(n)}return Array.from(i).sort()}function ts(t){let i=new Set;for(let r of t){let n=Wh(r);if(n)i.add(n)}return Array.from(i).sort()}var is=15353,hw="# managed-by: rpx",Oh="/etc/resolver",wt=null,Dn=new Set;function ow(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 Hh(t,i){let r=[],n=i;while(!0){let e=t[n];if(e===0){n++;break}if((e&192)===192){let f=t.readUInt16BE(n)&16383,{name:s}=Hh(t,f);r.push(s),n+=2;break}n++,r.push(t.subarray(n,n+e).toString("ascii")),n+=e}return{name:r.join("."),newOffset:n}}function uw(t,i){let{name:r,newOffset:n}=Hh(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function bn(t){let i=t.split("."),r=[];for(let n of i)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function aw(t,i,r){let n=[],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),n.push(e),n.push(bn(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(bn(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),n.push(s);let c=r.split(".").map((l)=>Number.parseInt(l,10));n.push(Buffer.from(c))}else if(i.type===28)s.writeUInt16BE(16,8),n.push(s),n.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,bn(i.name),f]);return Buffer.concat(n)}function $w(t,i){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(t,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(bn(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),r.push(e),Buffer.concat(r)}async function yw(t,i){if(Qt.platform!=="darwin")return!1;let r=ts(t);if(r.length===0)return!1;if(wt){for(let n of r)Dn.add(n);return w("dns","DNS server already running — merged domains",i),!0}return Dn=new Set(r),new Promise((n)=>{wt=cw.createSocket("udp4"),wt.on("error",(e)=>{w("dns",`DNS server error: ${e.message}`,i),wt?.close(),wt=null,n(!1)}),wt.on("message",(e,f)=>{try{let s=ow(e),{question:c}=uw(e,12);w("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let u of Dn)if(l===u||l.endsWith(`.${u}`)){h=!0;break}let o;if(h&&(c.type===1||c.type===28))o=aw(s.id,c,"127.0.0.1"),w("dns",`Responding with localhost for ${c.name}`,i);else o=$w(s.id,c),w("dns",`NXDOMAIN for ${c.name}`,i);wt?.send(o,f.port,f.address)}catch(s){w("dns",`Error processing DNS query: ${s}`,i)}}),wt.on("listening",()=>{let e=wt?.address();w("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),n(!0)});try{wt.bind(is,"127.0.0.1")}catch(e){w("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function Lh(t){if(wt)w("dns","Stopping DNS server",t),wt.close(),wt=null,Dn=new Set}function z1(){return wt!==null}function ww(){return`${hw}
|
|
153
|
+
nameserver 127.0.0.1
|
|
154
|
+
port ${is}
|
|
155
|
+
`}function ur(t){return Ih.join(Oh,t)}function mw(t){return t.includes("127.0.0.1")&&t.includes(String(is))}async function dw(t){try{return await Yh.readFile(ur(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function rs(t){if(Qt.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r()){w("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),w("dns","DNS cache flushed",t)}catch(n){w("dns",`Could not flush DNS cache: ${n}`,t)}}async function Aw(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js"),n=ww().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Oh} && printf "%b" "${n}" > ${ur(t)}'`;r(e),w("dns",`Created ${ur(t)}`,i)}async function Ew(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js");r(`rm -f ${ur(t)}`),w("dns",`Removed ${ur(t)}`,i)}async function G1(t,i){return Mh({domains:i??[],verbose:t})}async function Tw(t,i){if(Qt.platform!=="darwin")return!0;let{getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r())return w("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let n of t)await Aw(n,i);return await rs(i),!0}catch(n){return w("dns",`Failed to create resolver file: ${n}`,i),!1}}async function ns(t,i){if(Qt.platform!=="darwin")return;let{getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r())return;try{for(let n of t)await Ew(n,i);await rs(i)}catch(n){w("dns",`Failed to remove resolver files: ${n}`,i)}}async function Zh(t){if(Qt.platform!=="darwin")return[];let i=[];for(let r of Nh){let n=await dw(r);if(n&&mw(n))await ns([r],t),i.push(r)}return i}async function Mh(t){let i=t.rpxDir??yt(),r=ts(t.domains);if(r.length===0)return!1;let n=Qf(r);if(!await yw(r,t.verbose))return!1;if(!await Tw(n,t.verbose))return!1;let s={version:xn,resolvers:n,domains:r,ownerPid:t.ownerPid??Qt.pid,updatedAt:new Date().toISOString()};return await _h(i,s),!0}async function Vf(t,i={}){let r=t.map((l)=>l.to).filter(Boolean),n=i.rpxDir??yt(),e=Qf(r),c=((await kn(n))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await ns(c,i.verbose);if(e.length===0){Lh(i.verbose),await Xf(n);return}await Mh({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??Qt.pid})}async function hr(t={}){let i=t.rpxDir??yt();Lh(t.verbose);let n=(await kn(i))?.resolvers??[];await ns(n,t.verbose),await Zh(t.verbose),await Xf(i)}async function q1(t){await hr({verbose:t})}async function or(t={}){let i=t.rpxDir??yt(),r=await kn(i),n=r?.ownerPid!=null&&Ht(r.ownerPid);if(r&&!n){w("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,t.verbose),await hr(t);return}let e=await Zh(t.verbose);if(e.length>0)w("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await rs(t.verbose)}
|
|
156
|
+
export{M as a,$h as b,yh as c,Zn as d,Oy as e,Hy as f,Ly as g,Zy as h,fi as i,oi as j,Hf as k,er as l,Lf as m,wh as n,Mn as o,fr as p,sr as q,Zf as r,Gf as s,f1 as t,s1 as u,l1 as v,Sh as w,ky as x,qf as y,Kf as z,c1 as A,Ch as B,Bh as C,Gi as D,kf as E,Ht as F,d1 as G,py as H,Py as I,zi as J,bf as K,Fh as L,xn as M,Nh as N,Wh as O,lw as P,Qf as Q,ts as R,is as S,hw as T,yw as U,Lh as V,z1 as W,ur as X,mw as Y,G1 as Z,Zh as _,Mh as $,Vf as aa,hr as ba,q1 as ca,or as da,yt as ea,pf as fa,cr as ga,Qy as ha,tw as ia,lr as ja,J1 as ka,ew as la,N1 as ma,j1 as na,_1 as oa};
|